id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
26,081
NtQuerySystemInformation_SystemKernelDebuggerInformation.h
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQuerySystemInformation_SystemKernelDebuggerInformation.h
#pragma once BOOL NtQuerySystemInformation_SystemKernelDebuggerInformation(); typedef struct _SYSTEM_KERNEL_DEBUGGER_INFORMATION { BOOLEAN KernelDebuggerEnabled; BOOLEAN KernelDebuggerNotPresent; } SYSTEM_KERNEL_DEBUGGER_INFORMATION, *PSYSTEM_KERNEL_DEBUGGER_INFORMATION;
275
C++
.h
7
37.857143
75
0.88015
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,083
ScanForModules.h
LordNoteworthy_al-khaser/al-khaser/AntiDebug/ScanForModules.h
#pragma once BOOL ScanForModules_EnumProcessModulesEx_32bit(); BOOL ScanForModules_EnumProcessModulesEx_64bit(); BOOL ScanForModules_EnumProcessModulesEx_All(); BOOL ScanForModules_ToolHelp32(); BOOL ScanForModules_LDR_Direct(); BOOL ScanForModules_LdrEnumerateLoadedModules(); BOOL ScanForModules_MemoryWalk_GMI(); BOOL ScanForModules_MemoryWalk_Hidden(); BOOL ScanForModules_DotNetModuleStructures();
404
C++
.h
10
39.3
49
0.86514
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,084
WriteWatch.h
LordNoteworthy_al-khaser/al-khaser/AntiDebug/WriteWatch.h
#pragma once BOOL VirtualAlloc_WriteWatch_BufferOnly(); BOOL VirtualAlloc_WriteWatch_APICalls(); BOOL VirtualAlloc_WriteWatch_IsDebuggerPresent(); BOOL VirtualAlloc_WriteWatch_CodeWrite();
189
C++
.h
5
36.8
49
0.858696
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,085
ParentProcess.h
LordNoteworthy_al-khaser/al-khaser/AntiDebug/ParentProcess.h
#pragma once typedef struct _ALK_PROCESS_BASIC_INFORMATION { PVOID Reserved1; void* PebBaseAddress; PVOID Reserved2[2]; ULONG_PTR UniqueProcessId; ULONG_PTR ParentProcessId; } ALK_PROCESS_BASIC_INFORMATION; BOOL IsParentExplorerExe();
241
C++
.h
9
25.111111
47
0.82684
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,086
NtQueryObject_ObjectInformation.h
LordNoteworthy_al-khaser/al-khaser/AntiDebug/NtQueryObject_ObjectInformation.h
#pragma once BOOL NtQueryObject_ObjectAllTypesInformation(); BOOL NtQueryObject_ObjectTypeInformation(); #define DEBUG_READ_EVENT 0x0001 #define DEBUG_PROCESS_ASSIGN 0x0002 #define DEBUG_SET_INFORMATION 0x0004 #define DEBUG_QUERY_INFORMATION 0x0008 #define DEBUG_ALL_ACCESS (STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE | \ DEBUG_READ_EVENT | DEBUG_PROCESS_ASSIGN | DEBUG_SET_INFORMATION | \ DEBUG_QUERY_INFORMATION) typedef struct _OBJECT_TYPE_INFORMATION { UNICODE_STRING TypeName; ULONG TotalNumberOfHandles; ULONG TotalNumberOfObjects; }OBJECT_TYPE_INFORMATION, *POBJECT_TYPE_INFORMATION; typedef struct _OBJECT_ALL_INFORMATION { ULONG NumberOfObjects; OBJECT_TYPE_INFORMATION ObjectTypeInformation[1]; }OBJECT_ALL_INFORMATION, *POBJECT_ALL_INFORMATION;
769
C++
.h
19
38.578947
71
0.831099
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,087
VirtualBox.h
LordNoteworthy_al-khaser/al-khaser/AntiVM/VirtualBox.h
#pragma once VOID vbox_reg_key_value(); VOID vbox_reg_keys(); VOID vbox_files(); BOOL vbox_dir(); BOOL vbox_check_mac(); VOID vbox_devices(); BOOL vbox_window_class(); BOOL vbox_network_share(); VOID vbox_processes(); BOOL vbox_mac_wmi(); BOOL vbox_eventlogfile_wmi(); BOOL vbox_firmware_SMBIOS(); BOOL vbox_firmware_ACPI(); BOOL vbox_bus_wmi(); BOOL vbox_baseboard_wmi(); BOOL vbox_pnpentity_pcideviceid_wmi(); BOOL vbox_pnpentity_controllers_wmi(); BOOL vbox_pnpentity_vboxname_wmi();
489
C++
.h
19
24.631579
38
0.764957
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,088
Services.h
LordNoteworthy_al-khaser/al-khaser/AntiVM/Services.h
#pragma once BOOL VMDriverServices(); BOOL get_services(_In_ SC_HANDLE hServiceManager, _In_ DWORD serviceType, _Out_ ENUM_SERVICE_STATUS_PROCESS** servicesBuffer, _Out_ DWORD* serviceCount);
193
C++
.h
3
63
153
0.78836
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,089
Generic.h
LordNoteworthy_al-khaser/al-khaser/AntiVM/Generic.h
#pragma once VOID loaded_dlls(); VOID known_file_names(); VOID known_usernames(); VOID known_hostnames(); VOID other_known_sandbox_environment_checks(); BOOL NumberOfProcessors(); BOOL idt_trick(); BOOL ldt_trick(); BOOL gdt_trick(); BOOL str_trick(); BOOL number_cores_wmi(); BOOL disk_size_wmi(); BOOL setupdi_diskdrive(); BOOL mouse_movement(); BOOL lack_user_input(); BOOL memory_space(); BOOL dizk_size_deviceiocontrol(); BOOL disk_size_getdiskfreespace(); BOOL accelerated_sleep(); BOOL cpuid_is_hypervisor(); BOOL cpuid_hypervisor_vendor(); BOOL serial_number_bios_wmi(); BOOL model_computer_system_wmi(); BOOL manufacturer_computer_system_wmi(); BOOL current_temperature_acpi_wmi(); BOOL process_id_processor_wmi(); BOOL power_capabilities(); BOOL hybridanalysismacdetect(); BOOL cpu_fan_wmi(); BOOL caption_video_controller_wmi(); BOOL query_license_value(); BOOL cachememory_wmi(); BOOL physicalmemory_wmi(); BOOL memorydevice_wmi(); BOOL memoryarray_wmi(); BOOL voltageprobe_wmi(); BOOL portconnector_wmi(); BOOL smbiosmemory_wmi(); BOOL perfctrs_thermalzoneinfo_wmi(); BOOL cim_memory_wmi(); BOOL cim_numericsensor_wmi(); BOOL cim_physicalconnector_wmi(); BOOL cim_sensor_wmi(); BOOL cim_slot_wmi(); BOOL cim_temperaturesensor_wmi(); BOOL cim_voltagesensor_wmi(); BOOL pirated_windows(); BOOL registry_services_disk_enum(); BOOL registry_disk_enum(); BOOL number_SMBIOS_tables();
1,392
C++
.h
51
26.294118
46
0.785981
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,090
VMWare.h
LordNoteworthy_al-khaser/al-khaser/AntiVM/VMWare.h
#pragma once VOID vmware_reg_key_value(); VOID vmware_reg_keys(); VOID vmware_files(); BOOL vmware_dir(); VOID vmware_mac(); BOOL vmware_adapter_name(); VOID vmware_devices(); VOID vmware_processes(); BOOL vmware_firmware_SMBIOS(); BOOL vmware_firmware_ACPI();
261
C++
.h
11
22.727273
30
0.768
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,091
Qemu.h
LordNoteworthy_al-khaser/al-khaser/AntiVM/Qemu.h
#pragma once VOID qemu_reg_key_value(); VOID qemu_processes(); VOID qemu_dir(); BOOL qemu_firmware_ACPI(); BOOL qemu_firmware_SMBIOS();
137
C++
.h
6
21.666667
28
0.761538
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,092
AntiDisassm.h
LordNoteworthy_al-khaser/al-khaser/AntiDisassm/AntiDisassm.h
#pragma once VOID AntiDisassmConstantCondition(); VOID AntiDisassmAsmJmpSameTarget(); VOID AntiDisassmImpossibleDiasassm(); VOID AntiDisassmFunctionPointer(); VOID AntiDisassmReturnPointerAbuse(); VOID AntiDisassmSEHMisuse();
226
C++
.h
7
31.285714
37
0.881279
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,094
WinStructs.h
LordNoteworthy_al-khaser/al-khaser/Shared/WinStructs.h
#pragma once typedef struct _LDR_MODULE { LIST_ENTRY InLoadOrderModuleList; LIST_ENTRY InMemoryOrderModuleList; LIST_ENTRY InInitializationOrderModuleList; PVOID BaseAddress; PVOID EntryPoint; ULONG SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; ULONG Flags; SHORT LoadCount; SHORT TlsIndex; LIST_ENTRY HashTableEntry; ULONG TimeDateStamp; } LDR_MODULE, *PLDR_MODULE; typedef LONG KPRIORITY; typedef struct _THREAD_BASIC_INFORMATION { NTSTATUS ExitStatus; PVOID TebBaseAddress; CLIENT_ID ClientId; KAFFINITY AffinityMask; KPRIORITY Priority; KPRIORITY BasePriority; } THREAD_BASIC_INFORMATION, *PTHREAD_BASIC_INFORMATION; typedef struct _PROCESS_BASIC_INFORMATION_WOW64 { PVOID Reserved1[2]; PVOID64 PebBaseAddress; PVOID Reserved2[4]; ULONG_PTR UniqueProcessId[2]; PVOID Reserved3[2]; } PROCESS_BASIC_INFORMATION_WOW64; typedef struct _PEB64 { BYTE Reserved1[2]; BYTE BeingDebugged; BYTE Reserved2[1]; PVOID64 Reserved3[2]; PVOID64 Ldr; PVOID64 ProcessParameters; BYTE Reserved4[104]; PVOID64 Reserved5[52]; PVOID64 PostProcessInitRoutine; BYTE Reserved6[128]; PVOID64 Reserved7[1]; ULONG SessionId; } PEB64, *PPEB64; typedef struct _PEB_LDR_DATA64 { BYTE Reserved1[8]; PVOID64 Reserved2[3]; LIST_ENTRY64 InMemoryOrderModuleList; } PEB_LDR_DATA64, *PPEB_LDR_DATA64; typedef struct _UNICODE_STRING64 { USHORT Length; USHORT MaximumLength; PVOID64 Buffer; } UNICODE_STRING64; typedef struct _LDR_DATA_TABLE_ENTRY64 { PVOID64 Reserved1[2]; LIST_ENTRY64 InMemoryOrderLinks; PVOID64 Reserved2[2]; PVOID64 DllBase; PVOID64 Reserved3[2]; UNICODE_STRING64 FullDllName; BYTE Reserved4[8]; PVOID64 Reserved5[3]; union { ULONG CheckSum; PVOID64 Reserved6; } DUMMYUNIONNAME; ULONG TimeDateStamp; } LDR_DATA_TABLE_ENTRY64, *PLDR_DATA_TABLE_ENTRY64; /*++ NtCreateThreadEx specific */ typedef struct _PS_ATTRIBUTE { ULONG Attribute; SIZE_T Size; union { ULONG Value; PVOID ValuePtr; } u1; PSIZE_T ReturnLength; } PS_ATTRIBUTE, *PPS_ATTRIBUTE; typedef struct _PS_ATTRIBUTE_LIST { SIZE_T TotalLength; PS_ATTRIBUTE Attributes[1]; } PS_ATTRIBUTE_LIST, *PPS_ATTRIBUTE_LIST; #define PS_ATTRIBUTE_NUMBER_MASK 0x0000ffff #define PS_ATTRIBUTE_THREAD 0x00010000 #define PS_ATTRIBUTE_INPUT 0x00020000 #define PS_ATTRIBUTE_ADDITIVE 0x00040000 #define PsAttributeValue(Number, Thread, Input, Additive) \ (((Number) & PS_ATTRIBUTE_NUMBER_MASK) | \ ((Thread) ? PS_ATTRIBUTE_THREAD : 0) | \ ((Input) ? PS_ATTRIBUTE_INPUT : 0) | \ ((Additive) ? PS_ATTRIBUTE_ADDITIVE : 0)) typedef enum _PS_ATTRIBUTE_NUM { PsAttributeClientId = 3, } PS_ATTRIBUTE_NUM; #define PS_ATTRIBUTE_CLIENT_ID \ PsAttributeValue(PsAttributeClientId, TRUE, FALSE, FALSE) /* NtCreateThreadEx specific --*/ typedef struct _SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION { ULONG NumberOfLogicalProcessors; ULONG NumberOfCores; } SYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION, *PSYSTEM_HYPERVISOR_PROCESSOR_COUNT_INFORMATION; typedef struct _OBJECT_DIRECTORY_INFORMATION { UNICODE_STRING Name; UNICODE_STRING TypeName; } OBJECT_DIRECTORY_INFORMATION, *POBJECT_DIRECTORY_INFORMATION; typedef VOID(NTAPI LDR_ENUM_CALLBACK)(_In_ PLDR_DATA_TABLE_ENTRY ModuleInformation, _In_ PVOID Parameter, _Out_ BOOLEAN *Stop); typedef LDR_ENUM_CALLBACK *PLDR_ENUM_CALLBACK;
3,603
C++
.h
113
29.982301
127
0.736023
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,095
ApiTypeDefs.h
LordNoteworthy_al-khaser/al-khaser/Shared/ApiTypeDefs.h
#pragma once typedef DWORD(NTAPI* pCsrGetId)(VOID); typedef BOOL(WINAPI* pEnumProcessModulesEx)( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded, DWORD dwFilterFlag); typedef UINT(WINAPI* pEnumSystemFirmwareTables)(DWORD, PVOID, DWORD); typedef DWORD(WINAPI* pGetActiveProcessorCount)(WORD); typedef UINT(WINAPI* pGetSystemFirmwareTable)(DWORD, DWORD, PVOID, DWORD); typedef void (WINAPI *pGetNativeSystemInfo)(LPSYSTEM_INFO); typedef BOOL(WINAPI *pGetProductInfo)(DWORD, DWORD, DWORD, DWORD, PDWORD); typedef BOOL(WINAPI *pIsWow64Process) (HANDLE, PBOOL); typedef DWORD(WINAPI * pRtlCreateUserThread)( IN HANDLE ProcessHandle, IN PSECURITY_DESCRIPTOR SecurityDescriptor, IN BOOL CreateSuspended, IN ULONG StackZeroBits, IN OUT PULONG StackReserved, IN OUT PULONG StackCommit, IN LPVOID StartAddress, IN LPVOID StartParameter, OUT HANDLE ThreadHandle, OUT LPVOID ClientID ); typedef NTSTATUS(WINAPI* pNtClose)(HANDLE); typedef enum _SYSDBG_COMMAND { SysDbgQueryModuleInformation, SysDbgQueryTraceInformation, SysDbgSetTracepoint, SysDbgSetSpecialCall, SysDbgClearSpecialCalls, SysDbgQuerySpecialCalls, SysDbgBreakPoint, SysDbgQueryVersion, SysDbgReadVirtual, SysDbgWriteVirtual, SysDbgReadPhysical, SysDbgWritePhysical, SysDbgReadControlSpace, SysDbgWriteControlSpace, SysDbgReadIoSpace, SysDbgWriteIoSpace, SysDbgReadMsr, SysDbgWriteMsr, SysDbgReadBusData, SysDbgWriteBusData, SysDbgCheckLowMemory, SysDbgEnableKernelDebugger, SysDbgDisableKernelDebugger, SysDbgGetAutoKdEnable, SysDbgSetAutoKdEnable, SysDbgGetPrintBufferSize, SysDbgSetPrintBufferSize, SysDbgGetKdUmExceptionEnable, SysDbgSetKdUmExceptionEnable, SysDbgGetTriageDump, SysDbgGetKdBlockEnable, SysDbgSetKdBlockEnable, } SYSDBG_COMMAND, * PSYSDBG_COMMAND; typedef NTSTATUS(NTAPI* pNtSystemDebugControl)( IN SYSDBG_COMMAND Command, IN PVOID InputBuffer, IN ULONG InputBufferLength, OUT PVOID OutputBuffer, IN ULONG OutputBufferLength, OUT PULONG ReturnLength); typedef NTSTATUS(WINAPI *pNtCreateDebugObject)(OUT PHANDLE, IN ACCESS_MASK, IN POBJECT_ATTRIBUTES, IN ULONG); typedef NTSTATUS(WINAPI *pNtCreateThreadEx)( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN OPTIONAL POBJECT_ATTRIBUTES ObjectAttributes, IN HANDLE ProcessHandle, IN PVOID StartRoutine, IN OPTIONAL PVOID Argument, IN ULONG CreateFlags, //THREAD_CREATE_FLAGS_* IN OPTIONAL ULONG_PTR ZeroBits, IN OPTIONAL SIZE_T StackSize, IN OPTIONAL SIZE_T MaximumStackSize, IN OPTIONAL PPS_ATTRIBUTE_LIST AttributeList ); typedef NTSTATUS(WINAPI *pNtDelayExecution)(IN BOOLEAN, IN PLARGE_INTEGER); typedef NTSTATUS(WINAPI *pNtQueryInformationProcess)(IN HANDLE, IN UINT, OUT PVOID, IN ULONG, OUT PULONG); typedef NTSTATUS(WINAPI *pNtQueryInformationThread)(HANDLE, UINT, PVOID, ULONG, PULONG); typedef NTSTATUS(NTAPI *pNtQueryLicenseValue)( IN PUNICODE_STRING ValueName, OUT OPTIONAL PULONG Type, OUT PVOID Data, IN ULONG DataSize, OUT PULONG ResultDataSize); typedef VOID (NTAPI *pRtlInitUnicodeString)( _Out_ PUNICODE_STRING DestinationString, _In_opt_ PCWSTR SourceString); typedef NTSTATUS(WINAPI *pNtQueryDirectoryObject)(_In_ HANDLE, _Out_opt_ PVOID, _In_ ULONG, _In_ BOOLEAN, _In_ BOOLEAN, _Inout_ PULONG, _Out_opt_ PULONG); typedef NTSTATUS(WINAPI *pNtOpenDirectoryObject)(OUT PHANDLE, IN ACCESS_MASK, IN POBJECT_ATTRIBUTES); typedef NTSTATUS(WINAPI *pNtQueryObject)(IN HANDLE, IN UINT, OUT PVOID, IN ULONG, OUT PULONG); typedef NTSTATUS(WINAPI *pNtQuerySystemInformation)(IN UINT, OUT PVOID, IN ULONG, OUT PULONG); typedef NTSTATUS(WINAPI *pNtSetInformationThread)(HANDLE, UINT, PVOID, ULONG); typedef NTSTATUS(WINAPI* pNtUnmapViewOfSection)(HANDLE ProcessHandle, PVOID BaseAddress); typedef NTSTATUS(WINAPI* pNtYieldExecution)(); typedef NTSTATUS(WINAPI* pRtlGetVersion)(RTL_OSVERSIONINFOEXW*); typedef ULONG (NTAPI* pRtlNtStatusToDosError)(IN NTSTATUS Status); typedef NTSTATUS(NTAPI * pNtWow64QueryInformationProcess64)( IN HANDLE ProcessHandle, ULONG ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength OPTIONAL); typedef NTSTATUS(WINAPI *pNtWow64ReadVirtualMemory64)( HANDLE ProcessHandle, PVOID64 BaseAddress, PVOID Buffer, ULONGLONG BufferSize, PULONGLONG NumberOfBytesRead ); typedef NTSTATUS(NTAPI *pNtWow64QueryVirtualMemory64)( IN HANDLE ProcessHandle, IN PVOID64 BaseAddress, IN DWORD MemoryInformationClass, OUT PMEMORY_BASIC_INFORMATION64 MemoryInformation, IN ULONG64 Size, OUT PULONG64 ReturnLength OPTIONAL); typedef NTSTATUS(NTAPI *pLdrEnumerateLoadedModules)( IN BOOLEAN ReservedFlag, IN PLDR_ENUM_CALLBACK EnumProc, IN PVOID Context); typedef INT(NTAPI *pWudfIsAnyDebuggerPresent)(); typedef INT(NTAPI *pWudfIsKernelDebuggerPresent)(); typedef INT(NTAPI *pWudfIsUserDebuggerPresent)();
4,881
C++
.h
130
35.669231
154
0.829926
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,096
winapifamily.h
LordNoteworthy_al-khaser/al-khaser/Shared/winapifamily.h
/* Copyright (c) Microsoft Corporation. All rights reserved. Module Name: winapifamily.h Abstract: Master include file for API family partitioning. */ #define _WIN32_WINNT_WIN8 0x0602 #define _WIN32_WINNT_WINBLUE 0x0603 #ifndef _INC_WINAPIFAMILY #define _INC_WINAPIFAMILY #if defined(_MSC_VER) && !defined(MOFCOMP_PASS) #pragma once #endif // defined(_MSC_VER) && !defined(MOFCOMP_PASS) /* * When compiling C and C++ code using SDK header files, the development * environment can specify a target platform by #define-ing the * pre-processor symbol WINAPI_FAMILY to one of the following values. * Each FAMILY value denotes an application family for which a different * subset of the total set of header-file-defined APIs are available. * Setting the WINAPI_FAMILY value will effectively hide from the * editing and compilation environments the existence of APIs that * are not applicable to the family of applications targeting a * specific platform. */ /* * The WINAPI_FAMILY values of 0 and 1 are reserved to ensure that * an error will occur if WINAPI_FAMILY is set to any * WINAPI_PARTITION value (which must be 0 or 1, see below). */ #define WINAPI_FAMILY_PC_APP 2 /* Windows Store Applications */ #define WINAPI_FAMILY_PHONE_APP 3 /* Windows Phone Applications */ #define WINAPI_FAMILY_DESKTOP_APP 100 /* Windows Desktop Applications */ /* The value of WINAPI_FAMILY_DESKTOP_APP may change in future SDKs. */ /* Additional WINAPI_FAMILY values may be defined in future SDKs. */ /* * For compatibility with Windows 8 header files, the following * synonym for WINAPI_FAMILY_PC_APP is temporarily #define'd. * Use of this symbol should be considered deprecated. */ #define WINAPI_FAMILY_APP WINAPI_FAMILY_PC_APP /* * If no WINAPI_FAMILY value is specified, then all APIs available to * Windows desktop applications are exposed. */ #ifndef WINAPI_FAMILY #define WINAPI_FAMILY WINAPI_FAMILY_DESKTOP_APP #endif /* * API PARTITONs are part of an indirection mechanism for mapping between * individual APIs and the FAMILYs to which they apply. * Each PARTITION is a category or subset of named APIs. PARTITIONs * are permitted to have overlapping membership -- some single API * might be part of more than one PARTITION. In support of new * FAMILYs that might be added in future SDKs, any single current * PARTITION might in that future SDK be split into two or more new PARTITIONs. * Accordingly, application developers should avoid taking dependencies on * PARTITION names; developers' only dependency upon the symbols defined * in this file should be their reliance on the WINAPI_FAMILY names and values. */ /* * Current PARTITIONS are each #undef'ed below, and then will be #define-ed * to be either 1 or 0 or depending on the active WINAPI_FAMILY. */ #undef WINAPI_PARTITION_DESKTOP /* usable for PC desktop apps (but not store apps) */ #undef WINAPI_PARTITION_APP /* usable for most platforms' store apps */ #undef WINAPI_PARTITION_PC_APP /* specific to PC store apps */ #undef WINAPI_PARTITION_PHONE_APP /* specific to phone store apps */ /* * The mapping between families and partitions is summarized here. * An X indicates that the given partition is active for the given * platform/family. * * +---------------+ * | *Partition* | * +---+---+---+---+ * | | | | P | * | | | | H | * | D | | | O | * | E | | P | N | * | S | | C | E | * | K | | _ | _ | * | T | A | A | A | * +-------------------------+-+ O | P | P | P | * | *Platform/Family* \| P | P | P | P | * +---------------------------+---+---+---+---+ * | WINAPI_FAMILY_DESKTOP_APP | X | X | X | | * +---------------------------+---+---+---+---+ * | WINAPI_FAMILY_PC_APP | | X | X | | * +---------------------------+---+---+---+---+ * | WINAPI_FAMILY_PHONE_APP | | X | | X | * +---------------------------+---+---+---+---+ * * The table above is encoded in the following expressions, * each of which evaluates to 1 or 0. * * Whenever a new family is added, all of these expressions * need to be reconsidered. */ #if WINAPI_FAMILY != WINAPI_FAMILY_DESKTOP_APP && WINAPI_FAMILY != WINAPI_FAMILY_PC_APP && WINAPI_FAMILY != WINAPI_FAMILY_PHONE_APP # error Unknown WINAPI_FAMILY value. Was it defined in terms of a WINAPI_PARTITION_* value? #endif #define WINAPI_PARTITION_DESKTOP (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP) #define WINAPI_PARTITION_APP 1 /* active for all current families */ #define WINAPI_PARTITION_PC_APP (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP || WINAPI_FAMILY == WINAPI_FAMILY_PC_APP) #define WINAPI_PARTITION_PHONE_APP (WINAPI_FAMILY == WINAPI_FAMILY_PHONE_APP) /* * For compatibility with Windows Phone 8 header files, the following * synonym for WINAPI_PARTITION_PHONE_APP is temporarily #define'd. * Use of this symbol should be regarded as deprecated. */ #define WINAPI_PARTITION_PHONE WINAPI_PARTITION_PHONE_APP /* * Header files use the WINAPI_FAMILY_PARTITION macro to assign one or * more declarations to some group of partitions. The macro chooses * whether the preprocessor will emit or omit a sequence of declarations * bracketed by an #if/#endif pair. All header file references to the * WINAPI_PARTITION_* values should be in the form of occurrences of * WINAPI_FAMILY_PARTITION(...). * * For example, the following usage of WINAPI_FAMILY_PARTITION identifies * a sequence of declarations that are part of both the Windows Desktop * Partition and the Windows-Phone-Specific Store Partition: * * #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_PHONE_APP) * ... * #endif // WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_PHONE_APP) * * The comment on the closing #endif allow tools as well as people to find the * matching #ifdef properly. * * Usages of WINAPI_FAMILY_PARTITION may be combined, when the partitition definitions are * related. In particular one might use declarations like * * #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) * * or * * #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_PHONE_APP) * * Direct references to WINAPI_PARTITION_ values (eg #if !WINAPI_FAMILY_PARTITION_...) * should not be used. */ #define WINAPI_FAMILY_PARTITION(Partitions) (Partitions) /* * Macro used to #define or typedef a symbol used for selective deprecation * of individual methods of a COM interfaces that are otherwise available * for a given set of partitions. */ #define _WINAPI_DEPRECATED_DECLARATION __declspec(deprecated("This API cannot be used in the context of the caller's application type.")) /* * For compatibility with Windows 8 header files, the following * symbol is temporarily conditionally #define'd. Additional symbols * like this should be not defined in winapifamily.h, but rather should be * introduced locally to the header files of the component that needs them. */ #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) # define APP_DEPRECATED_HRESULT HRESULT _WINAPI_DEPRECATED_DECLARATION #endif // WINAPIFAMILY_PARTITION(WINAPI_PARTITION_APP) && !WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #endif /* !_INC_WINAPIFAMILY */
7,918
C++
.h
160
46.45625
139
0.671551
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
26,099
APIs.h
LordNoteworthy_al-khaser/al-khaser/Shared/APIs.h
#pragma once enum API_IDENTIFIER { API_CsrGetProcessId, API_EnumSystemFirmwareTables, API_GetActiveProcessorCount, API_GetSystemFirmwareTable, API_GetNativeSystemInfo, API_GetProductInfo, API_EnumProcessModulesEx_Kernel, API_EnumProcessModulesEx_PSAPI, API_IsWow64Process, API_LdrEnumerateLoadedModules, API_NtClose, API_NtSystemDebugControl, API_NtCreateDebugObject, API_NtDelayExecution, API_NtOpenDirectoryObject, API_NtQueryInformationThread, API_NtQueryInformationProcess, API_NtQueryLicenseValue, API_NtQueryDirectoryObject, API_NtQueryObject, API_NtQuerySystemInformation, API_NtSetInformationThread, API_NtWow64QueryInformationProcess64, API_NtWow64QueryVirtualMemory64, API_NtWow64ReadVirtualMemory64, API_NtYieldExecution, API_RtlGetVersion, API_RtlInitUnicodeString, API_WudfIsAnyDebuggerPresent, API_WudfIsKernelDebuggerPresent, API_WudfIsUserDebuggerPresent, }; enum API_OS_VERSION { NONE, WIN_XP, WIN_XP_SP1, WIN_XP_SP2, WIN_XP_SP3, WIN_VISTA, WIN_VISTA_SP1, WIN_VISTA_SP2, WIN_7, WIN_7_SP1, WIN_80, WIN_81, WIN_10, VERSION_MAX }; enum API_OS_BITS { ANY, X86_ONLY, X64_ONLY, }; struct VERSION_FUNCTION_MAP { API_OS_VERSION Version; bool(*Function)(); VERSION_FUNCTION_MAP(API_OS_VERSION version, bool(*function)()) { Version = version; Function = function; } VERSION_FUNCTION_MAP() { } }; struct API_DATA { API_IDENTIFIER Identifier; const char* Library; const char* EntryName; API_OS_BITS PlatformBits; API_OS_VERSION MinVersion; API_OS_VERSION RemovedInVersion; bool Available; bool ExpectedAvailable; void* Pointer; API_DATA(API_IDENTIFIER identifier, const char* lib, const char* name, API_OS_BITS bits, API_OS_VERSION minVersion, API_OS_VERSION removedInVersion) { Identifier = identifier; Library = lib; EntryName = name; PlatformBits = bits; MinVersion = minVersion; RemovedInVersion = removedInVersion; Available = false; ExpectedAvailable = false; Pointer = nullptr; } }; const VERSION_FUNCTION_MAP VersionFunctionMap[] = { { API_OS_VERSION::NONE, nullptr }, { API_OS_VERSION::WIN_XP, IsWindowsXPOrGreater }, { API_OS_VERSION::WIN_XP_SP1, IsWindowsXPSP1OrGreater }, { API_OS_VERSION::WIN_XP_SP2, IsWindowsXPSP2OrGreater }, { API_OS_VERSION::WIN_XP_SP3, IsWindowsXPSP3OrGreater }, { API_OS_VERSION::WIN_VISTA, IsWindowsVistaOrGreater }, { API_OS_VERSION::WIN_VISTA_SP1, IsWindowsVistaSP1OrGreater }, { API_OS_VERSION::WIN_VISTA_SP2, IsWindowsVistaSP2OrGreater }, { API_OS_VERSION::WIN_7, IsWindows7OrGreater }, { API_OS_VERSION::WIN_7_SP1, IsWindows7SP1OrGreater }, { API_OS_VERSION::WIN_80, IsWindows8OrGreater }, { API_OS_VERSION::WIN_81, IsWindows8Point1OrGreater }, { API_OS_VERSION::WIN_10, IsWindows10OrGreater }, }; class API { private: static bool ShouldFunctionExistOnCurrentPlatform(API_OS_BITS bits, API_OS_VERSION minVersion, API_OS_VERSION removedInVersion); public: static void Init(); static void PrintAvailabilityReport(); static bool IsAvailable(API_IDENTIFIER api); static void* GetAPI(API_IDENTIFIER api); };
3,067
C++
.h
120
23.583333
149
0.79612
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,100
log.h
LordNoteworthy_al-khaser/al-khaser/Shared/log.h
#pragma once #define WIDEN2(x) L##x #define WIDEN(x) WIDEN2(x) #define __WFILE__ WIDEN(__FILE__) #ifdef UNICODE #define __TFILE__ __WFILE__ #else #define __TFILE__ __FILE__ #endif void log_print(const TCHAR* filename, const TCHAR *fmt, ...); #define LOG_PRINT(...) log_print(__TFILE__, __VA_ARGS__ )
308
C++
.h
11
26.272727
61
0.66436
LordNoteworthy/al-khaser
5,787
1,160
38
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,101
misc-test.cpp
danmar_cppcheck/addons/test/misc-test.cpp
// To test: // ~/cppcheck/cppcheck --dump misc-test.cpp && python ../misc.py -verify misc-test.cpp.dump #include <string> #include <vector> // Warn about string concatenation in array initializers.. const char *a[] = {"a" "b"}; // stringConcatInArrayInit const char *b[] = {"a","b" "c"}; // stringConcatInArrayInit #define MACRO "MACRO" const char *c[] = { MACRO "text" }; // stringConcatInArrayInit // Function is implicitly virtual class base { virtual void dostuff(int); }; class derived : base { void dostuff(int); // implicitlyVirtual }; // Pass struct to ellipsis function struct {int x;int y;} s; void ellipsis(int x, ...); void foo(std::vector<std::string> v) { ellipsis(321, s); // ellipsisStructArg ellipsis(321, v[0]); // ellipsisStructArg }
774
C++
.cpp
23
31.73913
91
0.698925
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,102
naming_test.cpp
danmar_cppcheck/addons/test/naming_test.cpp
// To test: // ~/cppcheck/cppcheck --dump naming_test.cpp && python ../naming.py --var='[a-z].*' --function='[a-z].*' naming_test.cpp.dump // No error for mismatching Constructor/Destructor names should be issued, they can not be changed. class TestClass1 { TestClass1() {} ~TestClass1() {} TestClass1(const TestClass1 &) {} TestClass1(TestClass1 &&) {} };
374
C++
.cpp
10
34.7
126
0.674931
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,103
misra-test.cpp
danmar_cppcheck/addons/test/misra/misra-test.cpp
// #8441 class C { int a; int b; C(void) : a(1), b(1) { c; } }; class misra_21_1_C { public: misra_21_1_C operator=(const misra_21_1_C &); }; class C2 { public: C2(void); private: void* f; }; C2::C2(void) : f(NULL) {} static void test_misra_21_1_crash(void) { auto misra_21_1_C a, b; // 12.3 a = b; }
337
C++
.cpp
22
12.681818
52
0.557692
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,104
local_static_const.cpp
danmar_cppcheck/addons/test/threadsafety/local_static_const.cpp
struct Dummy { int x; }; void func() { // cppcheck-suppress threadsafety-threadsafety-const static const Dummy dummy; }
125
C++
.cpp
7
16.142857
54
0.754237
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,105
local_static.cpp
danmar_cppcheck/addons/test/threadsafety/local_static.cpp
struct Dummy { int x; }; void func() { // cppcheck-suppress threadsafety-threadsafety static Dummy dummy; }
117
C++
.cpp
7
14.428571
50
0.718182
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
26,106
MT-Unsafe.cpp
danmar_cppcheck/addons/test/threadsafety/MT-Unsafe.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2023 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * This does not match the standard cppchek test code, * because I haven't figured that out yet. * This code does compile and run, and does demonstrate * the issues that the threadsafety.py addon is supposed to find. * It does not use threads ! */ #include <stdio.h> #include <time.h> #include <string.h> void threadsafety_static() { // cppcheck-suppress threadsafety-threadsafety static unsigned int nCount = 0; nCount++; printf("%d\n", nCount); } void threadsafety_call() { time_t now = time(nullptr); // cppcheck-suppress threadsafety-unsafe-call printf("%s\n", ctime(&now)); } // cppcheck --addon=threadsafety // should *not* find any problems with this function. void threadsafety_safecall() { char haystack[] = "alphabet"; char needle[] = "Alph"; char* found = strcasestr(haystack, needle); printf("%s %sin %s\n", needle, found ? "" : "not ", haystack); } int main() { threadsafety_static(); threadsafety_call(); threadsafety_safecall(); threadsafety_static(); return 0; }
1,811
C++
.cpp
56
29.535714
72
0.717241
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,107
checkunusedfunctions.cpp
danmar_cppcheck/lib/checkunusedfunctions.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkunusedfunctions.h" #include "astutils.h" #include "errorlogger.h" #include "errortypes.h" #include "library.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include "utils.h" #include <algorithm> #include <cctype> #include <cstring> #include <fstream> #include <map> #include <sstream> #include <tuple> #include <utility> #include <vector> #include "xml.h" //--------------------------------------------------------------------------- static const CWE CWE561(561U); // Dead Code static std::string stripTemplateParameters(const std::string& funcName) { std::string name = funcName; const auto pos = name.find('<'); if (pos > 0 && pos != std::string::npos) name.erase(pos - 1); return name; } //--------------------------------------------------------------------------- // FUNCTION USAGE - Check for unused functions etc //--------------------------------------------------------------------------- static bool isRecursiveCall(const Token* ftok) { return ftok->function() && ftok->function() == Scope::nestedInFunction(ftok->scope()); } void CheckUnusedFunctions::parseTokens(const Tokenizer &tokenizer, const Settings &settings) { const char * const FileName = tokenizer.list.getFiles().front().c_str(); const bool doMarkup = settings.library.markupFile(FileName); // Function declarations.. if (!doMarkup) { const SymbolDatabase* symbolDatabase = tokenizer.getSymbolDatabase(); for (const Scope* scope : symbolDatabase->functionScopes) { const Function* func = scope->function; if (!func || !func->token) continue; // Don't warn about functions that are marked by __attribute__((constructor)) or __attribute__((destructor)) if (func->isAttributeConstructor() || func->isAttributeDestructor() || func->type != Function::eFunction || func->isOperator()) continue; if (func->isExtern()) continue; bool foundAllBaseClasses{}; if (const Function* ofunc = func->getOverriddenFunction(&foundAllBaseClasses)) { if (!foundAllBaseClasses || ofunc->isPure()) continue; } else if (func->isImplicitlyVirtual()) { continue; } mFunctionDecl.emplace_back(func); FunctionUsage &usage = mFunctions[stripTemplateParameters(func->name())]; if (func->retDef && (func->retDef->isAttributeUnused() || func->retDef->isAttributeMaybeUnused())) { usage.usedOtherFile = true; } if (!usage.lineNumber) usage.lineNumber = func->token->linenr(); // TODO: why always overwrite this but not the filename and line? usage.fileIndex = func->token->fileIndex(); const std::string& fileName = tokenizer.list.file(func->token); // No filename set yet.. if (usage.filename.empty()) { usage.filename = fileName; } // Multiple files => filename = "+" else if (usage.filename != fileName) { //func.filename = "+"; usage.usedOtherFile |= usage.usedSameFile; } } } // Function usage.. const Token *lambdaEndToken = nullptr; for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { if (tok == lambdaEndToken) lambdaEndToken = nullptr; else if (!lambdaEndToken && tok->str() == "[") lambdaEndToken = findLambdaEndToken(tok); // parsing of library code to find called functions if (settings.library.isexecutableblock(FileName, tok->str())) { const Token * markupVarToken = tok->tokAt(settings.library.blockstartoffset(FileName)); // not found if (!markupVarToken) continue; int scope = 0; bool start = true; // find all function calls in library code (starts with '(', not if or while etc) while ((scope || start) && markupVarToken) { if (markupVarToken->str() == settings.library.blockstart(FileName)) { scope++; start = false; } else if (markupVarToken->str() == settings.library.blockend(FileName)) scope--; else if (!settings.library.iskeyword(FileName, markupVarToken->str())) { mFunctionCalls.insert(markupVarToken->str()); if (mFunctions.find(markupVarToken->str()) != mFunctions.end()) mFunctions[markupVarToken->str()].usedOtherFile = true; else if (markupVarToken->strAt(1) == "(") { FunctionUsage &func = mFunctions[markupVarToken->str()]; func.filename = tokenizer.list.getFiles()[markupVarToken->fileIndex()]; if (func.filename.empty() || func.filename == "+") func.usedOtherFile = true; else func.usedSameFile = true; } } markupVarToken = markupVarToken->next(); } } if (!doMarkup // only check source files && settings.library.isexporter(tok->str()) && tok->next() != nullptr) { const Token * propToken = tok->next(); while (propToken && propToken->str() != ")") { if (settings.library.isexportedprefix(tok->str(), propToken->str())) { const Token* nextPropToken = propToken->next(); const std::string& value = nextPropToken->str(); if (mFunctions.find(value) != mFunctions.end()) { mFunctions[value].usedOtherFile = true; } mFunctionCalls.insert(value); } if (settings.library.isexportedsuffix(tok->str(), propToken->str())) { const Token* prevPropToken = propToken->previous(); const std::string& value = prevPropToken->str(); if (value != ")" && mFunctions.find(value) != mFunctions.end()) { mFunctions[value].usedOtherFile = true; } mFunctionCalls.insert(value); } propToken = propToken->next(); } } if (doMarkup && settings.library.isimporter(FileName, tok->str()) && tok->next()) { const Token * propToken = tok->next(); if (propToken->next()) { propToken = propToken->next(); while (propToken && propToken->str() != ")") { const std::string& value = propToken->str(); if (!value.empty()) { mFunctions[value].usedOtherFile = true; mFunctionCalls.insert(value); break; } propToken = propToken->next(); } } } if (settings.library.isreflection(tok->str())) { const int argIndex = settings.library.reflectionArgument(tok->str()); if (argIndex >= 0) { const Token * funcToken = tok->next(); int index = 0; std::string value; while (funcToken) { if (funcToken->str()==",") { if (++index == argIndex) break; value.clear(); } else value += funcToken->str(); funcToken = funcToken->next(); } if (index == argIndex) { value = value.substr(1, value.length() - 2); mFunctions[value].usedOtherFile = true; mFunctionCalls.insert(std::move(value)); } } } if (tok->hasAttributeCleanup()) { const std::string& funcname = tok->getAttributeCleanup(); mFunctions[funcname].usedOtherFile = true; mFunctionCalls.insert(funcname); continue; } const Token *funcname = nullptr; if (doMarkup) funcname = Token::Match(tok, "%name% (") ? tok : nullptr; else if ((lambdaEndToken || tok->scope()->isExecutable()) && Token::Match(tok, "%name% (")) { funcname = tok; } else if ((lambdaEndToken || tok->scope()->isExecutable()) && Token::Match(tok, "%name% <") && Token::simpleMatch(tok->linkAt(1), "> (")) { funcname = tok; } else if (Token::Match(tok, "< %name%") && tok->link()) { funcname = tok->next(); while (Token::Match(funcname, "%name% :: %name%")) funcname = funcname->tokAt(2); } else if (tok->scope()->type != Scope::ScopeType::eEnum && (Token::Match(tok, "[;{}.,()[=+-/|!?:]") || Token::Match(tok, "return|throw"))) { funcname = tok->next(); if (funcname && funcname->str() == "&") funcname = funcname->next(); if (funcname && funcname->str() == "::") funcname = funcname->next(); while (Token::Match(funcname, "%name% :: %name%")) funcname = funcname->tokAt(2); if (!Token::Match(funcname, "%name% [(),;]:}<>]")) continue; } if (!funcname || funcname->isKeyword() || funcname->isStandardType() || funcname->varId() || funcname->enumerator() || funcname->type()) continue; // funcname ( => Assert that the end parentheses isn't followed by { if (Token::Match(funcname, "%name% (|<") && funcname->linkAt(1)) { const Token *ftok = funcname->next(); if (ftok->str() == "<") ftok = ftok->link(); if (Token::Match(ftok->linkAt(1), ") const|throw|{")) funcname = nullptr; } if (funcname) { if (isRecursiveCall(funcname)) continue; const auto baseName = stripTemplateParameters(funcname->str()); FunctionUsage &func = mFunctions[baseName]; const std::string& called_from_file = tokenizer.list.getFiles()[funcname->fileIndex()]; if (func.filename.empty() || func.filename == "+" || func.filename != called_from_file) func.usedOtherFile = true; else func.usedSameFile = true; mFunctionCalls.insert(baseName); } } } static bool isOperatorFunction(const std::string & funcName) { /* Operator functions are invalid function names for C, so no need to check * this in here. As result the returned error function might be incorrect. * * List of valid operators can be found at: * http://en.cppreference.com/w/cpp/language/operators * * Conversion functions must be a member function (at least for gcc), so no * need to cover them for unused functions. * * To speed up the comparison, not the whole list of operators is used. * Instead only the character after the operator prefix is checked to be a * none alpa numeric value, but the '_', to cover function names like * "operator_unused". In addition the following valid operators are checked: * - new * - new[] * - delete * - delete[] */ const std::string operatorPrefix = "operator"; if (funcName.compare(0, operatorPrefix.length(), operatorPrefix) != 0) { return false; } // Taking care of funcName == "operator", which is no valid operator if (funcName.length() == operatorPrefix.length()) { return false; } const char firstOperatorChar = funcName[operatorPrefix.length()]; if (firstOperatorChar == '_') { return false; } if (!std::isalnum(firstOperatorChar)) { return true; } const std::vector<std::string> additionalOperators = { "new", "new[]", "delete", "delete[]" }; return std::find(additionalOperators.cbegin(), additionalOperators.cend(), funcName.substr(operatorPrefix.length())) != additionalOperators.cend(); } #define logChecker(id) \ do { \ const ErrorMessage errmsg({}, nullptr, Severity::internal, "logChecker", (id), CWE(0U), Certainty::normal); \ errorLogger.reportErr(errmsg); \ } while (false) bool CheckUnusedFunctions::check(const Settings& settings, ErrorLogger& errorLogger) const { logChecker("CheckUnusedFunctions::check"); // unusedFunction using ErrorParams = std::tuple<std::string, unsigned int, unsigned int, std::string>; std::vector<ErrorParams> errors; // ensure well-defined order for (std::unordered_map<std::string, FunctionUsage>::const_iterator it = mFunctions.cbegin(); it != mFunctions.cend(); ++it) { const FunctionUsage &func = it->second; if (func.usedOtherFile || func.filename.empty()) continue; if (settings.library.isentrypoint(it->first)) continue; if (!func.usedSameFile) { if (isOperatorFunction(it->first)) continue; std::string filename; if (func.filename != "+") filename = func.filename; errors.emplace_back(filename, func.fileIndex, func.lineNumber, it->first); } else if (!func.usedOtherFile) { /** @todo add error message "function is only used in <file> it can be static" */ /* std::ostringstream errmsg; errmsg << "The function '" << it->first << "' is only used in the file it was declared in so it should have local linkage."; mErrorLogger->reportErr( errmsg.str() ); errors = true; */ } } std::sort(errors.begin(), errors.end()); for (const auto& e : errors) unusedFunctionError(errorLogger, std::get<0>(e), std::get<1>(e), std::get<2>(e), std::get<3>(e)); return !errors.empty(); } void CheckUnusedFunctions::unusedFunctionError(ErrorLogger& errorLogger, const std::string &filename, unsigned int fileIndex, unsigned int lineNumber, const std::string &funcname) { std::list<ErrorMessage::FileLocation> locationList; if (!filename.empty()) { locationList.emplace_back(filename, lineNumber, 0); locationList.back().fileIndex = fileIndex; } const ErrorMessage errmsg(std::move(locationList), emptyString, Severity::style, "$symbol:" + funcname + "\nThe function '$symbol' is never used.", "unusedFunction", CWE561, Certainty::normal); errorLogger.reportErr(errmsg); } CheckUnusedFunctions::FunctionDecl::FunctionDecl(const Function *f) : functionName(f->name()), fileName(f->token->fileName()), lineNumber(f->token->linenr()) {} std::string CheckUnusedFunctions::analyzerInfo() const { std::ostringstream ret; for (const FunctionDecl &functionDecl : mFunctionDecl) { ret << " <functiondecl" << " file=\"" << ErrorLogger::toxml(functionDecl.fileName) << '\"' << " functionName=\"" << ErrorLogger::toxml(functionDecl.functionName) << '\"' << " lineNumber=\"" << functionDecl.lineNumber << "\"/>\n"; } for (const std::string &fc : mFunctionCalls) { ret << " <functioncall functionName=\"" << ErrorLogger::toxml(fc) << "\"/>\n"; } return ret.str(); } namespace { struct Location { Location() : lineNumber(0) {} Location(std::string f, const int l) : fileName(std::move(f)), lineNumber(l) {} std::string fileName; int lineNumber; }; } void CheckUnusedFunctions::analyseWholeProgram(const Settings &settings, ErrorLogger &errorLogger, const std::string &buildDir) { std::map<std::string, Location> decls; std::set<std::string> calls; const std::string filesTxt(buildDir + "/files.txt"); std::ifstream fin(filesTxt.c_str()); std::string filesTxtLine; while (std::getline(fin, filesTxtLine)) { const std::string::size_type firstColon = filesTxtLine.find(':'); if (firstColon == std::string::npos) continue; const std::string::size_type secondColon = filesTxtLine.find(':', firstColon+1); if (secondColon == std::string::npos) continue; const std::string xmlfile = buildDir + '/' + filesTxtLine.substr(0,firstColon); const std::string sourcefile = filesTxtLine.substr(secondColon+1); tinyxml2::XMLDocument doc; const tinyxml2::XMLError error = doc.LoadFile(xmlfile.c_str()); if (error != tinyxml2::XML_SUCCESS) continue; const tinyxml2::XMLElement * const rootNode = doc.FirstChildElement(); if (rootNode == nullptr) continue; for (const tinyxml2::XMLElement *e = rootNode->FirstChildElement(); e; e = e->NextSiblingElement()) { if (std::strcmp(e->Name(), "FileInfo") != 0) continue; const char *checkattr = e->Attribute("check"); if (checkattr == nullptr || std::strcmp(checkattr,"CheckUnusedFunctions") != 0) continue; for (const tinyxml2::XMLElement *e2 = e->FirstChildElement(); e2; e2 = e2->NextSiblingElement()) { const char* functionName = e2->Attribute("functionName"); if (functionName == nullptr) continue; const char* name = e2->Name(); if (std::strcmp(name,"functioncall") == 0) { calls.insert(functionName); continue; } if (std::strcmp(name,"functiondecl") == 0) { const char* lineNumber = e2->Attribute("lineNumber"); if (lineNumber) { const char* file = e2->Attribute("file"); // cppcheck-suppress templateInstantiation - TODO: fix this - see #11631 decls[functionName] = Location(file ? file : sourcefile, strToInt<int>(lineNumber)); } } } } } for (std::map<std::string, Location>::const_iterator decl = decls.cbegin(); decl != decls.cend(); ++decl) { const std::string &functionName = stripTemplateParameters(decl->first); if (settings.library.isentrypoint(functionName)) continue; if (calls.find(functionName) == calls.end() && !isOperatorFunction(functionName)) { const Location &loc = decl->second; unusedFunctionError(errorLogger, loc.fileName, /*fileIndex*/ 0, loc.lineNumber, functionName); } } } void CheckUnusedFunctions::updateFunctionData(const CheckUnusedFunctions& check) { for (const auto& entry : check.mFunctions) { FunctionUsage &usage = mFunctions[entry.first]; if (!usage.lineNumber) usage.lineNumber = entry.second.lineNumber; // TODO: why always overwrite this but not the filename and line? usage.fileIndex = entry.second.fileIndex; if (usage.filename.empty()) usage.filename = entry.second.filename; // cppcheck-suppress bitwiseOnBoolean - TODO: FP usage.usedOtherFile |= entry.second.usedOtherFile; // cppcheck-suppress bitwiseOnBoolean - TODO: FP usage.usedSameFile |= entry.second.usedSameFile; } mFunctionDecl.insert(mFunctionDecl.cend(), check.mFunctionDecl.cbegin(), check.mFunctionDecl.cend()); mFunctionCalls.insert(check.mFunctionCalls.cbegin(), check.mFunctionCalls.cend()); }
20,822
C++
.cpp
443
36.225734
197
0.570536
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,108
ctu.cpp
danmar_cppcheck/lib/ctu.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "ctu.h" #include "astutils.h" #include "errortypes.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include "utils.h" #include <algorithm> #include <cstdint> #include <cstring> #include <iterator> // back_inserter #include <sstream> #include <utility> #include "xml.h" //--------------------------------------------------------------------------- static constexpr char ATTR_CALL_ID[] = "call-id"; static constexpr char ATTR_CALL_FUNCNAME[] = "call-funcname"; static constexpr char ATTR_CALL_ARGNR[] = "call-argnr"; static constexpr char ATTR_CALL_ARGEXPR[] = "call-argexpr"; static constexpr char ATTR_CALL_ARGVALUETYPE[] = "call-argvaluetype"; static constexpr char ATTR_CALL_ARGVALUE[] = "call-argvalue"; static constexpr char ATTR_WARNING[] = "warning"; static constexpr char ATTR_LOC_FILENAME[] = "file"; static constexpr char ATTR_LOC_LINENR[] = "line"; static constexpr char ATTR_LOC_COLUMN[] = "col"; static constexpr char ATTR_INFO[] = "info"; static constexpr char ATTR_MY_ID[] = "my-id"; static constexpr char ATTR_MY_ARGNR[] = "my-argnr"; static constexpr char ATTR_MY_ARGNAME[] = "my-argname"; static constexpr char ATTR_VALUE[] = "value"; std::string CTU::getFunctionId(const Tokenizer &tokenizer, const Function *function) { return tokenizer.list.file(function->tokenDef) + ':' + std::to_string(function->tokenDef->linenr()) + ':' + std::to_string(function->tokenDef->column()); } CTU::FileInfo::Location::Location(const Tokenizer &tokenizer, const Token *tok) : fileName(tokenizer.list.file(tok)) , lineNumber(tok->linenr()) , column(tok->column()) {} std::string CTU::FileInfo::toString() const { std::ostringstream out; // Function calls.. for (const CTU::FileInfo::FunctionCall &functionCall : functionCalls) { out << functionCall.toXmlString(); } // Nested calls.. for (const CTU::FileInfo::NestedCall &nestedCall : nestedCalls) { out << nestedCall.toXmlString() << "\n"; } return out.str(); } std::string CTU::FileInfo::CallBase::toBaseXmlString() const { std::ostringstream out; out << " " << ATTR_CALL_ID << "=\"" << callId << "\"" << " " << ATTR_CALL_FUNCNAME << "=\"" << ErrorLogger::toxml(callFunctionName) << "\"" << " " << ATTR_CALL_ARGNR << "=\"" << callArgNr << "\"" << " " << ATTR_LOC_FILENAME << "=\"" << ErrorLogger::toxml(location.fileName) << "\"" << " " << ATTR_LOC_LINENR << "=\"" << location.lineNumber << "\"" << " " << ATTR_LOC_COLUMN << "=\"" << location.column << "\""; return out.str(); } std::string CTU::FileInfo::FunctionCall::toXmlString() const { std::ostringstream out; out << "<function-call" << toBaseXmlString() << " " << ATTR_CALL_ARGEXPR << "=\"" << ErrorLogger::toxml(callArgumentExpression) << "\"" << " " << ATTR_CALL_ARGVALUETYPE << "=\"" << static_cast<int>(callValueType) << "\"" << " " << ATTR_CALL_ARGVALUE << "=\"" << callArgValue << "\""; if (warning) out << " " << ATTR_WARNING << "=\"true\""; if (callValuePath.empty()) out << "/>"; else { out << ">\n"; for (const ErrorMessage::FileLocation &loc : callValuePath) out << " <path" << " " << ATTR_LOC_FILENAME << "=\"" << ErrorLogger::toxml(loc.getfile()) << "\"" << " " << ATTR_LOC_LINENR << "=\"" << loc.line << "\"" << " " << ATTR_LOC_COLUMN << "=\"" << loc.column << "\"" << " " << ATTR_INFO << "=\"" << ErrorLogger::toxml(loc.getinfo()) << "\"/>\n"; out << "</function-call>"; } return out.str(); } std::string CTU::FileInfo::NestedCall::toXmlString() const { std::ostringstream out; out << "<function-call" << toBaseXmlString() << " " << ATTR_MY_ID << "=\"" << myId << "\"" << " " << ATTR_MY_ARGNR << "=\"" << myArgNr << "\"" << "/>"; return out.str(); } std::string CTU::FileInfo::UnsafeUsage::toString() const { std::ostringstream out; out << " <unsafe-usage" << " " << ATTR_MY_ID << "=\"" << myId << '\"' << " " << ATTR_MY_ARGNR << "=\"" << myArgNr << '\"' << " " << ATTR_MY_ARGNAME << "=\"" << myArgumentName << '\"' << " " << ATTR_LOC_FILENAME << "=\"" << ErrorLogger::toxml(location.fileName) << '\"' << " " << ATTR_LOC_LINENR << "=\"" << location.lineNumber << '\"' << " " << ATTR_LOC_COLUMN << "=\"" << location.column << '\"' << " " << ATTR_VALUE << "=\"" << value << "\"" << "/>\n"; return out.str(); } std::string CTU::toString(const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage) { std::ostringstream ret; for (const CTU::FileInfo::UnsafeUsage &u : unsafeUsage) ret << u.toString(); return ret.str(); } CTU::FileInfo::CallBase::CallBase(const Tokenizer &tokenizer, const Token *callToken) : callId(getFunctionId(tokenizer, callToken->function())) , callFunctionName(callToken->next()->astOperand1()->expressionString()) , location(CTU::FileInfo::Location(tokenizer, callToken)) {} CTU::FileInfo::NestedCall::NestedCall(const Tokenizer &tokenizer, const Function *myFunction, const Token *callToken) : CallBase(tokenizer, callToken) , myId(getFunctionId(tokenizer, myFunction)) {} static std::string readAttrString(const tinyxml2::XMLElement *e, const char *attr, bool *error) { const char *value = e->Attribute(attr); if (!value && error) *error = true; return empty_if_null(value); } static long long readAttrInt(const tinyxml2::XMLElement *e, const char *attr, bool *error) { int64_t value = 0; const bool err = (e->QueryInt64Attribute(attr, &value) != tinyxml2::XML_SUCCESS); if (error) *error = err; return value; } bool CTU::FileInfo::CallBase::loadBaseFromXml(const tinyxml2::XMLElement *xmlElement) { bool error = false; callId = readAttrString(xmlElement, ATTR_CALL_ID, &error); callFunctionName = readAttrString(xmlElement, ATTR_CALL_FUNCNAME, &error); callArgNr = readAttrInt(xmlElement, ATTR_CALL_ARGNR, &error); location.fileName = readAttrString(xmlElement, ATTR_LOC_FILENAME, &error); location.lineNumber = readAttrInt(xmlElement, ATTR_LOC_LINENR, &error); location.column = readAttrInt(xmlElement, ATTR_LOC_COLUMN, &error); return !error; } bool CTU::FileInfo::FunctionCall::loadFromXml(const tinyxml2::XMLElement *xmlElement) { if (!loadBaseFromXml(xmlElement)) return false; bool error=false; callArgumentExpression = readAttrString(xmlElement, ATTR_CALL_ARGEXPR, &error); callValueType = (ValueFlow::Value::ValueType)readAttrInt(xmlElement, ATTR_CALL_ARGVALUETYPE, &error); callArgValue = readAttrInt(xmlElement, ATTR_CALL_ARGVALUE, &error); const char *w = xmlElement->Attribute(ATTR_WARNING); warning = w && std::strcmp(w, "true") == 0; for (const tinyxml2::XMLElement *e2 = xmlElement->FirstChildElement(); !error && e2; e2 = e2->NextSiblingElement()) { if (std::strcmp(e2->Name(), "path") != 0) continue; std::string file = readAttrString(e2, ATTR_LOC_FILENAME, &error); std::string info = readAttrString(e2, ATTR_INFO, &error); const int line = readAttrInt(e2, ATTR_LOC_LINENR, &error); const int column = readAttrInt(e2, ATTR_LOC_COLUMN, &error); ErrorMessage::FileLocation loc(file, std::move(info), line, column); (void)loc; // TODO: loc is unused } return !error; } bool CTU::FileInfo::NestedCall::loadFromXml(const tinyxml2::XMLElement *xmlElement) { if (!loadBaseFromXml(xmlElement)) return false; bool error = false; myId = readAttrString(xmlElement, ATTR_MY_ID, &error); myArgNr = readAttrInt(xmlElement, ATTR_MY_ARGNR, &error); return !error; } void CTU::FileInfo::loadFromXml(const tinyxml2::XMLElement *xmlElement) { for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) { const char* name = e->Name(); if (std::strcmp(name, "function-call") == 0) { FunctionCall functionCall; if (functionCall.loadFromXml(e)) functionCalls.push_back(std::move(functionCall)); } else if (std::strcmp(name, "nested-call") == 0) { NestedCall nestedCall; if (nestedCall.loadFromXml(e)) nestedCalls.push_back(std::move(nestedCall)); } } } std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> CTU::FileInfo::getCallsMap() const { std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> ret; for (const CTU::FileInfo::NestedCall &nc : nestedCalls) ret[nc.callId].push_back(&nc); for (const CTU::FileInfo::FunctionCall &fc : functionCalls) ret[fc.callId].push_back(&fc); return ret; } std::list<CTU::FileInfo::UnsafeUsage> CTU::loadUnsafeUsageListFromXml(const tinyxml2::XMLElement *xmlElement) { std::list<CTU::FileInfo::UnsafeUsage> ret; for (const tinyxml2::XMLElement *e = xmlElement->FirstChildElement(); e; e = e->NextSiblingElement()) { if (std::strcmp(e->Name(), "unsafe-usage") != 0) continue; bool error = false; FileInfo::UnsafeUsage unsafeUsage; unsafeUsage.myId = readAttrString(e, ATTR_MY_ID, &error); unsafeUsage.myArgNr = readAttrInt(e, ATTR_MY_ARGNR, &error); unsafeUsage.myArgumentName = readAttrString(e, ATTR_MY_ARGNAME, &error); unsafeUsage.location.fileName = readAttrString(e, ATTR_LOC_FILENAME, &error); unsafeUsage.location.lineNumber = readAttrInt(e, ATTR_LOC_LINENR, &error); unsafeUsage.location.column = readAttrInt(e, ATTR_LOC_COLUMN, &error); unsafeUsage.value = readAttrInt(e, ATTR_VALUE, &error); if (!error) ret.push_back(std::move(unsafeUsage)); } return ret; } static int isCallFunction(const Scope *scope, int argnr, const Token *&tok) { const Variable * const argvar = scope->function->getArgumentVar(argnr); if (!argvar->isPointer()) return -1; for (const Token *tok2 = scope->bodyStart; tok2 != scope->bodyEnd; tok2 = tok2->next()) { if (tok2->variable() != argvar) continue; if (!Token::Match(tok2->previous(), "[(,] %var% [,)]")) break; int argnr2 = 1; const Token *prev = tok2; while (prev && prev->str() != "(") { if (Token::Match(prev,"]|)")) prev = prev->link(); else if (prev->str() == ",") ++argnr2; prev = prev->previous(); } if (!prev || !Token::Match(prev->previous(), "%name% (")) break; if (!prev->astOperand1() || !prev->astOperand1()->function()) break; tok = prev->previous(); return argnr2; } return -1; } CTU::FileInfo *CTU::getFileInfo(const Tokenizer &tokenizer) { const SymbolDatabase * const symbolDatabase = tokenizer.getSymbolDatabase(); auto *fileInfo = new FileInfo; // Parse all functions in TU for (const Scope &scope : symbolDatabase->scopeList) { if (!scope.isExecutable() || scope.type != Scope::eFunction || !scope.function) continue; const Function *const scopeFunction = scope.function; // source function calls for (const Token *tok = scope.bodyStart; tok != scope.bodyEnd; tok = tok->next()) { if (tok->str() != "(" || !tok->astOperand1() || !tok->astOperand2()) continue; const Function* tokFunction = tok->astOperand1()->function(); if (!tokFunction) continue; const std::vector<const Token *> args(getArguments(tok->previous())); for (int argnr = 0; argnr < args.size(); ++argnr) { const Token *argtok = args[argnr]; if (!argtok) continue; for (const ValueFlow::Value &value : argtok->values()) { if ((!value.isIntValue() || value.intvalue != 0 || value.isInconclusive()) && !value.isBufferSizeValue()) continue; // Skip impossible values since they cannot be represented if (value.isImpossible()) continue; FileInfo::FunctionCall functionCall; functionCall.callValueType = value.valueType; functionCall.callId = getFunctionId(tokenizer, tokFunction); functionCall.callFunctionName = tok->astOperand1()->expressionString(); functionCall.location = FileInfo::Location(tokenizer,tok); functionCall.callArgNr = argnr + 1; functionCall.callArgumentExpression = argtok->expressionString(); functionCall.callArgValue = value.intvalue; functionCall.warning = !value.errorSeverity(); for (const ErrorPathItem &i : value.errorPath) { const std::string& file = tokenizer.list.file(i.first); const std::string& info = i.second; const int line = i.first->linenr(); const int column = i.first->column(); ErrorMessage::FileLocation loc(file, info, line, column); functionCall.callValuePath.push_back(std::move(loc)); } fileInfo->functionCalls.push_back(std::move(functionCall)); } // array if (argtok->variable() && argtok->variable()->isArray() && argtok->variable()->dimensions().size() == 1 && argtok->variable()->dimensionKnown(0)) { FileInfo::FunctionCall functionCall; functionCall.callValueType = ValueFlow::Value::ValueType::BUFFER_SIZE; functionCall.callId = getFunctionId(tokenizer, tokFunction); functionCall.callFunctionName = tok->astOperand1()->expressionString(); functionCall.location = FileInfo::Location(tokenizer, tok); functionCall.callArgNr = argnr + 1; functionCall.callArgumentExpression = argtok->expressionString(); const auto typeSize = argtok->valueType()->typeSize(tokenizer.getSettings().platform); functionCall.callArgValue = typeSize > 0 ? argtok->variable()->dimension(0) * typeSize : -1; functionCall.warning = false; fileInfo->functionCalls.push_back(std::move(functionCall)); } // &var => buffer if (argtok->isUnaryOp("&") && argtok->astOperand1()->variable() && argtok->astOperand1()->valueType() && !argtok->astOperand1()->variable()->isArray()) { FileInfo::FunctionCall functionCall; functionCall.callValueType = ValueFlow::Value::ValueType::BUFFER_SIZE; functionCall.callId = getFunctionId(tokenizer, tokFunction); functionCall.callFunctionName = tok->astOperand1()->expressionString(); functionCall.location = FileInfo::Location(tokenizer, tok); functionCall.callArgNr = argnr + 1; functionCall.callArgumentExpression = argtok->expressionString(); functionCall.callArgValue = argtok->astOperand1()->valueType()->typeSize(tokenizer.getSettings().platform); functionCall.warning = false; fileInfo->functionCalls.push_back(std::move(functionCall)); } // pointer/reference to uninitialized data auto isAddressOfArg = [](const Token* argtok) -> const Token* { if (!argtok->isUnaryOp("&")) return nullptr; argtok = argtok->astOperand1(); if (!argtok || !argtok->valueType() || argtok->valueType()->pointer != 0) return nullptr; return argtok; }; auto isReferenceArg = [&](const Token* argtok) -> const Token* { const Variable* argvar = tokFunction->getArgumentVar(argnr); if (!argvar || !argvar->valueType() || argvar->valueType()->reference == Reference::None) return nullptr; return argtok; }; const Token* addr = isAddressOfArg(argtok); argtok = addr ? addr : isReferenceArg(argtok); if (!argtok || argtok->values().size() != 1U) continue; if (argtok->variable() && argtok->variable()->isClass()) continue; const ValueFlow::Value &v = argtok->values().front(); if (v.valueType == ValueFlow::Value::ValueType::UNINIT && !v.isInconclusive()) { FileInfo::FunctionCall functionCall; functionCall.callValueType = ValueFlow::Value::ValueType::UNINIT; functionCall.callId = getFunctionId(tokenizer, tokFunction); functionCall.callFunctionName = tok->astOperand1()->expressionString(); functionCall.location = FileInfo::Location(tokenizer, tok); functionCall.callArgNr = argnr + 1; functionCall.callArgValue = 0; functionCall.callArgumentExpression = argtok->expressionString(); functionCall.warning = false; fileInfo->functionCalls.push_back(std::move(functionCall)); continue; } } } // Nested function calls for (int argnr = 0; argnr < scopeFunction->argCount(); ++argnr) { const Token *tok; const int argnr2 = isCallFunction(&scope, argnr, tok); if (argnr2 > 0) { FileInfo::NestedCall nestedCall(tokenizer, scopeFunction, tok); nestedCall.myArgNr = argnr + 1; nestedCall.callArgNr = argnr2; fileInfo->nestedCalls.push_back(std::move(nestedCall)); } } } return fileInfo; } static std::list<std::pair<const Token *, MathLib::bigint>> getUnsafeFunction(const Settings &settings, const Scope *scope, int argnr, bool (*isUnsafeUsage)(const Settings &settings, const Token *argtok, MathLib::bigint *value)) { std::list<std::pair<const Token *, MathLib::bigint>> ret; const Variable * const argvar = scope->function->getArgumentVar(argnr); if (!argvar->isArrayOrPointer() && !argvar->isReference()) return ret; for (const Token *tok2 = scope->bodyStart; tok2 != scope->bodyEnd; tok2 = tok2->next()) { if (Token::Match(tok2, ")|else {")) { tok2 = tok2->linkAt(1); if (Token::findmatch(tok2->link(), "return|throw", tok2)) return ret; int indirect = 0; if (argvar->valueType()) indirect = argvar->valueType()->pointer; if (isVariableChanged(tok2->link(), tok2, indirect, argvar->declarationId(), false, settings)) return ret; } if (Token::Match(tok2, "%oror%|&&|?")) { tok2 = tok2->findExpressionStartEndTokens().second; continue; } if (tok2->variable() != argvar) continue; MathLib::bigint value = 0; if (!isUnsafeUsage(settings, tok2, &value)) return ret; // TODO: Is this a read? then continue.. ret.emplace_back(tok2, value); return ret; } return ret; } std::list<CTU::FileInfo::UnsafeUsage> CTU::getUnsafeUsage(const Tokenizer &tokenizer, const Settings &settings, bool (*isUnsafeUsage)(const Settings &settings, const Token *argtok, MathLib::bigint *value)) { std::list<CTU::FileInfo::UnsafeUsage> unsafeUsage; // Parse all functions in TU const SymbolDatabase * const symbolDatabase = tokenizer.getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (!scope.isExecutable() || scope.type != Scope::eFunction || !scope.function) continue; const Function *const function = scope.function; // "Unsafe" functions unconditionally reads data before it is written.. for (int argnr = 0; argnr < function->argCount(); ++argnr) { for (const std::pair<const Token *, MathLib::bigint> &v : getUnsafeFunction(settings, &scope, argnr, isUnsafeUsage)) { const Token *tok = v.first; const MathLib::bigint val = v.second; unsafeUsage.emplace_back(CTU::getFunctionId(tokenizer, function), argnr+1, tok->str(), CTU::FileInfo::Location(tokenizer,tok), val); } } } return unsafeUsage; } static bool findPath(const std::string &callId, nonneg int callArgNr, MathLib::bigint unsafeValue, CTU::FileInfo::InvalidValueType invalidValue, const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> &callsMap, const CTU::FileInfo::CallBase *path[10], int index, bool warning, int maxCtuDepth) { if (index >= maxCtuDepth) return false; // TODO: add bailout message? const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>>::const_iterator it = callsMap.find(callId); if (it == callsMap.end()) return false; for (const CTU::FileInfo::CallBase *c : it->second) { if (c->callArgNr != callArgNr) continue; const auto *functionCall = dynamic_cast<const CTU::FileInfo::FunctionCall *>(c); if (functionCall) { if (!warning && functionCall->warning) continue; switch (invalidValue) { case CTU::FileInfo::InvalidValueType::null: if (functionCall->callValueType != ValueFlow::Value::ValueType::INT || functionCall->callArgValue != 0) continue; break; case CTU::FileInfo::InvalidValueType::uninit: if (functionCall->callValueType != ValueFlow::Value::ValueType::UNINIT) continue; break; case CTU::FileInfo::InvalidValueType::bufferOverflow: if (functionCall->callValueType != ValueFlow::Value::ValueType::BUFFER_SIZE) continue; if (unsafeValue < 0 || (unsafeValue >= functionCall->callArgValue && functionCall->callArgValue >= 0)) break; continue; } path[index] = functionCall; return true; } const auto *nestedCall = dynamic_cast<const CTU::FileInfo::NestedCall *>(c); if (!nestedCall) continue; if (findPath(nestedCall->myId, nestedCall->myArgNr, unsafeValue, invalidValue, callsMap, path, index + 1, warning, maxCtuDepth)) { path[index] = nestedCall; return true; } } return false; } std::list<ErrorMessage::FileLocation> CTU::FileInfo::getErrorPath(InvalidValueType invalidValue, const CTU::FileInfo::UnsafeUsage &unsafeUsage, const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> &callsMap, const char info[], const FunctionCall ** const functionCallPtr, bool warning, int maxCtuDepth) { std::list<ErrorMessage::FileLocation> locationList; const CTU::FileInfo::CallBase *path[10] = {nullptr}; if (!findPath(unsafeUsage.myId, unsafeUsage.myArgNr, unsafeUsage.value, invalidValue, callsMap, path, 0, warning, maxCtuDepth)) return locationList; const std::string value1 = (invalidValue == InvalidValueType::null) ? "null" : "uninitialized"; for (int index = 9; index >= 0; index--) { if (!path[index]) continue; const auto *functionCall = dynamic_cast<const CTU::FileInfo::FunctionCall *>(path[index]); if (functionCall) { if (functionCallPtr) *functionCallPtr = functionCall; std::copy(functionCall->callValuePath.cbegin(), functionCall->callValuePath.cend(), std::back_inserter(locationList)); } std::string info_s = "Calling function " + path[index]->callFunctionName + ", " + std::to_string(path[index]->callArgNr) + getOrdinalText(path[index]->callArgNr) + " argument is " + value1; ErrorMessage::FileLocation fileLoc(path[index]->location.fileName, std::move(info_s), path[index]->location.lineNumber, path[index]->location.column); locationList.push_back(std::move(fileLoc)); } std::string info_s = replaceStr(info, "ARG", unsafeUsage.myArgumentName); ErrorMessage::FileLocation fileLoc2(unsafeUsage.location.fileName, std::move(info_s), unsafeUsage.location.lineNumber, unsafeUsage.location.column); locationList.push_back(std::move(fileLoc2)); return locationList; }
26,521
C++
.cpp
533
39.549719
228
0.592988
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,109
vf_bitand.cpp
danmar_cppcheck/lib/vf_bitand.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_bitand.h" #include "mathlib.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <string> namespace ValueFlow { void analyzeBitAnd(TokenList &tokenlist, const Settings& settings) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (tok->str() != "&") continue; if (tok->hasKnownValue()) continue; if (!tok->astOperand1() || !tok->astOperand2()) continue; MathLib::bigint number; if (MathLib::isInt(tok->astOperand1()->str())) number = MathLib::toBigNumber(tok->astOperand1()->str()); else if (MathLib::isInt(tok->astOperand2()->str())) number = MathLib::toBigNumber(tok->astOperand2()->str()); else continue; int bit = 0; while (bit <= (MathLib::bigint_bits - 2) && ((((MathLib::bigint)1) << bit) < number)) ++bit; if ((((MathLib::bigint)1) << bit) == number) { setTokenValue(tok, Value(0), settings); setTokenValue(tok, Value(number), settings); } } } }
2,000
C++
.cpp
52
31.115385
97
0.610939
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,110
checkersreport.cpp
danmar_cppcheck/lib/checkersreport.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "checkersreport.h" #include "checkers.h" #include "errortypes.h" #include "settings.h" #include <algorithm> #include <cstddef> #include <map> #include <sstream> #include <unordered_set> #include <vector> static bool isCppcheckPremium(const Settings& settings) { return (settings.cppcheckCfgProductName.compare(0, 16, "Cppcheck Premium") == 0); } static int getMisraCVersion(const Settings& settings) { if (settings.premiumArgs.find("misra-c-2012") != std::string::npos) return 2012; if (settings.premiumArgs.find("misra-c-2023") != std::string::npos) return 2023; if (settings.addons.count("misra")) return 2012; const bool misraAddonInfo = std::any_of(settings.addonInfos.cbegin(), settings.addonInfos.cend(), [](const AddonInfo& addonInfo) { return addonInfo.name == "misra"; }); if (misraAddonInfo) return 2012; return 0; } static bool isMisraRuleActive(const std::set<std::string>& activeCheckers, const std::string& rule) { if (activeCheckers.count("Misra C: " + rule)) return true; if (rule == "1.1") return true; // syntax error if (rule == "1.3") return true; // undefined behavior if (rule == "2.1") return activeCheckers.count("CheckCondition::alwaysTrueFalse") != 0; if (rule == "2.6") return activeCheckers.count("CheckOther::checkUnusedLabel") != 0; if (rule == "2.8") return activeCheckers.count("CheckUnusedVar::checkFunctionVariableUsage") != 0; if (rule == "5.3") return activeCheckers.count("CheckOther::checkShadowVariables") != 0; if (rule == "8.13") return activeCheckers.count("CheckOther::checkConstPointer") != 0; if (rule == "9.1") return true; // uninitvar if (rule == "12.5") return activeCheckers.count("CheckOther::checkConstPointer") != 0; if (rule == "14.3") return activeCheckers.count("CheckCondition::alwaysTrueFalse") != 0; if (rule == "17.5") return activeCheckers.count("CheckBufferOverrun::argumentSize") != 0; if (rule == "18.1") return activeCheckers.count("CheckBufferOverrun::pointerArithmetic") != 0; if (rule == "18.2") return activeCheckers.count("CheckOther::checkComparePointers") != 0; if (rule == "18.3") return activeCheckers.count("CheckOther::checkComparePointers") != 0; if (rule == "18.6") return true; // danlingLifetime => error if (rule == "19.1") return activeCheckers.count("CheckOther::checkOverlappingWrite") != 0; if (rule == "20.6") return true; // preprocessorErrorDirective if (rule == "21.13") return activeCheckers.count("CheckFunctions::invalidFunctionUsage") != 0; if (rule == "21.17") return activeCheckers.count("CheckBufferOverrun::bufferOverflow") != 0; if (rule == "21.18") return activeCheckers.count("CheckBufferOverrun::bufferOverflow") != 0; if (rule == "22.1") return true; // memleak => error if (rule == "22.2") return activeCheckers.count("CheckAutoVariables::autoVariables") != 0; if (rule == "22.3") return activeCheckers.count("CheckIO::checkFileUsage") != 0; if (rule == "22.4") return activeCheckers.count("CheckIO::checkFileUsage") != 0; if (rule == "22.6") return activeCheckers.count("CheckIO::checkFileUsage") != 0; return false; } CheckersReport::CheckersReport(const Settings& settings, const std::set<std::string>& activeCheckers) : mSettings(settings), mActiveCheckers(activeCheckers) {} int CheckersReport::getActiveCheckersCount() { if (mAllCheckersCount == 0) { countCheckers(); } return mActiveCheckersCount; } int CheckersReport::getAllCheckersCount() { if (mAllCheckersCount == 0) { countCheckers(); } return mAllCheckersCount; } void CheckersReport::countCheckers() { mActiveCheckersCount = mAllCheckersCount = 0; for (const auto& checkReq: checkers::allCheckers) { if (mActiveCheckers.count(checkReq.first) > 0) ++mActiveCheckersCount; ++mAllCheckersCount; } for (const auto& checkReq: checkers::premiumCheckers) { if (mActiveCheckers.count(checkReq.first) > 0) ++mActiveCheckersCount; ++mAllCheckersCount; } if (mSettings.premiumArgs.find("misra-c-") != std::string::npos || mSettings.addons.count("misra")) { for (const checkers::MisraInfo& info: checkers::misraC2012Rules) { const std::string rule = std::to_string(info.a) + "." + std::to_string(info.b); const bool active = isMisraRuleActive(mActiveCheckers, rule); if (active) ++mActiveCheckersCount; ++mAllCheckersCount; } } } std::string CheckersReport::getReport(const std::string& criticalErrors) const { std::ostringstream fout; fout << "Critical errors" << std::endl; fout << "---------------" << std::endl; if (!criticalErrors.empty()) { fout << "There were critical errors (" << criticalErrors << ")." << std::endl; fout << "These cause the analysis of the file to end prematurely." << std::endl; } else { fout << "No critical errors encountered." << std::endl; // TODO: mention "information" and "debug" as source for indications of bailouts // TODO: still rephrase this - this message does not provides confidence in the results // TODO: document what a bailout is and why it is done - mention it in the upcoming security/tuning guide // TODO: make bailouts a seperate group - need to differentiate between user bailouts (missing data like configuration/includes) and internal bailouts (e.g. limitations of ValueFlow) fout << "Note: There might still have been non-critical bailouts which might lead to false negatives." << std::endl; } fout << std::endl << std::endl; fout << "Open source checkers" << std::endl; fout << "--------------------" << std::endl; std::size_t maxCheckerSize = 0; for (const auto& checkReq: checkers::allCheckers) { const std::string& checker = checkReq.first; maxCheckerSize = std::max(checker.size(), maxCheckerSize); } for (const auto& checkReq: checkers::allCheckers) { const std::string& checker = checkReq.first; const bool active = mActiveCheckers.count(checkReq.first) > 0; const std::string& req = checkReq.second; fout << (active ? "Yes " : "No ") << checker; if (!active && !req.empty()) fout << std::string(maxCheckerSize + 4 - checker.size(), ' ') << "require:" + req; fout << std::endl; } const bool cppcheckPremium = isCppcheckPremium(mSettings); auto reportSection = [&fout, cppcheckPremium] (const std::string& title, const Settings& settings, const std::set<std::string>& activeCheckers, const std::map<std::string, std::string>& premiumCheckers, const std::string& substring) { fout << std::endl << std::endl; fout << title << std::endl; fout << std::string(title.size(), '-') << std::endl; if (!cppcheckPremium) { fout << "Not available, Cppcheck Premium is not used" << std::endl; return; } int maxCheckerSize = 0; for (const auto& checkReq: premiumCheckers) { const std::string& checker = checkReq.first; if (checker.find(substring) != std::string::npos && checker.size() > maxCheckerSize) maxCheckerSize = checker.size(); } for (const auto& checkReq: premiumCheckers) { const std::string& checker = checkReq.first; if (checker.find(substring) == std::string::npos) continue; std::string req = checkReq.second; bool active = cppcheckPremium && activeCheckers.count(checker) > 0; if (substring == "::") { if (req == "warning") active &= settings.severity.isEnabled(Severity::warning); else if (req == "style") active &= settings.severity.isEnabled(Severity::style); else if (req == "portability") active &= settings.severity.isEnabled(Severity::portability); else if (!req.empty()) active = false; // FIXME: handle req } fout << (active ? "Yes " : "No ") << checker; if (!cppcheckPremium) { if (!req.empty()) req = "premium," + req; else req = "premium"; } if (!req.empty()) req = "require:" + req; if (!active) fout << std::string(maxCheckerSize + 4 - checker.size(), ' ') << req; fout << std::endl; } }; reportSection("Premium checkers", mSettings, mActiveCheckers, checkers::premiumCheckers, "::"); reportSection("Autosar", mSettings, mActiveCheckers, checkers::premiumCheckers, "Autosar: "); reportSection("Cert C", mSettings, mActiveCheckers, checkers::premiumCheckers, "Cert C: "); reportSection("Cert C++", mSettings, mActiveCheckers, checkers::premiumCheckers, "Cert C++: "); const int misraCVersion = getMisraCVersion(mSettings); if (misraCVersion == 0) { fout << std::endl << std::endl; fout << "Misra C" << std::endl; fout << "-------" << std::endl; fout << "Misra is not enabled" << std::endl; } else { fout << std::endl << std::endl; fout << "Misra C " << misraCVersion << std::endl; fout << "------------" << std::endl; for (const checkers::MisraInfo& info: checkers::misraC2012Directives) { const std::string directive = "Dir " + std::to_string(info.a) + "." + std::to_string(info.b); const bool active = isMisraRuleActive(mActiveCheckers, directive); fout << (active ? "Yes " : "No ") << "Misra C " << misraCVersion << ": " << directive; std::string extra; if (misraCVersion == 2012 && info.amendment >= 1) extra = " amendment:" + std::to_string(info.amendment); if (!extra.empty()) fout << std::string(10 - directive.size(), ' ') << extra; fout << '\n'; } for (const checkers::MisraInfo& info: checkers::misraC2012Rules) { const std::string rule = std::to_string(info.a) + "." + std::to_string(info.b); const bool active = isMisraRuleActive(mActiveCheckers, rule); fout << (active ? "Yes " : "No ") << "Misra C " << misraCVersion << ": " << rule; std::string extra; if (misraCVersion == 2012 && info.amendment >= 1) extra = " amendment:" + std::to_string(info.amendment); std::string reqs; if (info.amendment >= 3) reqs += ",premium"; if (!active && !reqs.empty()) extra += " require:" + reqs.substr(1); if (!extra.empty()) fout << std::string(10 - rule.size(), ' ') << extra; fout << '\n'; } } reportSection("Misra C++ 2008", mSettings, mActiveCheckers, checkers::premiumCheckers, "Misra C++ 2008: "); reportSection("Misra C++ 2023", mSettings, mActiveCheckers, checkers::premiumCheckers, "Misra C++ 2023: "); return fout.str(); } std::string CheckersReport::getXmlReport(const std::string& criticalErrors) const { std::string ret; if (!criticalErrors.empty()) ret += " <critical-errors>" + criticalErrors + "</critical-errors>\n"; else ret += " <critical-errors/>\n"; ret += " <checkers-report>\n"; const int misraCVersion = getMisraCVersion(mSettings); for (std::string checker: mActiveCheckers) { if (checker.compare(0,8,"Misra C:") == 0) checker = "Misra C " + std::to_string(misraCVersion) + ":" + checker.substr(8); ret += " <checker id=\"" + checker + "\"/>\n"; } ret += " </checkers-report>"; return ret; }
13,077
C++
.cpp
285
37.680702
190
0.604558
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,111
checkother.cpp
danmar_cppcheck/lib/checkother.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkother.h" #include "astutils.h" #include "fwdanalysis.h" #include "library.h" #include "mathlib.h" #include "platform.h" #include "settings.h" #include "standards.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include "utils.h" #include "valueflow.h" #include "vfvalue.h" #include <algorithm> // find_if() #include <cctype> #include <cstddef> #include <cstdint> #include <list> #include <map> #include <set> #include <sstream> #include <utility> //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckOther instance; } static const CWE CWE128(128U); // Wrap-around Error static const CWE CWE131(131U); // Incorrect Calculation of Buffer Size static const CWE CWE197(197U); // Numeric Truncation Error static const CWE CWE362(362U); // Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') static const CWE CWE369(369U); // Divide By Zero static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE475(475U); // Undefined Behavior for Input to API static const CWE CWE561(561U); // Dead Code static const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable') static const CWE CWE570(570U); // Expression is Always False static const CWE CWE571(571U); // Expression is Always True static const CWE CWE672(672U); // Operation on a Resource after Expiration or Release static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments static const CWE CWE683(683U); // Function Call With Incorrect Order of Arguments static const CWE CWE704(704U); // Incorrect Type Conversion or Cast static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior static const CWE CWE768(768U); // Incorrect Short Circuit Evaluation static const CWE CWE783(783U); // Operator Precedence Logic Error //---------------------------------------------------------------------------------- // The return value of fgetc(), getc(), ungetc(), getchar() etc. is an integer value. // If this return value is stored in a character variable and then compared // to EOF, which is an integer, the comparison maybe be false. // // Reference: // - Ticket #160 // - http://www.cplusplus.com/reference/cstdio/fgetc/ // - http://www.cplusplus.com/reference/cstdio/getc/ // - http://www.cplusplus.com/reference/cstdio/getchar/ // - http://www.cplusplus.com/reference/cstdio/ungetc/ ... //---------------------------------------------------------------------------------- void CheckOther::checkCastIntToCharAndBack() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckOther::checkCastIntToCharAndBack"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { std::map<int, std::string> vars; for (const Token* tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) { // Quick check to see if any of the matches below have any chances if (!Token::Match(tok, "%var%|EOF %comp%|=")) continue; if (Token::Match(tok, "%var% = fclose|fflush|fputc|fputs|fscanf|getchar|getc|fgetc|putchar|putc|puts|scanf|sscanf|ungetc (")) { const Variable *var = tok->variable(); if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) { vars[tok->varId()] = tok->strAt(2); } } else if (Token::Match(tok, "EOF %comp% ( %var% = fclose|fflush|fputc|fputs|fscanf|getchar|getc|fgetc|putchar|putc|puts|scanf|sscanf|ungetc (")) { tok = tok->tokAt(3); const Variable *var = tok->variable(); if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) { checkCastIntToCharAndBackError(tok, tok->strAt(2)); } } else if (tok->isCpp() && (Token::Match(tok, "EOF %comp% ( %var% = std :: cin . get (") || Token::Match(tok, "EOF %comp% ( %var% = cin . get ("))) { tok = tok->tokAt(3); const Variable *var = tok->variable(); if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) { checkCastIntToCharAndBackError(tok, "cin.get"); } } else if (tok->isCpp() && (Token::Match(tok, "%var% = std :: cin . get (") || Token::Match(tok, "%var% = cin . get ("))) { const Variable *var = tok->variable(); if (var && var->typeEndToken()->str() == "char" && !var->typeEndToken()->isSigned()) { vars[tok->varId()] = "cin.get"; } } else if (Token::Match(tok, "%var% %comp% EOF")) { if (vars.find(tok->varId()) != vars.end()) { checkCastIntToCharAndBackError(tok, vars[tok->varId()]); } } else if (Token::Match(tok, "EOF %comp% %var%")) { tok = tok->tokAt(2); if (vars.find(tok->varId()) != vars.end()) { checkCastIntToCharAndBackError(tok, vars[tok->varId()]); } } } } } void CheckOther::checkCastIntToCharAndBackError(const Token *tok, const std::string &strFunctionName) { reportError( tok, Severity::warning, "checkCastIntToCharAndBack", "$symbol:" + strFunctionName + "\n" "Storing $symbol() return value in char variable and then comparing with EOF.\n" "When saving $symbol() return value in char variable there is loss of precision. " " When $symbol() returns EOF this value is truncated. Comparing the char " "variable with EOF can have unexpected results. For instance a loop \"while (EOF != (c = $symbol());\" " "loops forever on some compilers/platforms and on other compilers/platforms it will stop " "when the file contains a matching character.", CWE197, Certainty::normal ); } //--------------------------------------------------------------------------- // Clarify calculation precedence for ternary operators. //--------------------------------------------------------------------------- void CheckOther::clarifyCalculation() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("clarifyCalculation")) return; logChecker("CheckOther::clarifyCalculation"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { // ? operator where lhs is arithmetical expression if (tok->str() != "?" || !tok->astOperand1() || !tok->astOperand1()->isCalculation()) continue; if (!tok->astOperand1()->isArithmeticalOp() && tok->astOperand1()->tokType() != Token::eBitOp) continue; // non-pointer calculation in lhs and pointer in rhs => no clarification is needed if (tok->astOperand1()->isBinaryOp() && Token::Match(tok->astOperand1(), "%or%|&|%|*|/") && tok->astOperand2()->valueType() && tok->astOperand2()->valueType()->pointer > 0) continue; // bit operation in lhs and char literals in rhs => probably no mistake if (tok->astOperand1()->tokType() == Token::eBitOp && Token::Match(tok->astOperand2()->astOperand1(), "%char%") && Token::Match(tok->astOperand2()->astOperand2(), "%char%")) continue; // 2nd operand in lhs has known integer value => probably no mistake if (tok->astOperand1()->isBinaryOp() && tok->astOperand1()->astOperand2()->hasKnownIntValue()) { const Token *op = tok->astOperand1()->astOperand2(); if (op->isNumber()) continue; if (op->valueType() && op->valueType()->isEnum()) continue; } // Is code clarified by parentheses already? const Token *tok2 = tok->astOperand1(); for (; tok2; tok2 = tok2->next()) { if (tok2->str() == "(") tok2 = tok2->link(); else if (tok2->str() == ")") break; else if (tok2->str() == "?") { clarifyCalculationError(tok, tok->astOperand1()->str()); break; } } } } } void CheckOther::clarifyCalculationError(const Token *tok, const std::string &op) { // suspicious calculation const std::string calc("'a" + op + "b?c:d'"); // recommended calculation #1 const std::string s1("'(a" + op + "b)?c:d'"); // recommended calculation #2 const std::string s2("'a" + op + "(b?c:d)'"); reportError(tok, Severity::style, "clarifyCalculation", "Clarify calculation precedence for '" + op + "' and '?'.\n" "Suspicious calculation. Please use parentheses to clarify the code. " "The code '" + calc + "' should be written as either '" + s1 + "' or '" + s2 + "'.", CWE783, Certainty::normal); } //--------------------------------------------------------------------------- // Clarify (meaningless) statements like *foo++; with parentheses. //--------------------------------------------------------------------------- void CheckOther::clarifyStatement() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckOther::clarifyStatement"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { if (tok->astOperand1() && Token::Match(tok, "* %name%")) { const Token *tok2 = tok->previous(); while (tok2 && tok2->str() == "*") tok2 = tok2->previous(); if (tok2 && !tok2->astParent() && Token::Match(tok2, "[{};]")) { tok2 = tok->astOperand1(); if (Token::Match(tok2, "++|-- [;,]")) clarifyStatementError(tok2); } } } } } void CheckOther::clarifyStatementError(const Token *tok) { reportError(tok, Severity::warning, "clarifyStatement", "In expression like '*A++' the result of '*' is unused. Did you intend to write '(*A)++;'?\n" "A statement like '*A++;' might not do what you intended. Postfix 'operator++' is executed before 'operator*'. " "Thus, the dereference is meaningless. Did you intend to write '(*A)++;'?", CWE783, Certainty::normal); } //--------------------------------------------------------------------------- // Check for suspicious occurrences of 'if(); {}'. //--------------------------------------------------------------------------- void CheckOther::checkSuspiciousSemicolon() { if (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning)) return; const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); logChecker("CheckOther::checkSuspiciousSemicolon"); // warning,inconclusive // Look for "if(); {}", "for(); {}" or "while(); {}" for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type == Scope::eIf || scope.type == Scope::eElse || scope.type == Scope::eWhile || scope.type == Scope::eFor) { // Ensure the semicolon is at the same line number as the if/for/while statement // and the {..} block follows it without an extra empty line. if (Token::simpleMatch(scope.bodyStart, "{ ; } {") && scope.bodyStart->previous()->linenr() == scope.bodyStart->tokAt(2)->linenr() && scope.bodyStart->linenr()+1 >= scope.bodyStart->tokAt(3)->linenr() && !scope.bodyStart->tokAt(3)->isExpandedMacro()) { suspiciousSemicolonError(scope.classDef); } } } } void CheckOther::suspiciousSemicolonError(const Token* tok) { reportError(tok, Severity::warning, "suspiciousSemicolon", "Suspicious use of ; at the end of '" + (tok ? tok->str() : std::string()) + "' statement.", CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // For C++ code, warn if C-style casts are used on pointer types //--------------------------------------------------------------------------- void CheckOther::warningOldStylePointerCast() { // Only valid on C++ code if (!mTokenizer->isCPP()) return; if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("cstyleCast")) return; logChecker("CheckOther::warningOldStylePointerCast"); // style,c++ const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { const Token* tok; if (scope->function && scope->function->isConstructor()) tok = scope->classDef; else tok = scope->bodyStart; for (; tok && tok != scope->bodyEnd; tok = tok->next()) { // Old style pointer casting.. if (tok->str() != "(") continue; const Token* castTok = tok->next(); while (Token::Match(castTok, "const|volatile|class|struct|union|%type%|::")) { castTok = castTok->next(); if (Token::simpleMatch(castTok, "<") && castTok->link()) castTok = castTok->link()->next(); } if (castTok == tok->next()) continue; bool isPtr = false, isRef = false; while (Token::Match(castTok, "*|const|&")) { if (castTok->str() == "*") isPtr = true; else if (castTok->str() == "&") isRef = true; castTok = castTok->next(); } if ((!isPtr && !isRef) || !Token::Match(castTok, ") (| %name%|%num%|%bool%|%char%|%str%|&")) continue; if (Token::Match(tok->previous(), "%type%")) continue; // skip first "const" in "const Type* const" while (Token::Match(tok->next(), "const|volatile|class|struct|union")) tok = tok->next(); const Token* typeTok = tok->next(); // skip second "const" in "const Type* const" if (tok->strAt(3) == "const") tok = tok->next(); const Token *p = tok->tokAt(4); if (p->hasKnownIntValue() && p->values().front().intvalue==0) // Casting nullpointers is safe continue; if (typeTok->tokType() == Token::eType || typeTok->tokType() == Token::eName) cstyleCastError(tok, isPtr); } } } void CheckOther::cstyleCastError(const Token *tok, bool isPtr) { const std::string type = isPtr ? "pointer" : "reference"; reportError(tok, Severity::style, "cstyleCast", "C-style " + type + " casting\n" "C-style " + type + " casting detected. C++ offers four different kinds of casts as replacements: " "static_cast, const_cast, dynamic_cast and reinterpret_cast. A C-style cast could evaluate to " "any of those automatically, thus it is considered safer if the programmer explicitly states " "which kind of cast is expected.", CWE398, Certainty::normal); } void CheckOther::suspiciousFloatingPointCast() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("suspiciousFloatingPointCast")) return; logChecker("CheckOther::suspiciousFloatingPointCast"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { const Token* tok = scope->bodyStart; if (scope->function && scope->function->isConstructor()) tok = scope->classDef; for (; tok && tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isCast()) continue; const ValueType* vt = tok->valueType(); if (!vt || vt->pointer || vt->reference != Reference::None || (vt->type != ValueType::FLOAT && vt->type != ValueType::DOUBLE)) continue; using VTT = std::vector<ValueType::Type>; const VTT sourceTypes = vt->type == ValueType::FLOAT ? VTT{ ValueType::DOUBLE, ValueType::LONGDOUBLE } : VTT{ ValueType::LONGDOUBLE }; const Token* source = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1(); if (!source || !source->valueType() || std::find(sourceTypes.begin(), sourceTypes.end(), source->valueType()->type) == sourceTypes.end()) continue; const Token* parent = tok->astParent(); if (!parent) continue; const ValueType* parentVt = parent->valueType(); if (!parentVt || parent->str() == "(") { int argn{}; if (const Token* ftok = getTokenArgumentFunction(tok, argn)) { if (ftok->function()) { if (const Variable* argVar = ftok->function()->getArgumentVar(argn)) parentVt = argVar->valueType(); } } } if (!parentVt || std::find(sourceTypes.begin(), sourceTypes.end(), parentVt->type) == sourceTypes.end()) continue; suspiciousFloatingPointCastError(tok); } } } void CheckOther::suspiciousFloatingPointCastError(const Token* tok) { reportError(tok, Severity::style, "suspiciousFloatingPointCast", "Floating-point cast causes loss of precision.\n" "If this cast is not intentional, remove it to avoid loss of precision", CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // float* f; double* d = (double*)f; <-- Pointer cast to a type with an incompatible binary data representation //--------------------------------------------------------------------------- void CheckOther::invalidPointerCast() { if (!mSettings->severity.isEnabled(Severity::portability)) return; logChecker("CheckOther::invalidPointerCast"); // portability const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { const Token* toTok = nullptr; const Token* fromTok = nullptr; // Find cast if (Token::Match(tok, "( const|volatile| const|volatile| %type% %type%| const| * )")) { toTok = tok; fromTok = tok->astOperand1(); } else if (Token::simpleMatch(tok, "reinterpret_cast <") && tok->linkAt(1)) { toTok = tok->linkAt(1)->next(); fromTok = toTok->astOperand2(); } if (!fromTok) continue; const ValueType* fromType = fromTok->valueType(); const ValueType* toType = toTok->valueType(); if (!fromType || !toType || !fromType->pointer || !toType->pointer) continue; if (fromType->type != toType->type && fromType->type >= ValueType::Type::BOOL && toType->type >= ValueType::Type::BOOL && (toType->type != ValueType::Type::CHAR || printInconclusive)) { if (toType->isIntegral() && fromType->isIntegral()) continue; invalidPointerCastError(tok, fromType->str(), toType->str(), toType->type == ValueType::Type::CHAR, toType->isIntegral()); } } } } void CheckOther::invalidPointerCastError(const Token* tok, const std::string& from, const std::string& to, bool inconclusive, bool toIsInt) { if (toIsInt) { // If we cast something to int*, this can be useful to play with its binary data representation reportError(tok, Severity::portability, "invalidPointerCast", "Casting from " + from + " to " + to + " is not portable due to different binary data representations on different platforms.", CWE704, inconclusive ? Certainty::inconclusive : Certainty::normal); } else reportError(tok, Severity::portability, "invalidPointerCast", "Casting between " + from + " and " + to + " which have an incompatible binary data representation.", CWE704, Certainty::normal); } //--------------------------------------------------------------------------- // Detect redundant assignments: x = 0; x = 4; //--------------------------------------------------------------------------- void CheckOther::checkRedundantAssignment() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("redundantAssignment") && !mSettings->isPremiumEnabled("redundantAssignInSwitch")) return; logChecker("CheckOther::checkRedundantAssignment"); // style const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { if (!scope->bodyStart) continue; for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (Token::simpleMatch(tok, "] (")) // todo: handle lambdas break; if (Token::simpleMatch(tok, "try {")) // todo: check try blocks tok = tok->linkAt(1); if ((tok->isAssignmentOp() || tok->tokType() == Token::eIncDecOp) && tok->astOperand1()) { if (tok->astParent()) continue; // Do not warn about redundant initialization when rhs is trivial // TODO : do not simplify the variable declarations bool isInitialization = false; if (Token::Match(tok->tokAt(-2), "; %var% =") && tok->tokAt(-2)->isSplittedVarDeclEq()) { isInitialization = true; bool trivial = true; visitAstNodes(tok->astOperand2(), [&](const Token *rhs) { if (Token::simpleMatch(rhs, "{ 0 }")) return ChildrenToVisit::none; if (Token::Match(rhs, "%str%|%num%|%name%") && !rhs->varId()) return ChildrenToVisit::none; if (Token::Match(rhs, ":: %name%") && rhs->hasKnownIntValue()) return ChildrenToVisit::none; if (rhs->isCast()) return ChildrenToVisit::op2; trivial = false; return ChildrenToVisit::done; }); if (trivial) continue; } const Token* rhs = tok->astOperand2(); // Do not warn about assignment with 0 / NULL if ((rhs && MathLib::isNullValue(rhs->str())) || isNullOperand(rhs)) continue; if (tok->astOperand1()->variable() && tok->astOperand1()->variable()->isReference()) // todo: check references continue; if (tok->astOperand1()->variable() && tok->astOperand1()->variable()->isStatic()) // todo: check static variables continue; bool inconclusive = false; if (tok->isCpp() && tok->astOperand1()->valueType()) { // If there is a custom assignment operator => this is inconclusive if (tok->astOperand1()->valueType()->typeScope) { const std::string op = "operator" + tok->str(); const std::list<Function>& fList = tok->astOperand1()->valueType()->typeScope->functionList; inconclusive = std::any_of(fList.cbegin(), fList.cend(), [&](const Function& f) { return f.name() == op; }); } // assigning a smart pointer has side effects if (tok->astOperand1()->valueType()->type == ValueType::SMART_POINTER) break; } if (inconclusive && !mSettings->certainty.isEnabled(Certainty::inconclusive)) continue; FwdAnalysis fwdAnalysis(*mSettings); if (fwdAnalysis.hasOperand(tok->astOperand2(), tok->astOperand1())) continue; // Is there a redundant assignment? const Token *start; if (tok->isAssignmentOp()) start = tok->next(); else start = tok->findExpressionStartEndTokens().second->next(); const Token * tokenToCheck = tok->astOperand1(); // Check if we are working with union for (const Token* tempToken = tokenToCheck; Token::simpleMatch(tempToken, ".");) { tempToken = tempToken->astOperand1(); if (tempToken && tempToken->variable() && tempToken->variable()->type() && tempToken->variable()->type()->isUnionType()) tokenToCheck = tempToken; } if (start->hasKnownSymbolicValue(tokenToCheck) && Token::simpleMatch(start->astParent(), "=") && !diag(tok)) { const ValueFlow::Value* val = start->getKnownValue(ValueFlow::Value::ValueType::SYMBOLIC); if (val->intvalue == 0) // no offset redundantAssignmentSameValueError(tokenToCheck, val, tok->astOperand1()->expressionString()); } // Get next assignment.. const Token *nextAssign = fwdAnalysis.reassign(tokenToCheck, start, scope->bodyEnd); // extra check for union if (nextAssign && tokenToCheck != tok->astOperand1()) nextAssign = fwdAnalysis.reassign(tok->astOperand1(), start, scope->bodyEnd); if (!nextAssign) continue; // there is redundant assignment. Is there a case between the assignments? bool hasCase = false; for (const Token *tok2 = tok; tok2 != nextAssign; tok2 = tok2->next()) { if (tok2->str() == "break" || tok2->str() == "return") break; if (tok2->str() == "case") { hasCase = true; break; } } // warn if (hasCase) redundantAssignmentInSwitchError(tok, nextAssign, tok->astOperand1()->expressionString()); else if (isInitialization) redundantInitializationError(tok, nextAssign, tok->astOperand1()->expressionString(), inconclusive); else { diag(nextAssign); redundantAssignmentError(tok, nextAssign, tok->astOperand1()->expressionString(), inconclusive); } } } } } void CheckOther::redundantCopyError(const Token *tok1, const Token* tok2, const std::string& var) { const std::list<const Token *> callstack = { tok1, tok2 }; reportError(callstack, Severity::performance, "redundantCopy", "$symbol:" + var + "\n" "Buffer '$symbol' is being written before its old content has been used.", CWE563, Certainty::normal); } void CheckOther::redundantAssignmentError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive) { const ErrorPath errorPath = { ErrorPathItem(tok1, var + " is assigned"), ErrorPathItem(tok2, var + " is overwritten") }; if (inconclusive) reportError(errorPath, Severity::style, "redundantAssignment", "$symbol:" + var + "\n" "Variable '$symbol' is reassigned a value before the old one has been used if variable is no semaphore variable.\n" "Variable '$symbol' is reassigned a value before the old one has been used. Make sure that this variable is not used like a semaphore in a threading environment before simplifying this code.", CWE563, Certainty::inconclusive); else reportError(errorPath, Severity::style, "redundantAssignment", "$symbol:" + var + "\n" "Variable '$symbol' is reassigned a value before the old one has been used.", CWE563, Certainty::normal); } void CheckOther::redundantInitializationError(const Token *tok1, const Token* tok2, const std::string& var, bool inconclusive) { const ErrorPath errorPath = { ErrorPathItem(tok1, var + " is initialized"), ErrorPathItem(tok2, var + " is overwritten") }; reportError(errorPath, Severity::style, "redundantInitialization", "$symbol:" + var + "\nRedundant initialization for '$symbol'. The initialized value is overwritten before it is read.", CWE563, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckOther::redundantAssignmentInSwitchError(const Token *tok1, const Token* tok2, const std::string &var) { const ErrorPath errorPath = { ErrorPathItem(tok1, "$symbol is assigned"), ErrorPathItem(tok2, "$symbol is overwritten") }; reportError(errorPath, Severity::style, "redundantAssignInSwitch", "$symbol:" + var + "\n" "Variable '$symbol' is reassigned a value before the old one has been used. 'break;' missing?", CWE563, Certainty::normal); } void CheckOther::redundantAssignmentSameValueError(const Token *tok, const ValueFlow::Value* val, const std::string &var) { auto errorPath = val->errorPath; errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::style, "redundantAssignment", "$symbol:" + var + "\n" "Variable '$symbol' is assigned an expression that holds the same value.", CWE563, Certainty::normal); } //--------------------------------------------------------------------------- // switch (x) // { // case 2: // y = a; // <- this assignment is redundant // case 3: // y = b; // <- case 2 falls through and sets y twice // } //--------------------------------------------------------------------------- static inline bool isFunctionOrBreakPattern(const Token *tok) { return Token::Match(tok, "%name% (") || Token::Match(tok, "break|continue|return|exit|goto|throw"); } void CheckOther::redundantBitwiseOperationInSwitchError() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckOther::redundantBitwiseOperationInSwitch"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); // Find the beginning of a switch. E.g.: // switch (var) { ... for (const Scope &switchScope : symbolDatabase->scopeList) { if (switchScope.type != Scope::eSwitch || !switchScope.bodyStart) continue; // Check the contents of the switch statement std::map<int, const Token*> varsWithBitsSet; std::map<int, std::string> bitOperations; for (const Token *tok2 = switchScope.bodyStart->next(); tok2 != switchScope.bodyEnd; tok2 = tok2->next()) { if (tok2->str() == "{") { // Inside a conditional or loop. Don't mark variable accesses as being redundant. E.g.: // case 3: b = 1; // case 4: if (a) { b = 2; } // Doesn't make the b=1 redundant because it's conditional if (Token::Match(tok2->previous(), ")|else {") && tok2->link()) { const Token* endOfConditional = tok2->link(); for (const Token* tok3 = tok2; tok3 != endOfConditional; tok3 = tok3->next()) { if (tok3->varId() != 0) { varsWithBitsSet.erase(tok3->varId()); bitOperations.erase(tok3->varId()); } else if (isFunctionOrBreakPattern(tok3)) { varsWithBitsSet.clear(); bitOperations.clear(); } } tok2 = endOfConditional; } } // Variable assignment. Report an error if it's assigned to twice before a break. E.g.: // case 3: b = 1; // <== redundant // case 4: b = 2; if (Token::Match(tok2->previous(), ";|{|}|: %var% = %any% ;")) { varsWithBitsSet.erase(tok2->varId()); bitOperations.erase(tok2->varId()); } // Bitwise operation. Report an error if it's performed twice before a break. E.g.: // case 3: b |= 1; // <== redundant // case 4: b |= 1; else if (Token::Match(tok2->previous(), ";|{|}|: %var% %assign% %num% ;") && (tok2->strAt(1) == "|=" || tok2->strAt(1) == "&=") && Token::Match(tok2->next()->astOperand2(), "%num%")) { const std::string bitOp = tok2->strAt(1)[0] + tok2->strAt(2); const std::map<int, const Token*>::const_iterator i2 = varsWithBitsSet.find(tok2->varId()); // This variable has not had a bit operation performed on it yet, so just make a note of it if (i2 == varsWithBitsSet.end()) { varsWithBitsSet[tok2->varId()] = tok2; bitOperations[tok2->varId()] = bitOp; } // The same bit operation has been performed on the same variable twice, so report an error else if (bitOperations[tok2->varId()] == bitOp) redundantBitwiseOperationInSwitchError(i2->second, i2->second->str()); // A different bit operation was performed on the variable, so clear it else { varsWithBitsSet.erase(tok2->varId()); bitOperations.erase(tok2->varId()); } } // Bitwise operation. Report an error if it's performed twice before a break. E.g.: // case 3: b = b | 1; // <== redundant // case 4: b = b | 1; else if (Token::Match(tok2->previous(), ";|{|}|: %var% = %name% %or%|& %num% ;") && tok2->varId() == tok2->tokAt(2)->varId()) { const std::string bitOp = tok2->strAt(3) + tok2->strAt(4); const std::map<int, const Token*>::const_iterator i2 = varsWithBitsSet.find(tok2->varId()); // This variable has not had a bit operation performed on it yet, so just make a note of it if (i2 == varsWithBitsSet.end()) { varsWithBitsSet[tok2->varId()] = tok2; bitOperations[tok2->varId()] = bitOp; } // The same bit operation has been performed on the same variable twice, so report an error else if (bitOperations[tok2->varId()] == bitOp) redundantBitwiseOperationInSwitchError(i2->second, i2->second->str()); // A different bit operation was performed on the variable, so clear it else { varsWithBitsSet.erase(tok2->varId()); bitOperations.erase(tok2->varId()); } } // Not a simple assignment so there may be good reason if this variable is assigned to twice. E.g.: // case 3: b = 1; // case 4: b++; else if (tok2->varId() != 0 && tok2->strAt(1) != "|" && tok2->strAt(1) != "&") { varsWithBitsSet.erase(tok2->varId()); bitOperations.erase(tok2->varId()); } // Reset our record of assignments if there is a break or function call. E.g.: // case 3: b = 1; break; if (isFunctionOrBreakPattern(tok2)) { varsWithBitsSet.clear(); bitOperations.clear(); } } } } void CheckOther::redundantBitwiseOperationInSwitchError(const Token *tok, const std::string &varname) { reportError(tok, Severity::style, "redundantBitwiseOperationInSwitch", "$symbol:" + varname + "\n" "Redundant bitwise operation on '$symbol' in 'switch' statement. 'break;' missing?"); } //--------------------------------------------------------------------------- // Check for statements like case A||B: in switch() //--------------------------------------------------------------------------- void CheckOther::checkSuspiciousCaseInSwitch() { if (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckOther::checkSuspiciousCaseInSwitch"); // warning,inconclusive const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope & scope : symbolDatabase->scopeList) { if (scope.type != Scope::eSwitch) continue; for (const Token* tok = scope.bodyStart->next(); tok != scope.bodyEnd; tok = tok->next()) { if (tok->str() == "case") { const Token* finding = nullptr; for (const Token* tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == ":") break; if (Token::Match(tok2, "[;}{]")) break; if (tok2->str() == "?") finding = nullptr; else if (Token::Match(tok2, "&&|%oror%")) finding = tok2; } if (finding) suspiciousCaseInSwitchError(finding, finding->str()); } } } } void CheckOther::suspiciousCaseInSwitchError(const Token* tok, const std::string& operatorString) { reportError(tok, Severity::warning, "suspiciousCase", "Found suspicious case label in switch(). Operator '" + operatorString + "' probably doesn't work as intended.\n" "Using an operator like '" + operatorString + "' in a case label is suspicious. Did you intend to use a bitwise operator, multiple case labels or if/else instead?", CWE398, Certainty::inconclusive); } //--------------------------------------------------------------------------- // Find consecutive return, break, continue, goto or throw statements. e.g.: // break; break; // Detect dead code, that follows such a statement. e.g.: // return(0); foo(); //--------------------------------------------------------------------------- void CheckOther::checkUnreachableCode() { // misra-c-2012-2.1 // misra-c-2023-2.1 // misra-cpp-2008-0-1-1 // autosar if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("duplicateBreak") && !mSettings->isPremiumEnabled("unreachableCode")) return; logChecker("CheckOther::checkUnreachableCode"); // style const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { const Token* secondBreak = nullptr; const Token* labelName = nullptr; if (tok->link() && Token::Match(tok, "(|[|<")) tok = tok->link(); else if (Token::Match(tok, "break|continue ;")) secondBreak = tok->tokAt(2); else if (Token::Match(tok, "[;{}:] return|throw") && tok->next()->isKeyword()) { if (Token::simpleMatch(tok->astParent(), "?")) continue; tok = tok->next(); // tok should point to return or throw for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == "{") tok2 = tok2->link(); if (tok2->str() == ";") { secondBreak = tok2->next(); break; } } } else if (Token::Match(tok, "goto %any% ;")) { secondBreak = tok->tokAt(3); labelName = tok->next(); } else if (Token::Match(tok, "%name% (") && mSettings->library.isnoreturn(tok) && !Token::Match(tok->next()->astParent(), "?|:")) { if ((!tok->function() || (tok->function()->token != tok && tok->function()->tokenDef != tok)) && tok->linkAt(1)->strAt(1) != "{") secondBreak = tok->linkAt(1)->tokAt(2); if (Token::simpleMatch(secondBreak, "return")) { // clarification for tools that function returns continue; } } // Statements follow directly, no line between them. (#3383) // TODO: Try to find a better way to avoid false positives due to preprocessor configurations. const bool inconclusive = secondBreak && (secondBreak->linenr() - 1 > secondBreak->previous()->linenr()); if (secondBreak && (printInconclusive || !inconclusive)) { if (Token::Match(secondBreak, "continue|goto|throw|return") && secondBreak->isKeyword()) { duplicateBreakError(secondBreak, inconclusive); tok = Token::findmatch(secondBreak, "[}:]"); } else if (secondBreak->str() == "break") { // break inside switch as second break statement should not issue a warning if (tok->str() == "break") // If the previous was a break, too: Issue warning duplicateBreakError(secondBreak, inconclusive); else { if (tok->scope()->type != Scope::eSwitch) // Check, if the enclosing scope is a switch duplicateBreakError(secondBreak, inconclusive); } tok = Token::findmatch(secondBreak, "[}:]"); } else if (!Token::Match(secondBreak, "return|}|case|default") && secondBreak->strAt(1) != ":") { // TODO: No bailout for unconditional scopes // If the goto label is followed by a loop construct in which the label is defined it's quite likely // that the goto jump was intended to skip some code on the first loop iteration. bool labelInFollowingLoop = false; if (labelName && Token::Match(secondBreak, "while|do|for")) { const Token *scope2 = Token::findsimplematch(secondBreak, "{"); if (scope2) { for (const Token *tokIter = scope2; tokIter != scope2->link() && tokIter; tokIter = tokIter->next()) { if (Token::Match(tokIter, "[;{}] %any% :") && labelName->str() == tokIter->strAt(1)) { labelInFollowingLoop = true; break; } } } } // hide FP for statements that just hide compiler warnings about unused function arguments bool silencedCompilerWarningOnly = false; const Token *silencedWarning = secondBreak; for (;;) { if (Token::Match(silencedWarning, "( void ) %name% ;")) { silencedWarning = silencedWarning->tokAt(5); continue; } if (silencedWarning && silencedWarning == scope->bodyEnd) silencedCompilerWarningOnly = true; break; } if (silencedWarning) secondBreak = silencedWarning; if (!labelInFollowingLoop && !silencedCompilerWarningOnly) unreachableCodeError(secondBreak, tok, inconclusive); tok = Token::findmatch(secondBreak, "[}:]"); } else if (secondBreak->scope() && secondBreak->scope()->isLoopScope() && secondBreak->str() == "}" && tok->str() == "continue") { redundantContinueError(tok); tok = secondBreak; } else tok = secondBreak; if (!tok) break; tok = tok->previous(); // Will be advanced again by for loop } } } } void CheckOther::duplicateBreakError(const Token *tok, bool inconclusive) { reportError(tok, Severity::style, "duplicateBreak", "Consecutive return, break, continue, goto or throw statements are unnecessary.\n" "Consecutive return, break, continue, goto or throw statements are unnecessary. " "The second statement can never be executed, and so should be removed.", CWE561, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckOther::unreachableCodeError(const Token *tok, const Token* noreturn, bool inconclusive) { std::string msg = "Statements following "; if (noreturn && (noreturn->function() || mSettings->library.isnoreturn(noreturn))) msg += "noreturn function '" + noreturn->str() + "()'"; else if (noreturn && noreturn->isKeyword()) msg += "'" + noreturn->str() + "'"; else msg += "return, break, continue, goto or throw"; msg += " will never be executed."; reportError(tok, Severity::style, "unreachableCode", msg, CWE561, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckOther::redundantContinueError(const Token *tok) { reportError(tok, Severity::style, "redundantContinue", "'continue' is redundant since it is the last statement in a loop.", CWE561, Certainty::normal); } static bool isSimpleExpr(const Token* tok, const Variable* var, const Settings& settings) { if (!tok) return false; if (tok->isNumber() || tok->tokType() == Token::eString || tok->tokType() == Token::eChar || tok->isBoolean()) return true; bool needsCheck = tok->varId() > 0; if (!needsCheck) { if (tok->isArithmeticalOp()) return isSimpleExpr(tok->astOperand1(), var, settings) && (!tok->astOperand2() || isSimpleExpr(tok->astOperand2(), var, settings)); const Token* ftok = tok->previous(); if (Token::Match(ftok, "%name% (") && ((ftok->function() && ftok->function()->isConst()) || settings.library.isFunctionConst(ftok->str(), /*pure*/ true))) needsCheck = true; else if (tok->str() == "[") { needsCheck = tok->astOperand1() && tok->astOperand1()->varId() > 0; tok = tok->astOperand1(); } else if (isLeafDot(tok->astOperand2())) { needsCheck = tok->astOperand2()->varId() > 0; tok = tok->astOperand2(); } } return (needsCheck && !findExpressionChanged(tok, tok->astParent(), var->scope()->bodyEnd, settings)); } //--------------------------------------------------------------------------- // Check scope of variables.. //--------------------------------------------------------------------------- void CheckOther::checkVariableScope() { if (mSettings->clang) return; if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("variableScope")) return; const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); // In C it is common practice to declare local variables at the // start of functions. if (mSettings->daca && mTokenizer->isC()) return; logChecker("CheckOther::checkVariableScope"); // style,notclang for (const Variable* var : symbolDatabase->variableList()) { if (!var || !var->isLocal() || var->isConst()) continue; if (var->nameToken()->isExpandedMacro()) continue; const bool isPtrOrRef = var->isPointer() || var->isReference(); const bool isSimpleType = var->typeStartToken()->isStandardType() || var->typeStartToken()->isEnumType() || (var->typeStartToken()->isC() && var->type() && var->type()->isStructType()); if (!isPtrOrRef && !isSimpleType && !astIsContainer(var->nameToken())) continue; if (mTokenizer->hasIfdef(var->nameToken(), var->scope()->bodyEnd)) continue; // reference of range for loop variable.. if (Token::Match(var->nameToken()->previous(), "& %var% = %var% .")) { const Token *otherVarToken = var->nameToken()->tokAt(2); const Variable *otherVar = otherVarToken->variable(); if (otherVar && Token::Match(otherVar->nameToken(), "%var% :") && otherVar->nameToken()->next()->astParent() && Token::simpleMatch(otherVar->nameToken()->next()->astParent()->previous(), "for (")) continue; } bool forHead = false; // Don't check variables declared in header of a for loop for (const Token* tok = var->typeStartToken(); tok; tok = tok->previous()) { if (tok->str() == "(") { forHead = true; break; } if (Token::Match(tok, "[;{}]")) break; } if (forHead) continue; const Token* tok = var->nameToken()->next(); bool isConstructor = false; if (Token::Match(tok, "; %varid% =", var->declarationId())) { // bailout for assignment tok = tok->tokAt(2)->astOperand2(); if (!isSimpleExpr(tok, var, *mSettings)) continue; } else if (Token::Match(tok, "{|(")) { // bailout for constructor isConstructor = true; const Token* argTok = tok->astOperand2(); bool bail = false; while (argTok) { if (Token::simpleMatch(argTok, ",")) { if (!isSimpleExpr(argTok->astOperand2(), var, *mSettings)) { bail = true; break; } } else if (argTok->str() != "." && !isSimpleExpr(argTok, var, *mSettings)) { bail = true; break; } argTok = argTok->astOperand1(); } if (bail) continue; } // bailout if initialized with function call that has possible side effects if (!isConstructor && Token::Match(tok, "[(=]") && Token::simpleMatch(tok->astOperand2(), "(")) continue; bool reduce = true; bool used = false; // Don't warn about unused variables for (; tok && tok != var->scope()->bodyEnd; tok = tok->next()) { if (tok->str() == "{" && tok->scope() != tok->previous()->scope() && !tok->isExpandedMacro() && !isWithinScope(tok, var, Scope::ScopeType::eLambda)) { if (used) { bool used2 = false; if (!checkInnerScope(tok, var, used2) || used2) { reduce = false; break; } } else if (!checkInnerScope(tok, var, used)) { reduce = false; break; } tok = tok->link(); // parse else if blocks.. } else if (Token::simpleMatch(tok, "else { if (") && Token::simpleMatch(tok->linkAt(3), ") {")) { tok = tok->next(); } else if (tok->varId() == var->declarationId() || tok->str() == "goto") { reduce = false; break; } } if (reduce && used) variableScopeError(var->nameToken(), var->name()); } } // used to check if an argument to a function might depend on another argument static bool mayDependOn(const ValueType *other, const ValueType *original) { if (!other || !original) return false; // other must be pointer if (!other->pointer) return false; // must be same underlying type if (other->type != original->type) return false; const int otherPtr = other->pointer + (other->reference == Reference::LValue ? 1 : 0); const int originalPtr = original->pointer; if (otherPtr == originalPtr) { // if other is not const than original may be copied to other return !other->isConst(otherPtr); } // other may be reassigned to original return otherPtr > originalPtr; } bool CheckOther::checkInnerScope(const Token *tok, const Variable* var, bool& used) const { const Scope* scope = tok->next()->scope(); bool loopVariable = scope->isLoopScope(); bool noContinue = true; const Token* forHeadEnd = nullptr; const Token* end = tok->link(); if (scope->type == Scope::eUnconditional && (tok->strAt(-1) == ")" || tok->previous()->isName())) // Might be an unknown macro like BOOST_FOREACH loopVariable = true; if (scope->type == Scope::eDo) { end = end->linkAt(2); } else if (loopVariable && tok->strAt(-1) == ")") { tok = tok->linkAt(-1); // Jump to opening ( of for/while statement } else if (scope->type == Scope::eSwitch) { for (const Scope* innerScope : scope->nestedList) { if (used) { bool used2 = false; if (!checkInnerScope(innerScope->bodyStart, var, used2) || used2) { return false; } } else if (!checkInnerScope(innerScope->bodyStart, var, used)) { return false; } } } bool bFirstAssignment=false; for (; tok && tok != end; tok = tok->next()) { if (tok->str() == "goto") return false; if (tok->str() == "continue") noContinue = false; if (Token::simpleMatch(tok, "for (")) forHeadEnd = tok->linkAt(1); if (tok == forHeadEnd) forHeadEnd = nullptr; if (loopVariable && noContinue && tok->scope() == scope && !forHeadEnd && scope->type != Scope::eSwitch && Token::Match(tok, "%varid% =", var->declarationId())) { // Assigned in outer scope. loopVariable = false; std::pair<const Token*, const Token*> range = tok->next()->findExpressionStartEndTokens(); if (range.first) range.first = range.first->next(); const Token* exprTok = findExpression(var->nameToken()->exprId(), range.first, range.second, [&](const Token* tok2) { return tok2->varId() == var->declarationId(); }); if (exprTok) { tok = exprTok; loopVariable = true; } } if (loopVariable && Token::Match(tok, "%varid% !!=", var->declarationId())) // Variable used in loop return false; if (Token::Match(tok, "& %varid%", var->declarationId())) // Taking address of variable return false; if (Token::Match(tok, "%varid% =", var->declarationId())) { if (!bFirstAssignment && var->isInit() && Token::findmatch(tok->tokAt(2), "%varid%", Token::findsimplematch(tok->tokAt(3), ";"), var->declarationId())) return false; bFirstAssignment = true; } if (!bFirstAssignment && Token::Match(tok, "* %varid%", var->declarationId())) // dereferencing means access to previous content return false; if (Token::Match(tok, "= %varid%", var->declarationId()) && (var->isArray() || var->isPointer() || (var->valueType() && var->valueType()->container))) // Create a copy of array/pointer. Bailout, because the memory it points to might be necessary in outer scope return false; if (tok->varId() == var->declarationId()) { used = true; if (scope == tok->scope()) { if (scope->type == Scope::eSwitch) return false; // Used in outer switch scope - unsafe or impossible to reduce scope if (scope->bodyStart && scope->bodyStart->isSimplifiedScope()) return false; // simplified if/for/switch init statement } if (var->isArrayOrPointer()) { int argn{}; if (const Token* ftok = getTokenArgumentFunction(tok, argn)) { // var passed to function? if (ftok->next()->astParent()) { // return value used? if (ftok->function() && Function::returnsPointer(ftok->function())) return false; const std::string ret = mSettings->library.returnValueType(ftok); // assume that var is returned if (!ret.empty() && ret.back() == '*') return false; } if (ftok->function()) { const std::list<Variable> &argvars = ftok->function()->argumentList; if (const Variable* argvar = ftok->function()->getArgumentVar(argn)) { if (!std::all_of(argvars.cbegin(), argvars.cend(), [&](const Variable& other) { return &other == argvar || !mayDependOn(other.valueType(), argvar->valueType()); })) return false; } } } } const auto yield = astContainerYield(tok); if (yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT) return false; } } return true; } void CheckOther::variableScopeError(const Token *tok, const std::string &varname) { reportError(tok, Severity::style, "variableScope", "$symbol:" + varname + "\n" "The scope of the variable '$symbol' can be reduced.\n" "The scope of the variable '$symbol' can be reduced. Warning: Be careful " "when fixing this message, especially when there are inner loops. Here is an " "example where cppcheck will write that the scope for 'i' can be reduced:\n" "void f(int x)\n" "{\n" " int i = 0;\n" " if (x) {\n" " // it's safe to move 'int i = 0;' here\n" " for (int n = 0; n < 10; ++n) {\n" " // it is possible but not safe to move 'int i = 0;' here\n" " do_something(&i);\n" " }\n" " }\n" "}\n" "When you see this message it is always safe to reduce the variable scope 1 level.", CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // Comma in return statement: return a+1, b++;. (experimental) //--------------------------------------------------------------------------- void CheckOther::checkCommaSeparatedReturn() { // This is experimental for now. See #5076 if ((true) || !mSettings->severity.isEnabled(Severity::style)) // NOLINT(readability-simplify-boolean-expr) return; // logChecker for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() == "return") { tok = tok->next(); while (tok && tok->str() != ";") { if (tok->link() && Token::Match(tok, "[([{<]")) tok = tok->link(); if (!tok->isExpandedMacro() && tok->str() == "," && tok->linenr() != tok->next()->linenr()) commaSeparatedReturnError(tok); tok = tok->next(); } // bailout: missing semicolon (invalid code / bad tokenizer) if (!tok) break; } } } void CheckOther::commaSeparatedReturnError(const Token *tok) { reportError(tok, Severity::style, "commaSeparatedReturn", "Comma is used in return statement. The comma can easily be misread as a ';'.\n" "Comma is used in return statement. When comma is used in a return statement it can " "easily be misread as a semicolon. For example in the code below the value " "of 'b' is returned if the condition is true, but it is easy to think that 'a+1' is " "returned:\n" " if (x)\n" " return a + 1,\n" " b++;\n" "However it can be useful to use comma in macros. Cppcheck does not warn when such a " "macro is then used in a return statement, it is less likely such code is misunderstood.", CWE398, Certainty::normal); } static bool isLargeContainer(const Variable* var, const Settings* settings) { const ValueType* vt = var->valueType(); if (vt->container->size_templateArgNo < 0) return true; const std::size_t maxByValueSize = 2 * settings->platform.sizeof_pointer; if (var->dimensions().empty()) { if (vt->container->startPattern == "std :: bitset <") { if (vt->containerTypeToken->hasKnownIntValue()) return vt->containerTypeToken->getKnownIntValue() / 8 > maxByValueSize; } return false; } const ValueType vtElem = ValueType::parseDecl(vt->containerTypeToken, *settings); const auto elemSize = std::max<std::size_t>(ValueFlow::getSizeOf(vtElem, *settings), 1); const auto arraySize = var->dimension(0) * elemSize; return arraySize > maxByValueSize; } void CheckOther::checkPassByReference() { if (!mSettings->severity.isEnabled(Severity::performance) || mTokenizer->isC()) return; logChecker("CheckOther::checkPassByReference"); // performance,c++ const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Variable* var : symbolDatabase->variableList()) { if (!var || !var->isClass() || var->isPointer() || (var->isArray() && !var->isStlType()) || var->isReference() || var->isEnumType()) continue; const bool isRangeBasedFor = astIsRangeBasedForDecl(var->nameToken()); if (!var->isArgument() && !isRangeBasedFor) continue; if (!isRangeBasedFor && var->scope() && var->scope()->function->arg->link()->strAt(-1) == "...") continue; // references could not be used as va_start parameters (#5824) const Token * const varDeclEndToken = var->declEndToken(); if ((varDeclEndToken && varDeclEndToken->isExternC()) || (var->scope() && var->scope()->function && var->scope()->function->tokenDef && var->scope()->function->tokenDef->isExternC())) continue; // references cannot be used in functions in extern "C" blocks bool inconclusive = false; const bool isContainer = var->valueType() && var->valueType()->type == ValueType::Type::CONTAINER && var->valueType()->container && !var->valueType()->container->view; if (isContainer && !isLargeContainer(var, mSettings)) continue; if (!isContainer) { if (var->type() && !var->type()->isEnumType()) { // Check if type is a struct or class. // Ensure that it is a large object. if (!var->type()->classScope) inconclusive = true; else if (!var->valueType() || ValueFlow::getSizeOf(*var->valueType(), *mSettings) <= 2 * mSettings->platform.sizeof_pointer) continue; } else continue; } if (inconclusive && !mSettings->certainty.isEnabled(Certainty::inconclusive)) continue; const bool isConst = var->isConst(); if (isConst && !var->isArray()) { passedByValueError(var, inconclusive, isRangeBasedFor); continue; } // Check if variable could be const if (!isRangeBasedFor && (!var->scope() || var->scope()->function->isImplicitlyVirtual())) continue; if (!isVariableChanged(var, *mSettings)) { passedByValueError(var, inconclusive, isRangeBasedFor); } } } void CheckOther::passedByValueError(const Variable* var, bool inconclusive, bool isRangeBasedFor) { std::string id = isRangeBasedFor ? "iterateByValue" : "passedByValue"; const std::string action = isRangeBasedFor ? "declared as": "passed by"; const std::string type = isRangeBasedFor ? "Range variable" : "Function parameter"; std::string msg = "$symbol:" + (var ? var->name() : "") + "\n" + type + " '$symbol' should be " + action + " const reference."; ErrorPath errorPath; if (var && var->scope() && var->scope()->function && var->scope()->function->functionPointerUsage) { id += "Callback"; errorPath.emplace_front(var->scope()->function->functionPointerUsage, "Function pointer used here."); msg += " However it seems that '" + var->scope()->function->name() + "' is a callback function."; } if (var) errorPath.emplace_back(var->nameToken(), msg); if (isRangeBasedFor) msg += "\nVariable '$symbol' is used to iterate by value. It could be declared as a const reference which is usually faster and recommended in C++."; else msg += "\nParameter '$symbol' is passed by value. It could be passed as a const reference which is usually faster and recommended in C++."; reportError(errorPath, Severity::performance, id.c_str(), msg, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal); } static bool isVariableMutableInInitializer(const Token* start, const Token * end, nonneg int varid) { if (!start) return false; if (!end) return false; for (const Token *tok = start; tok != end; tok = tok->next()) { if (tok->varId() != varid) continue; if (tok->astParent()) { const Token * memberTok = tok->astParent()->previous(); if (Token::Match(memberTok, "%var% (") && memberTok->variable()) { const Variable * memberVar = memberTok->variable(); if (memberVar->isClass()) //TODO: check if the called constructor could live with a const variable // pending that, assume the worst (that it can't) return true; if (!memberVar->isReference()) continue; if (memberVar->isConst()) continue; } } return true; } return false; } void CheckOther::checkConstVariable() { if ((!mSettings->severity.isEnabled(Severity::style) || mTokenizer->isC()) && !mSettings->isPremiumEnabled("constVariable")) return; logChecker("CheckOther::checkConstVariable"); // style,c++ const SymbolDatabase *const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Variable *var : symbolDatabase->variableList()) { if (!var) continue; if (!var->isReference()) continue; if (var->isRValueReference()) continue; if (var->isPointer()) continue; if (var->isConst()) continue; const Scope* scope = var->scope(); if (!scope) continue; const Function* function = scope->function; if (!function && !scope->isLocal()) continue; if (function && var->isArgument()) { if (function->isImplicitlyVirtual() || function->templateDef) continue; if (function->isConstructor() && isVariableMutableInInitializer(function->constructorMemberInitialization(), scope->bodyStart, var->declarationId())) continue; } if (var->isGlobal()) continue; if (var->isStatic()) continue; if (var->isArray() && !var->isStlType()) continue; if (var->isEnumType()) continue; if (var->isVolatile()) continue; if (var->isMaybeUnused()) continue; if (var->nameToken()->isExpandedMacro()) continue; if (isStructuredBindingVariable(var)) // TODO: check all bound variables continue; if (isVariableChanged(var, *mSettings)) continue; const bool hasFunction = function != nullptr; if (!hasFunction) { const Scope* functionScope = scope; do { functionScope = functionScope->nestedIn; } while (functionScope && !(function = functionScope->function)); } if (function && (Function::returnsReference(function) || Function::returnsPointer(function)) && !Function::returnsConst(function)) { std::vector<const Token*> returns = Function::findReturns(function); if (std::any_of(returns.cbegin(), returns.cend(), [&](const Token* retTok) { if (retTok->varId() == var->declarationId()) return true; while (retTok && retTok->isCast()) retTok = retTok->astOperand2(); while (Token::simpleMatch(retTok, ".")) retTok = retTok->astOperand2(); if (Token::simpleMatch(retTok, "&")) retTok = retTok->astOperand1(); return ValueFlow::hasLifetimeToken(getParentLifetime(retTok), var->nameToken(), *mSettings); })) continue; } // Skip if another non-const variable is initialized with this variable { //Is it the right side of an initialization of a non-const reference bool usedInAssignment = false; for (const Token* tok = var->nameToken(); tok != scope->bodyEnd && tok != nullptr; tok = tok->next()) { if (Token::Match(tok, "& %var% = %varid%", var->declarationId())) { const Variable* refvar = tok->next()->variable(); if (refvar && !refvar->isConst() && refvar->nameToken() == tok->next()) { usedInAssignment = true; break; } } if (tok->isUnaryOp("&") && Token::Match(tok, "& %varid%", var->declarationId())) { const Token* opTok = tok->astParent(); int argn = -1; if (opTok && (opTok->isUnaryOp("!") || opTok->isComparisonOp())) continue; if (opTok && (opTok->isAssignmentOp() || opTok->isCalculation())) { if (opTok->isCalculation()) { if (opTok->astOperand1() != tok) opTok = opTok->astOperand1(); else opTok = opTok->astOperand2(); } if (opTok && opTok->valueType() && var->valueType() && opTok->valueType()->isConst(var->valueType()->pointer)) continue; } else if (const Token* ftok = getTokenArgumentFunction(tok, argn)) { bool inconclusive{}; if (var->valueType() && !isVariableChangedByFunctionCall(ftok, var->valueType()->pointer, var->declarationId(), *mSettings, &inconclusive) && !inconclusive) continue; } usedInAssignment = true; break; } if (astIsRangeBasedForDecl(tok) && Token::Match(tok->astParent()->astOperand2(), "%varid%", var->declarationId())) { const Variable* refvar = tok->astParent()->astOperand1()->variable(); if (refvar && refvar->isReference() && !refvar->isConst()) { usedInAssignment = true; break; } } } if (usedInAssignment) continue; } constVariableError(var, hasFunction ? function : nullptr); } } static const Token* getVariableChangedStart(const Variable* p) { if (p->isArgument()) return p->scope()->bodyStart; const Token* start = p->nameToken()->next(); if (start->isSplittedVarDeclEq()) start = start->tokAt(3); return start; } static bool isConstPointerVariable(const Variable* p, const Settings& settings) { const int indirect = p->isArray() ? p->dimensions().size() : 1; const Token* start = getVariableChangedStart(p); while (const Token* tok = findVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, settings)) { if (p->isReference()) return false; // Assigning a pointer through another pointer may still be const if (!Token::simpleMatch(tok->astParent(), "=")) return false; if (!astIsLHS(tok)) return false; start = tok->next(); } return true; } namespace { struct CompareVariables { bool operator()(const Variable* a, const Variable* b) const { const int fileA = a->nameToken()->fileIndex(); const int fileB = b->nameToken()->fileIndex(); if (fileA != fileB) return fileA < fileB; const int lineA = a->nameToken()->linenr(); const int lineB = b->nameToken()->linenr(); if (lineA != lineB) return lineA < lineB; const int columnA = a->nameToken()->column(); const int columnB = b->nameToken()->column(); return columnA < columnB; } }; } void CheckOther::checkConstPointer() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("constParameter") && !mSettings->isPremiumEnabled("constParameterPointer") && !mSettings->isPremiumEnabled("constParameterReference") && !mSettings->isPremiumEnabled("constVariablePointer")) return; logChecker("CheckOther::checkConstPointer"); // style std::set<const Variable*, CompareVariables> pointers, nonConstPointers; for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { const Variable* const var = tok->variable(); if (!var) continue; if (!var->isLocal() && !var->isArgument()) continue; const Token* const nameTok = var->nameToken(); if (tok == nameTok) { // declarations of (static) pointers are (not) split up, array declarations are never split up if (var->isLocal() && (!var->isStatic() || Token::simpleMatch(nameTok->next(), "[")) && !astIsRangeBasedForDecl(nameTok)) continue; } // Skip function pointers if (Token::Match(nameTok, "%name% ) (")) continue; const ValueType* const vt = tok->valueType(); if (!vt) continue; if ((vt->pointer != 1 && !(vt->pointer == 2 && var->isArray())) || (vt->constness & 1)) continue; if (var->typeStartToken()->isTemplateArg()) continue; if (std::find(nonConstPointers.cbegin(), nonConstPointers.cend(), var) != nonConstPointers.cend()) continue; pointers.emplace(var); const Token* parent = tok->astParent(); enum Deref : std::uint8_t { NONE, DEREF, MEMBER } deref = NONE; bool hasIncDecPlus = false; if (parent && (parent->isUnaryOp("*") || (((hasIncDecPlus = parent->isIncDecOp()) || (hasIncDecPlus = (parent->str() == "+"))) && parent->astParent() && parent->astParent()->isUnaryOp("*")))) deref = DEREF; else if (Token::simpleMatch(parent, "[") && parent->astOperand1() == tok && tok != nameTok) deref = DEREF; else if (Token::Match(parent, "%op%") && Token::simpleMatch(parent->astParent(), ".")) deref = MEMBER; else if (Token::simpleMatch(parent, ".")) deref = MEMBER; else if (astIsRangeBasedForDecl(tok)) continue; if (deref != NONE) { const Token* gparent = parent->astParent(); while (Token::simpleMatch(gparent, "[") && parent != gparent->astOperand2() && parent->str() == gparent->str()) gparent = gparent->astParent(); if (deref == MEMBER) { if (!gparent) continue; if (parent->astOperand2()) { if (parent->astOperand2()->function() && parent->astOperand2()->function()->isConst()) continue; if (mSettings->library.isFunctionConst(parent->astOperand2())) continue; } } if (hasIncDecPlus) { parent = gparent; gparent = gparent ? gparent->astParent() : nullptr; } if (Token::Match(gparent, "%cop%") && !gparent->isUnaryOp("&") && !gparent->isUnaryOp("*")) continue; int argn = -1; if (Token::simpleMatch(gparent, "return")) { const Function* function = gparent->scope()->function; if (function && (!Function::returnsReference(function) || Function::returnsConst(function))) continue; } else if (Token::Match(gparent, "%assign%") && parent == gparent->astOperand2()) { bool takingRef = false, nonConstPtrAssignment = false; const Token *lhs = gparent->astOperand1(); if (lhs && lhs->variable() && lhs->variable()->isReference() && lhs->variable()->nameToken() == lhs && !lhs->variable()->isConst()) takingRef = true; if (lhs && lhs->valueType() && lhs->valueType()->pointer && (lhs->valueType()->constness & 1) == 0 && parent->valueType() && parent->valueType()->pointer) nonConstPtrAssignment = true; if (!takingRef && !nonConstPtrAssignment) continue; } else if (Token::simpleMatch(gparent, "[") && gparent->astOperand2() == parent) continue; else if (gparent && gparent->isCast() && gparent->valueType() && ((gparent->valueType()->pointer == 0 && gparent->valueType()->reference == Reference::None) || (var->valueType() && gparent->valueType()->isConst(var->valueType()->pointer)))) continue; else if (const Token* ftok = getTokenArgumentFunction(parent, argn)) { bool inconclusive{}; if (!isVariableChangedByFunctionCall(ftok->next(), vt->pointer, var->declarationId(), *mSettings, &inconclusive) && !inconclusive) continue; } } else { int argn = -1; if (Token::Match(parent, "%oror%|%comp%|&&|?|!|-|<<")) continue; if (hasIncDecPlus && !parent->astParent()) continue; if (Token::simpleMatch(parent, "(") && Token::Match(parent->astOperand1(), "if|while")) continue; if (Token::simpleMatch(parent, "=") && parent->astOperand1() == tok) continue; if (const Token* ftok = getTokenArgumentFunction(tok, argn)) { if (ftok->function()) { const bool isCastArg = parent->isCast() && !ftok->function()->getOverloadedFunctions().empty(); // assume that cast changes the called function if (!isCastArg) { const Variable* argVar = ftok->function()->getArgumentVar(argn); if (argVar && argVar->valueType() && argVar->valueType()->isConst(vt->pointer)) { bool inconclusive{}; if (!isVariableChangedByFunctionCall(ftok, vt->pointer, var->declarationId(), *mSettings, &inconclusive) && !inconclusive) continue; } } } else { const auto dir = mSettings->library.getArgDirection(ftok, argn + 1); if (dir == Library::ArgumentChecks::Direction::DIR_IN) continue; } } else if (Token::simpleMatch(parent, "(")) { if (parent->isCast() && parent->valueType() && var->valueType() && parent->valueType()->isConst(var->valueType()->pointer)) continue; } } if (tok != nameTok) nonConstPointers.emplace(var); } for (const Variable *p: pointers) { if (p->isArgument()) { if (!p->scope() || !p->scope()->function || p->scope()->function->isImplicitlyVirtual(true) || p->scope()->function->hasVirtualSpecifier()) continue; if (p->isMaybeUnused()) continue; } if (const Function* func = Scope::nestedInFunction(p->scope())) if (func->templateDef) continue; if (std::find(nonConstPointers.cbegin(), nonConstPointers.cend(), p) == nonConstPointers.cend()) { // const Token *start = getVariableChangedStart(p); // const int indirect = p->isArray() ? p->dimensions().size() : 1; // if (isVariableChanged(start, p->scope()->bodyEnd, indirect, p->declarationId(), false, *mSettings)) // continue; if (!isConstPointerVariable(p, *mSettings)) continue; if (p->typeStartToken() && p->typeStartToken()->isSimplifiedTypedef() && !(Token::simpleMatch(p->typeEndToken(), "*") && !p->typeEndToken()->isSimplifiedTypedef())) continue; constVariableError(p, p->isArgument() ? p->scope()->function : nullptr); } } } void CheckOther::constVariableError(const Variable *var, const Function *function) { if (!var) { reportError(nullptr, Severity::style, "constParameter", "Parameter 'x' can be declared with const"); reportError(nullptr, Severity::style, "constVariable", "Variable 'x' can be declared with const"); reportError(nullptr, Severity::style, "constParameterReference", "Parameter 'x' can be declared with const"); reportError(nullptr, Severity::style, "constVariableReference", "Variable 'x' can be declared with const"); reportError(nullptr, Severity::style, "constParameterPointer", "Parameter 'x' can be declared with const"); reportError(nullptr, Severity::style, "constVariablePointer", "Variable 'x' can be declared with const"); reportError(nullptr, Severity::style, "constParameterCallback", "Parameter 'x' can be declared with const, however it seems that 'f' is a callback function."); return; } const std::string vartype(var->isArgument() ? "Parameter" : "Variable"); const std::string& varname(var->name()); const std::string ptrRefArray = var->isArray() ? "const array" : (var->isPointer() ? "pointer to const" : "reference to const"); ErrorPath errorPath; std::string id = "const" + vartype; std::string message = "$symbol:" + varname + "\n" + vartype + " '$symbol' can be declared as " + ptrRefArray; errorPath.emplace_back(var->nameToken(), message); if (var->isArgument() && function && function->functionPointerUsage) { errorPath.emplace_front(function->functionPointerUsage, "You might need to cast the function pointer here"); id += "Callback"; message += ". However it seems that '" + function->name() + "' is a callback function, if '$symbol' is declared with const you might also need to cast function pointer(s)."; } else if (var->isReference()) { id += "Reference"; } else if (var->isPointer() && !var->isArray()) { id += "Pointer"; } reportError(errorPath, Severity::style, id.c_str(), message, CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // Check usage of char variables.. //--------------------------------------------------------------------------- void CheckOther::checkCharVariable() { const bool warning = mSettings->severity.isEnabled(Severity::warning); const bool portability = mSettings->severity.isEnabled(Severity::portability); if (!warning && !portability) return; logChecker("CheckOther::checkCharVariable"); // warning,portability const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "%var% [")) { if (!tok->variable()) continue; if (!tok->variable()->isArray() && !tok->variable()->isPointer()) continue; const Token *index = tok->next()->astOperand2(); if (warning && tok->variable()->isArray() && astIsSignedChar(index) && index->getValueGE(0x80, *mSettings)) signedCharArrayIndexError(tok); if (portability && astIsUnknownSignChar(index) && index->getValueGE(0x80, *mSettings)) unknownSignCharArrayIndexError(tok); } else if (warning && Token::Match(tok, "[&|^]") && tok->isBinaryOp()) { bool warn = false; if (astIsSignedChar(tok->astOperand1())) { const ValueFlow::Value *v1 = tok->astOperand1()->getValueLE(-1, *mSettings); const ValueFlow::Value *v2 = tok->astOperand2()->getMaxValue(false); if (!v1) v1 = tok->astOperand1()->getValueGE(0x80, *mSettings); if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100)) warn = true; } else if (astIsSignedChar(tok->astOperand2())) { const ValueFlow::Value *v1 = tok->astOperand2()->getValueLE(-1, *mSettings); const ValueFlow::Value *v2 = tok->astOperand1()->getMaxValue(false); if (!v1) v1 = tok->astOperand2()->getValueGE(0x80, *mSettings); if (v1 && !(tok->str() == "&" && v2 && v2->isKnown() && v2->intvalue >= 0 && v2->intvalue < 0x100)) warn = true; } // is the result stored in a short|int|long? if (warn && Token::simpleMatch(tok->astParent(), "=")) { const Token *lhs = tok->astParent()->astOperand1(); if (lhs && lhs->valueType() && lhs->valueType()->type >= ValueType::Type::SHORT) charBitOpError(tok); // This is an error.. } } } } } void CheckOther::signedCharArrayIndexError(const Token *tok) { reportError(tok, Severity::warning, "signedCharArrayIndex", "Signed 'char' type used as array index.\n" "Signed 'char' type used as array index. If the value " "can be greater than 127 there will be a buffer underflow " "because of sign extension.", CWE128, Certainty::normal); } void CheckOther::unknownSignCharArrayIndexError(const Token *tok) { reportError(tok, Severity::portability, "unknownSignCharArrayIndex", "'char' type used as array index.\n" "'char' type used as array index. Values greater than 127 will be " "treated depending on whether 'char' is signed or unsigned on target platform.", CWE758, Certainty::normal); } void CheckOther::charBitOpError(const Token *tok) { reportError(tok, Severity::warning, "charBitOp", "When using 'char' variables in bit operations, sign extension can generate unexpected results.\n" "When using 'char' variables in bit operations, sign extension can generate unexpected results. For example:\n" " char c = 0x80;\n" " int i = 0 | c;\n" " if (i & 0x8000)\n" " printf(\"not expected\");\n" "The \"not expected\" will be printed on the screen.", CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // Incomplete statement.. //--------------------------------------------------------------------------- static bool isType(const Token * tok, bool unknown) { if (tok && (tok->isStandardType() || (!tok->isKeyword() && Token::Match(tok, "%type%")) || tok->str() == "auto")) return true; if (tok && tok->varId()) return false; if (Token::simpleMatch(tok, "::")) return isType(tok->astOperand2(), unknown); if (Token::simpleMatch(tok, "<") && tok->link()) return true; if (unknown && Token::Match(tok, "%name% !!(")) return true; return false; } static bool isVarDeclOp(const Token* tok) { if (!tok) return false; const Token * vartok = tok->astOperand2(); if (vartok && vartok->variable() && vartok->variable()->nameToken() == vartok) return true; const Token * typetok = tok->astOperand1(); return isType(typetok, vartok && vartok->varId() != 0); } static bool isBracketAccess(const Token* tok) { if (!Token::simpleMatch(tok, "[") || !tok->astOperand1()) return false; tok = tok->astOperand1(); if (tok->str() == ".") tok = tok->astOperand2(); while (Token::simpleMatch(tok, "[")) tok = tok->astOperand1(); if (!tok || !tok->variable()) return false; return tok->variable()->nameToken() != tok; } static bool isConstant(const Token* tok) { return tok && (tok->isEnumerator() || Token::Match(tok, "%bool%|%num%|%str%|%char%|nullptr|NULL")); } static bool isConstStatement(const Token *tok, bool isNestedBracket = false) { if (!tok) return false; if (tok->isExpandedMacro()) return false; if (tok->varId() != 0) return true; if (isConstant(tok)) return true; if (Token::Match(tok, "*|&|&&") && (Token::Match(tok->previous(), "::|.|const|volatile|restrict") || isVarDeclOp(tok))) return false; if (Token::Match(tok, "<<|>>") && !astIsIntegral(tok, false)) return false; const Token* tok2 = tok; while (tok2) { if (Token::simpleMatch(tok2->astOperand1(), "delete")) return false; tok2 = tok2->astParent(); } if (Token::Match(tok, "&&|%oror%")) return isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2()); if (Token::Match(tok, "!|~|%cop%") && (tok->astOperand1() || tok->astOperand2())) return true; if (Token::simpleMatch(tok->previous(), "sizeof (")) return true; if (isCPPCast(tok)) { if (Token::simpleMatch(tok->astOperand1(), "dynamic_cast") && Token::simpleMatch(tok->astOperand1()->linkAt(1)->previous(), "& >")) return false; return isWithoutSideEffects(tok) && isConstStatement(tok->astOperand2()); } if (tok->isCast() && tok->next() && tok->next()->isStandardType()) return isWithoutSideEffects(tok->astOperand1()) && isConstStatement(tok->astOperand1()); if (Token::simpleMatch(tok, ".")) return isConstStatement(tok->astOperand2()); if (Token::simpleMatch(tok, ",")) { if (tok->astParent()) // warn about const statement on rhs at the top level return isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2()); const Token* lml = previousBeforeAstLeftmostLeaf(tok); // don't warn about matrix/vector assignment (e.g. Eigen) if (lml) lml = lml->next(); const Token* stream = lml; while (stream && Token::Match(stream->astParent(), ".|[|(|*")) stream = stream->astParent(); return (!stream || !isLikelyStream(stream)) && isConstStatement(tok->astOperand2()); } if (Token::simpleMatch(tok, "?") && Token::simpleMatch(tok->astOperand2(), ":")) // ternary operator return isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2()->astOperand1()) && isConstStatement(tok->astOperand2()->astOperand2()); if (isBracketAccess(tok) && isWithoutSideEffects(tok->astOperand1(), /*checkArrayAccess*/ true, /*checkReference*/ false)) { const bool isChained = succeeds(tok->astParent(), tok); if (Token::simpleMatch(tok->astParent(), "[")) { if (isChained) return isConstStatement(tok->astOperand2()) && isConstStatement(tok->astParent()); return isNestedBracket && isConstStatement(tok->astOperand2()); } return isConstStatement(tok->astOperand2(), /*isNestedBracket*/ !isChained); } return false; } static bool isVoidStmt(const Token *tok) { if (Token::simpleMatch(tok, "( void")) return true; if (isCPPCast(tok) && tok->astOperand1() && Token::Match(tok->astOperand1()->next(), "< void *| >")) return true; const Token *tok2 = tok; while (tok2->astOperand1()) tok2 = tok2->astOperand1(); if (Token::simpleMatch(tok2->previous(), ")") && Token::simpleMatch(tok2->linkAt(-1), "( void")) return true; if (Token::simpleMatch(tok2, "( void")) return true; return Token::Match(tok2->previous(), "delete|throw|return"); } static bool isConstTop(const Token *tok) { if (!tok) return false; if (!tok->astParent()) return true; if (Token::simpleMatch(tok->astParent(), ";") && Token::Match(tok->astTop()->previous(), "for|if (") && Token::simpleMatch(tok->astTop()->astOperand2(), ";")) { if (Token::simpleMatch(tok->astParent()->astParent(), ";")) return tok->astParent()->astOperand2() == tok; return tok->astParent()->astOperand1() == tok; } if (Token::simpleMatch(tok, "[")) { const Token* bracTok = tok; while (Token::simpleMatch(bracTok->astParent(), "[")) bracTok = bracTok->astParent(); if (!bracTok->astParent()) return true; } if (tok->str() == "," && tok->astParent()->isAssignmentOp()) return true; return false; } void CheckOther::checkIncompleteStatement() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckOther::checkIncompleteStatement"); // warning for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { const Scope *scope = tok->scope(); if (scope && !scope->isExecutable()) continue; if (!isConstTop(tok)) continue; if (tok->str() == "," && Token::simpleMatch(tok->astTop()->previous(), "for (")) continue; // Do not warn for statement when both lhs and rhs has side effects: // dostuff() || x=213; if (Token::Match(tok, "%oror%|&&")) { bool warn = false; visitAstNodes(tok, [&warn](const Token *child) { if (Token::Match(child, "%oror%|&&")) return ChildrenToVisit::op1_and_op2; if (child->isAssignmentOp()) return ChildrenToVisit::none; if (child->tokType() == Token::Type::eIncDecOp) return ChildrenToVisit::none; if (Token::Match(child->previous(), "%name% (")) return ChildrenToVisit::none; warn = true; return ChildrenToVisit::done; }); if (!warn) continue; } const Token *rtok = nextAfterAstRightmostLeaf(tok); if (!Token::simpleMatch(tok->astParent(), ";") && !Token::simpleMatch(rtok, ";") && !Token::Match(tok->previous(), ";|}|{ %any% ;") && !(tok->isCpp() && tok->isCast() && !tok->astParent()) && !Token::simpleMatch(tok->tokAt(-2), "for (") && !Token::Match(tok->tokAt(-1), "%var% [") && !(tok->str() == "," && tok->astParent() && tok->astParent()->isAssignmentOp())) continue; // Skip statement expressions if (Token::simpleMatch(rtok, "; } )")) continue; if (!isConstStatement(tok)) continue; if (isVoidStmt(tok)) continue; if (tok->isCpp() && tok->str() == "&" && !(tok->astOperand1() && tok->astOperand1()->valueType() && tok->astOperand1()->valueType()->isIntegral())) // Possible archive continue; const bool inconclusive = tok->isConstOp(); if (mSettings->certainty.isEnabled(Certainty::inconclusive) || !inconclusive) constStatementError(tok, tok->isNumber() ? "numeric" : "string", inconclusive); } } void CheckOther::constStatementError(const Token *tok, const std::string &type, bool inconclusive) { const Token *valueTok = tok; while (valueTok && valueTok->isCast()) valueTok = valueTok->astOperand2() ? valueTok->astOperand2() : valueTok->astOperand1(); std::string msg; if (Token::simpleMatch(tok, "==")) msg = "Found suspicious equality comparison. Did you intend to assign a value instead?"; else if (Token::Match(tok, ",|!|~|%cop%")) msg = "Found suspicious operator '" + tok->str() + "', result is not used."; else if (Token::Match(tok, "%var%")) msg = "Unused variable value '" + tok->str() + "'"; else if (isConstant(valueTok)) { std::string typeStr("string"); if (valueTok->isNumber()) typeStr = "numeric"; else if (valueTok->isBoolean()) typeStr = "bool"; else if (valueTok->tokType() == Token::eChar) typeStr = "character"; else if (isNullOperand(valueTok)) typeStr = "NULL"; else if (valueTok->isEnumerator()) typeStr = "enumerator"; msg = "Redundant code: Found a statement that begins with " + typeStr + " constant."; } else if (!tok) msg = "Redundant code: Found a statement that begins with " + type + " constant."; else if (tok->isCast() && tok->tokType() == Token::Type::eExtendedOp) { msg = "Redundant code: Found unused cast "; msg += valueTok ? "of expression '" + valueTok->expressionString() + "'." : "expression."; } else if (tok->str() == "?" && tok->tokType() == Token::Type::eExtendedOp) msg = "Redundant code: Found unused result of ternary operator."; else if (tok->str() == "." && tok->tokType() == Token::Type::eOther) msg = "Redundant code: Found unused member access."; else if (tok->str() == "[" && tok->tokType() == Token::Type::eExtendedOp) msg = "Redundant code: Found unused array access."; else if (mSettings->debugwarnings) { reportError(tok, Severity::debug, "debug", "constStatementError not handled."); return; } reportError(tok, Severity::warning, "constStatement", msg, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal); } //--------------------------------------------------------------------------- // Detect division by zero. //--------------------------------------------------------------------------- void CheckOther::checkZeroDivision() { logChecker("CheckOther::checkZeroDivision"); for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (!tok->astOperand2() || !tok->astOperand1()) continue; if (tok->str() != "%" && tok->str() != "/" && tok->str() != "%=" && tok->str() != "/=") continue; if (!tok->valueType() || !tok->valueType()->isIntegral()) continue; if (tok->scope() && tok->scope()->type == Scope::eEnum) // don't warn for compile-time error continue; // Value flow.. const ValueFlow::Value *value = tok->astOperand2()->getValue(0LL); if (value && mSettings->isEnabled(value, false)) zerodivError(tok, value); } } void CheckOther::zerodivError(const Token *tok, const ValueFlow::Value *value) { if (!tok && !value) { reportError(tok, Severity::error, "zerodiv", "Division by zero.", CWE369, Certainty::normal); reportError(tok, Severity::warning, "zerodivcond", ValueFlow::eitherTheConditionIsRedundant(nullptr) + " or there is division by zero.", CWE369, Certainty::normal); return; } const ErrorPath errorPath = getErrorPath(tok, value, "Division by zero"); std::ostringstream errmsg; if (value->condition) { const int line = tok ? tok->linenr() : 0; errmsg << ValueFlow::eitherTheConditionIsRedundant(value->condition) << " or there is division by zero at line " << line << "."; } else errmsg << "Division by zero."; reportError(errorPath, value->errorSeverity() ? Severity::error : Severity::warning, value->condition ? "zerodivcond" : "zerodiv", errmsg.str(), CWE369, value->isInconclusive() ? Certainty::inconclusive : Certainty::normal); } //--------------------------------------------------------------------------- // Check for NaN (not-a-number) in an arithmetic expression, e.g. // double d = 1.0 / 0.0 + 100.0; //--------------------------------------------------------------------------- void CheckOther::checkNanInArithmeticExpression() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("nanInArithmeticExpression")) return; logChecker("CheckOther::checkNanInArithmeticExpression"); // style for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() != "/") continue; if (!Token::Match(tok->astParent(), "[+-]")) continue; if (Token::simpleMatch(tok->astOperand2(), "0.0")) nanInArithmeticExpressionError(tok); } } void CheckOther::nanInArithmeticExpressionError(const Token *tok) { reportError(tok, Severity::style, "nanInArithmeticExpression", "Using NaN/Inf in a computation.\n" "Using NaN/Inf in a computation. " "Although nothing bad really happens, it is suspicious.", CWE369, Certainty::normal); } //--------------------------------------------------------------------------- // Creating instance of classes which are destroyed immediately //--------------------------------------------------------------------------- void CheckOther::checkMisusedScopedObject() { // Skip this check for .c files if (mTokenizer->isC()) return; if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedScopedObject")) return; logChecker("CheckOther::checkMisusedScopedObject"); // style,c++ auto getConstructorTok = [](const Token* tok, std::string& typeStr) -> const Token* { if (!Token::Match(tok, "[;{}] %name%") || tok->next()->isKeyword()) return nullptr; tok = tok->next(); typeStr.clear(); while (Token::Match(tok, "%name% ::")) { typeStr += tok->str(); typeStr += "::"; tok = tok->tokAt(2); } typeStr += tok->str(); const Token* endTok = tok; if (Token::Match(endTok, "%name% <")) endTok = endTok->linkAt(1); if (Token::Match(endTok, "%name%|> (|{") && Token::Match(endTok->linkAt(1), ")|} ;") && !Token::simpleMatch(endTok->next()->astParent(), ";")) { // for loop condition return tok; } return nullptr; }; auto isLibraryConstructor = [&](const Token* tok, const std::string& typeStr) -> bool { const Library::TypeCheck typeCheck = mSettings->library.getTypeCheck("unusedvar", typeStr); if (typeCheck == Library::TypeCheck::check || typeCheck == Library::TypeCheck::checkFiniteLifetime) return true; return mSettings->library.detectContainerOrIterator(tok); }; const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); std::string typeStr; for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { const Token* ctorTok = getConstructorTok(tok, typeStr); if (ctorTok && (((ctorTok->type() || ctorTok->isStandardType() || (ctorTok->function() && ctorTok->function()->isConstructor())) // TODO: The rhs of || should be removed; It is a workaround for a symboldatabase bug && (!ctorTok->function() || ctorTok->function()->isConstructor()) // // is not a function on this scope or is function in this scope and it's a ctor && ctorTok->str() != "void") || isLibraryConstructor(tok->next(), typeStr))) { const Token* parTok = ctorTok->next(); if (Token::simpleMatch(parTok, "<") && parTok->link()) parTok = parTok->link()->next(); if (const Token* arg = parTok->astOperand2()) { if (!isConstStatement(arg)) continue; if (parTok->str() == "(") { if (arg->varId() && !(arg->variable() && arg->variable()->nameToken() != arg)) continue; const Token* rml = nextAfterAstRightmostLeaf(arg); if (rml && rml->previous() && rml->previous()->varId()) continue; } } tok = tok->next(); misusedScopeObjectError(ctorTok, typeStr); tok = tok->next(); } if (tok->isAssignmentOp() && Token::simpleMatch(tok->astOperand1(), "(") && tok->astOperand1()->astOperand1()) { if (const Function* ftok = tok->astOperand1()->astOperand1()->function()) { if (ftok->retType && Token::Match(ftok->retType->classDef, "class|struct|union") && !Function::returnsReference(ftok, /*unknown*/ false, /*includeRValueRef*/ true)) misusedScopeObjectError(tok->next(), ftok->retType->name(), /*isAssignment*/ true); } } } } } void CheckOther::misusedScopeObjectError(const Token *tok, const std::string& varname, bool isAssignment) { std::string msg = "Instance of '$symbol' object is destroyed immediately"; msg += isAssignment ? ", assignment has no effect." : "."; reportError(tok, Severity::style, "unusedScopedObject", "$symbol:" + varname + "\n" + msg, CWE563, Certainty::normal); } static const Token * getSingleExpressionInBlock(const Token * tok) { if (!tok) return nullptr; const Token * top = tok->astTop(); const Token * nextExpression = nextAfterAstRightmostLeaf(top); if (!Token::simpleMatch(nextExpression, "; }")) return nullptr; return top; } //----------------------------------------------------------------------------- // check for duplicate code in if and else branches // if (a) { b = true; } else { b = true; } //----------------------------------------------------------------------------- void CheckOther::checkDuplicateBranch() { // This is inconclusive since in practice most warnings are noise: // * There can be unfixed low-priority todos. The code is fine as it // is but it could be possible to enhance it. Writing a warning // here is noise since the code is fine (see cppcheck, abiword, ..) // * There can be overspecified code so some conditions can't be true // and their conditional code is a duplicate of the condition that // is always true just in case it would be false. See for instance // abiword. if (!mSettings->severity.isEnabled(Severity::style) || !mSettings->certainty.isEnabled(Certainty::inconclusive)) return; logChecker("CheckOther::checkDuplicateBranch"); // style,inconclusive const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope & scope : symbolDatabase->scopeList) { if (scope.type != Scope::eIf) continue; // check all the code in the function for if (..) else if (Token::simpleMatch(scope.bodyEnd, "} else {")) { // Make sure there are no macros (different macros might be expanded // to the same code) bool macro = false; for (const Token *tok = scope.bodyStart; tok != scope.bodyEnd->linkAt(2); tok = tok->next()) { if (tok->isExpandedMacro()) { macro = true; break; } } if (macro) continue; const Token * const tokIf = scope.bodyStart->next(); const Token * const tokElse = scope.bodyEnd->tokAt(3); // compare first tok before stringifying the whole blocks const std::string tokIfStr = tokIf->stringify(false, true, false); if (tokIfStr.empty()) continue; const std::string tokElseStr = tokElse->stringify(false, true, false); if (tokIfStr == tokElseStr) { // save if branch code const std::string branch1 = tokIf->stringifyList(scope.bodyEnd); if (branch1.empty()) continue; // save else branch code const std::string branch2 = tokElse->stringifyList(scope.bodyEnd->linkAt(2)); // check for duplicates if (branch1 == branch2) { duplicateBranchError(scope.classDef, scope.bodyEnd->next(), ErrorPath{}); continue; } } // check for duplicates using isSameExpression const Token * branchTop1 = getSingleExpressionInBlock(tokIf); if (!branchTop1) continue; const Token * branchTop2 = getSingleExpressionInBlock(tokElse); if (!branchTop2) continue; if (branchTop1->str() != branchTop2->str()) continue; ErrorPath errorPath; if (isSameExpression(false, branchTop1->astOperand1(), branchTop2->astOperand1(), *mSettings, true, true, &errorPath) && isSameExpression(false, branchTop1->astOperand2(), branchTop2->astOperand2(), *mSettings, true, true, &errorPath)) duplicateBranchError(scope.classDef, scope.bodyEnd->next(), std::move(errorPath)); } } } void CheckOther::duplicateBranchError(const Token *tok1, const Token *tok2, ErrorPath errors) { errors.emplace_back(tok2, ""); errors.emplace_back(tok1, ""); reportError(errors, Severity::style, "duplicateBranch", "Found duplicate branches for 'if' and 'else'.\n" "Finding the same code in an 'if' and related 'else' branch is suspicious and " "might indicate a cut and paste or logic error. Please examine this code " "carefully to determine if it is correct.", CWE398, Certainty::inconclusive); } //----------------------------------------------------------------------------- // Check for a free() of an invalid address // char* p = malloc(100); // free(p + 10); //----------------------------------------------------------------------------- void CheckOther::checkInvalidFree() { std::map<int, bool> inconclusive; std::map<int, std::string> allocation; logChecker("CheckOther::checkInvalidFree"); const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) { // Keep track of which variables were assigned addresses to newly-allocated memory if ((tok->isCpp() && Token::Match(tok, "%var% = new")) || (Token::Match(tok, "%var% = %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2)))) { allocation.insert(std::make_pair(tok->varId(), tok->strAt(2))); inconclusive.insert(std::make_pair(tok->varId(), false)); } // If a previously-allocated pointer is incremented or decremented, any subsequent // free involving pointer arithmetic may or may not be invalid, so we should only // report an inconclusive result. else if (Token::Match(tok, "%var% = %name% +|-") && tok->varId() == tok->tokAt(2)->varId() && allocation.find(tok->varId()) != allocation.end()) { if (printInconclusive) inconclusive[tok->varId()] = true; else { allocation.erase(tok->varId()); inconclusive.erase(tok->varId()); } } // If a previously-allocated pointer is assigned a completely new value, // we can't know if any subsequent free() on that pointer is valid or not. else if (Token::Match(tok, "%var% =")) { allocation.erase(tok->varId()); inconclusive.erase(tok->varId()); } // If a variable that was previously assigned a newly-allocated memory location is // added or subtracted from when used to free the memory, report an error. else if ((Token::Match(tok, "%name% ( %any% +|-") && mSettings->library.getDeallocFuncInfo(tok)) || Token::Match(tok, "delete [ ] ( %any% +|-") || Token::Match(tok, "delete %any% +|- %any%")) { const int varIndex = tok->strAt(1) == "(" ? 2 : tok->strAt(3) == "(" ? 4 : 1; const int var1 = tok->tokAt(varIndex)->varId(); const int var2 = tok->tokAt(varIndex + 2)->varId(); const std::map<int, bool>::const_iterator alloc1 = inconclusive.find(var1); const std::map<int, bool>::const_iterator alloc2 = inconclusive.find(var2); if (alloc1 != inconclusive.end()) { invalidFreeError(tok, allocation[var1], alloc1->second); } else if (alloc2 != inconclusive.end()) { invalidFreeError(tok, allocation[var2], alloc2->second); } } // If the previously-allocated variable is passed in to another function // as a parameter, it might be modified, so we shouldn't report an error // if it is later used to free memory else if (Token::Match(tok, "%name% (") && !mSettings->library.isFunctionConst(tok->str(), true)) { const Token* tok2 = Token::findmatch(tok->next(), "%var%", tok->linkAt(1)); while (tok2 != nullptr) { allocation.erase(tok->varId()); inconclusive.erase(tok2->varId()); tok2 = Token::findmatch(tok2->next(), "%var%", tok->linkAt(1)); } } } } } void CheckOther::invalidFreeError(const Token *tok, const std::string &allocation, bool inconclusive) { std::string alloc = allocation; if (alloc != "new") alloc += "()"; std::string deallocated = (alloc == "new") ? "deleted" : "freed"; reportError(tok, Severity::error, "invalidFree", "Mismatching address is " + deallocated + ". The address you get from " + alloc + " must be " + deallocated + " without offset.", CWE(0U), inconclusive ? Certainty::inconclusive : Certainty::normal); } //--------------------------------------------------------------------------- // check for the same expression on both sides of an operator // (x == x), (x && x), (x || x) // (x.y == x.y), (x.y && x.y), (x.y || x.y) //--------------------------------------------------------------------------- namespace { bool notconst(const Function* func) { return !func->isConst(); } void getConstFunctions(const SymbolDatabase *symbolDatabase, std::list<const Function*> &constFunctions) { for (const Scope &scope : symbolDatabase->scopeList) { // only add const functions that do not have a non-const overloaded version // since it is pretty much impossible to tell which is being called. using StringFunctionMap = std::map<std::string, std::list<const Function*>>; StringFunctionMap functionsByName; for (const Function &func : scope.functionList) { functionsByName[func.tokenDef->str()].push_back(&func); } for (std::pair<const std::string, std::list<const Function*>>& it : functionsByName) { const std::list<const Function*>::const_iterator nc = std::find_if(it.second.cbegin(), it.second.cend(), notconst); if (nc == it.second.cend()) { // ok to add all of them constFunctions.splice(constFunctions.end(), it.second); } } } } } void CheckOther::checkDuplicateExpression() { { const bool styleEnabled = mSettings->severity.isEnabled(Severity::style); const bool premiumEnabled = mSettings->isPremiumEnabled("oppositeExpression") || mSettings->isPremiumEnabled("duplicateExpression") || mSettings->isPremiumEnabled("duplicateAssignExpression") || mSettings->isPremiumEnabled("duplicateExpressionTernary") || mSettings->isPremiumEnabled("duplicateValueTernary") || mSettings->isPremiumEnabled("selfAssignment") || mSettings->isPremiumEnabled("knownConditionTrueFalse"); if (!styleEnabled && !premiumEnabled) return; } logChecker("CheckOther::checkDuplicateExpression"); // style,warning // Parse all executing scopes.. const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); std::list<const Function*> constFunctions; getConstFunctions(symbolDatabase, constFunctions); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() == "=" && Token::Match(tok->astOperand1(), "%var%")) { const Token * endStatement = Token::findsimplematch(tok, ";"); if (Token::Match(endStatement, "; %type% %var% ;")) { endStatement = endStatement->tokAt(4); } if (Token::Match(endStatement, "%var% %assign%")) { const Token * nextAssign = endStatement->tokAt(1); const Token * var1 = tok->astOperand1(); const Token * var2 = nextAssign->astOperand1(); if (var1 && var2 && Token::Match(var1->previous(), ";|{|} %var%") && Token::Match(var2->previous(), ";|{|} %var%") && var2->valueType() && var1->valueType() && var2->valueType()->originalTypeName == var1->valueType()->originalTypeName && var2->valueType()->pointer == var1->valueType()->pointer && var2->valueType()->constness == var1->valueType()->constness && var2->varId() != var1->varId() && ( tok->astOperand2()->isArithmeticalOp() || tok->astOperand2()->str() == "." || Token::Match(tok->astOperand2()->previous(), "%name% (") ) && tok->next()->tokType() != Token::eType && isSameExpression(true, tok->next(), nextAssign->next(), *mSettings, true, false) && isSameExpression(true, tok->astOperand2(), nextAssign->astOperand2(), *mSettings, true, false) && tok->astOperand2()->expressionString() == nextAssign->astOperand2()->expressionString()) { bool differentDomain = false; const Scope * varScope = var1->scope() ? var1->scope() : scope; const Token* assignTok = Token::findsimplematch(var2, ";"); for (; assignTok && assignTok != varScope->bodyEnd; assignTok = assignTok->next()) { if (!Token::Match(assignTok, "%assign%|%comp%")) continue; if (!assignTok->astOperand1()) continue; if (!assignTok->astOperand2()) continue; if (assignTok->astOperand1()->varId() != var1->varId() && assignTok->astOperand1()->varId() != var2->varId() && !isSameExpression(true, tok->astOperand2(), assignTok->astOperand1(), *mSettings, true, true)) continue; if (assignTok->astOperand2()->varId() != var1->varId() && assignTok->astOperand2()->varId() != var2->varId() && !isSameExpression(true, tok->astOperand2(), assignTok->astOperand2(), *mSettings, true, true)) continue; differentDomain = true; break; } if (!differentDomain && !isUniqueExpression(tok->astOperand2())) duplicateAssignExpressionError(var1, var2, false); else if (mSettings->certainty.isEnabled(Certainty::inconclusive)) { diag(assignTok); duplicateAssignExpressionError(var1, var2, true); } } } } auto isInsideLambdaCaptureList = [](const Token* tok) { const Token* parent = tok->astParent(); while (Token::simpleMatch(parent, ",")) parent = parent->astParent(); return isLambdaCaptureList(parent); }; ErrorPath errorPath; if (tok->isOp() && tok->astOperand1() && !Token::Match(tok, "+|*|<<|>>|+=|*=|<<=|>>=") && !isInsideLambdaCaptureList(tok)) { if (Token::Match(tok, "==|!=|-") && astIsFloat(tok->astOperand1(), true)) continue; const bool pointerDereference = (tok->astOperand1() && tok->astOperand1()->isUnaryOp("*")) || (tok->astOperand2() && tok->astOperand2()->isUnaryOp("*")); const bool followVar = (!isConstVarExpression(tok) || Token::Match(tok, "%comp%|%oror%|&&")) && !pointerDereference; if (isSameExpression(true, tok->astOperand1(), tok->astOperand2(), *mSettings, true, followVar, &errorPath)) { if (isWithoutSideEffects(tok->astOperand1())) { const Token* loopTok = isInLoopCondition(tok); if (!loopTok || !findExpressionChanged(tok, tok, loopTok->link()->linkAt(1), *mSettings)) { const bool isEnum = tok->scope()->type == Scope::eEnum; const bool assignment = !isEnum && tok->str() == "="; if (assignment) selfAssignmentError(tok, tok->astOperand1()->expressionString()); else if (!isEnum) { if (tok->isCpp() && mSettings->standards.cpp >= Standards::CPP11 && tok->str() == "==") { const Token* parent = tok->astParent(); while (parent && parent->astParent()) { parent = parent->astParent(); } if (parent && parent->previous() && parent->strAt(-1) == "static_assert") { continue; } } duplicateExpressionError(tok->astOperand1(), tok->astOperand2(), tok, std::move(errorPath)); } } } } else if (tok->str() == "=" && Token::simpleMatch(tok->astOperand2(), "=") && isSameExpression(false, tok->astOperand1(), tok->astOperand2()->astOperand1(), *mSettings, true, false)) { if (isWithoutSideEffects(tok->astOperand1())) { selfAssignmentError(tok, tok->astOperand1()->expressionString()); } } else if (isOppositeExpression(tok->astOperand1(), tok->astOperand2(), *mSettings, false, true, &errorPath) && !Token::Match(tok, "=|-|-=|/|/=") && isWithoutSideEffects(tok->astOperand1())) { oppositeExpressionError(tok, std::move(errorPath)); } else if (!Token::Match(tok, "[-/%]")) { // These operators are not associative if (tok->astOperand2() && tok->str() == tok->astOperand1()->str() && isSameExpression(true, tok->astOperand2(), tok->astOperand1()->astOperand2(), *mSettings, true, followVar, &errorPath) && isWithoutSideEffects(tok->astOperand2())) duplicateExpressionError(tok->astOperand2(), tok->astOperand1()->astOperand2(), tok, std::move(errorPath)); else if (tok->astOperand2() && isConstExpression(tok->astOperand1(), mSettings->library)) { auto checkDuplicate = [&](const Token* exp1, const Token* exp2, const Token* ast1) { if (isSameExpression(true, exp1, exp2, *mSettings, true, true, &errorPath) && isWithoutSideEffects(exp1) && isWithoutSideEffects(ast1->astOperand2())) duplicateExpressionError(exp1, exp2, tok, errorPath, /*hasMultipleExpr*/ true); }; const Token *ast1 = tok->astOperand1(); while (ast1 && tok->str() == ast1->str()) { // chain of identical operators checkDuplicate(ast1->astOperand2(), tok->astOperand2(), ast1); if (ast1->astOperand1() && ast1->astOperand1()->str() != tok->str()) // check first condition in the chain checkDuplicate(ast1->astOperand1(), tok->astOperand2(), ast1); ast1 = ast1->astOperand1(); } } } } else if (tok->astOperand1() && tok->astOperand2() && tok->str() == ":" && tok->astParent() && tok->astParent()->str() == "?") { if (!tok->astOperand1()->values().empty() && !tok->astOperand2()->values().empty() && isEqualKnownValue(tok->astOperand1(), tok->astOperand2()) && !isVariableChanged(tok->astParent(), /*indirect*/ 0, *mSettings) && isConstStatement(tok->astOperand1()) && isConstStatement(tok->astOperand2())) duplicateValueTernaryError(tok); else if (isSameExpression(true, tok->astOperand1(), tok->astOperand2(), *mSettings, false, true, &errorPath)) duplicateExpressionTernaryError(tok, std::move(errorPath)); } } } } void CheckOther::oppositeExpressionError(const Token *opTok, ErrorPath errors) { errors.emplace_back(opTok, ""); const std::string& op = opTok ? opTok->str() : "&&"; reportError(errors, Severity::style, "oppositeExpression", "Opposite expression on both sides of \'" + op + "\'.\n" "Finding the opposite expression on both sides of an operator is suspicious and might " "indicate a cut and paste or logic error. Please examine this code carefully to " "determine if it is correct.", CWE398, Certainty::normal); } void CheckOther::duplicateExpressionError(const Token *tok1, const Token *tok2, const Token *opTok, ErrorPath errors, bool hasMultipleExpr) { errors.emplace_back(opTok, ""); const std::string& expr1 = tok1 ? tok1->expressionString() : "x"; const std::string& expr2 = tok2 ? tok2->expressionString() : "x"; const std::string& op = opTok ? opTok->str() : "&&"; std::string msg = "Same expression " + (hasMultipleExpr ? "\'" + expr1 + "\'" + " found multiple times in chain of \'" + op + "\' operators" : "on both sides of \'" + op + "\'"); const char *id = "duplicateExpression"; if (expr1 != expr2 && (!opTok || Token::Match(opTok, "%oror%|%comp%|&&|?|!"))) { id = "knownConditionTrueFalse"; std::string exprMsg = "The comparison \'" + expr1 + " " + op + " " + expr2 + "\' is always "; if (Token::Match(opTok, "==|>=|<=")) msg = exprMsg + "true"; else if (Token::Match(opTok, "!=|>|<")) msg = exprMsg + "false"; } if (expr1 != expr2 && !Token::Match(tok1, "%num%|NULL|nullptr") && !Token::Match(tok2, "%num%|NULL|nullptr")) msg += " because '" + expr1 + "' and '" + expr2 + "' represent the same value"; reportError(errors, Severity::style, id, msg + (std::string(".\nFinding the same expression ") + (hasMultipleExpr ? "more than once in a condition" : "on both sides of an operator")) + " is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to " "determine if it is correct.", CWE398, Certainty::normal); } void CheckOther::duplicateAssignExpressionError(const Token *tok1, const Token *tok2, bool inconclusive) { const std::list<const Token *> toks = { tok2, tok1 }; const std::string& var1 = tok1 ? tok1->str() : "x"; const std::string& var2 = tok2 ? tok2->str() : "x"; reportError(toks, Severity::style, "duplicateAssignExpression", "Same expression used in consecutive assignments of '" + var1 + "' and '" + var2 + "'.\n" "Finding variables '" + var1 + "' and '" + var2 + "' that are assigned the same expression " "is suspicious and might indicate a cut and paste or logic error. Please examine this code carefully to " "determine if it is correct.", CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckOther::duplicateExpressionTernaryError(const Token *tok, ErrorPath errors) { errors.emplace_back(tok, ""); reportError(errors, Severity::style, "duplicateExpressionTernary", "Same expression in both branches of ternary operator.\n" "Finding the same expression in both branches of ternary operator is suspicious as " "the same code is executed regardless of the condition.", CWE398, Certainty::normal); } void CheckOther::duplicateValueTernaryError(const Token *tok) { reportError(tok, Severity::style, "duplicateValueTernary", "Same value in both branches of ternary operator.\n" "Finding the same value in both branches of ternary operator is suspicious as " "the same code is executed regardless of the condition.", CWE398, Certainty::normal); } void CheckOther::selfAssignmentError(const Token *tok, const std::string &varname) { reportError(tok, Severity::style, "selfAssignment", "$symbol:" + varname + "\n" "Redundant assignment of '$symbol' to itself.", CWE398, Certainty::normal); } //----------------------------------------------------------------------------- // Check is a comparison of two variables leads to condition, which is // always true or false. // For instance: int a = 1; if(isless(a,a)){...} // In this case isless(a,a) always evaluates to false. // // Reference: // - http://www.cplusplus.com/reference/cmath/ //----------------------------------------------------------------------------- void CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (tok->isName() && Token::Match(tok, "isgreater|isless|islessgreater|isgreaterequal|islessequal ( %var% , %var% )")) { const int varidLeft = tok->tokAt(2)->varId();// get the left varid const int varidRight = tok->tokAt(4)->varId();// get the right varid // compare varids: if they are not zero but equal // --> the comparison function is called with the same variables if (varidLeft == varidRight) { const std::string& functionName = tok->str(); // store function name const std::string& varNameLeft = tok->strAt(2); // get the left variable name if (functionName == "isgreater" || functionName == "isless" || functionName == "islessgreater") { // e.g.: isgreater(x,x) --> (x)>(x) --> false checkComparisonFunctionIsAlwaysTrueOrFalseError(tok, functionName, varNameLeft, false); } else { // functionName == "isgreaterequal" || functionName == "islessequal" // e.g.: isgreaterequal(x,x) --> (x)>=(x) --> true checkComparisonFunctionIsAlwaysTrueOrFalseError(tok, functionName, varNameLeft, true); } } } } } } void CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalseError(const Token* tok, const std::string &functionName, const std::string &varName, const bool result) { const std::string strResult = bool_to_string(result); const CWE cweResult = result ? CWE571 : CWE570; reportError(tok, Severity::warning, "comparisonFunctionIsAlwaysTrueOrFalse", "$symbol:" + functionName + "\n" "Comparison of two identical variables with $symbol(" + varName + "," + varName + ") always evaluates to " + strResult + ".\n" "The function $symbol is designed to compare two variables. Calling this function with one variable (" + varName + ") " "for both parameters leads to a statement which is always " + strResult + ".", cweResult, Certainty::normal); } //--------------------------------------------------------------------------- // Check testing sign of unsigned variables and pointers. //--------------------------------------------------------------------------- void CheckOther::checkSignOfUnsignedVariable() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unsignedLessThanZero")) return; logChecker("CheckOther::checkSignOfUnsignedVariable"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { // check all the code in the function for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { const ValueFlow::Value *zeroValue = nullptr; const Token *nonZeroExpr = nullptr; if (comparisonNonZeroExpressionLessThanZero(tok, zeroValue, nonZeroExpr)) { const ValueType* vt = nonZeroExpr->valueType(); if (vt->pointer) pointerLessThanZeroError(tok, zeroValue); else unsignedLessThanZeroError(tok, zeroValue, nonZeroExpr->expressionString()); } else if (testIfNonZeroExpressionIsPositive(tok, zeroValue, nonZeroExpr)) { const ValueType* vt = nonZeroExpr->valueType(); if (vt->pointer) pointerPositiveError(tok, zeroValue); else unsignedPositiveError(tok, zeroValue, nonZeroExpr->expressionString()); } } } } bool CheckOther::comparisonNonZeroExpressionLessThanZero(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr, bool suppress) { if (!tok->isComparisonOp() || !tok->astOperand1() || !tok->astOperand2()) return false; const ValueFlow::Value *v1 = tok->astOperand1()->getValue(0); const ValueFlow::Value *v2 = tok->astOperand2()->getValue(0); if (Token::Match(tok, "<|<=") && v2 && v2->isKnown()) { zeroValue = v2; nonZeroExpr = tok->astOperand1(); } else if (Token::Match(tok, ">|>=") && v1 && v1->isKnown()) { zeroValue = v1; nonZeroExpr = tok->astOperand2(); } else { return false; } if (const Variable* var = nonZeroExpr->variable()) if (var->typeStartToken()->isTemplateArg()) return suppress; const ValueType* vt = nonZeroExpr->valueType(); return vt && (vt->pointer || vt->sign == ValueType::UNSIGNED); } bool CheckOther::testIfNonZeroExpressionIsPositive(const Token *tok, const ValueFlow::Value *&zeroValue, const Token *&nonZeroExpr) { if (!tok->isComparisonOp() || !tok->astOperand1() || !tok->astOperand2()) return false; const ValueFlow::Value *v1 = tok->astOperand1()->getValue(0); const ValueFlow::Value *v2 = tok->astOperand2()->getValue(0); if (Token::simpleMatch(tok, ">=") && v2 && v2->isKnown()) { zeroValue = v2; nonZeroExpr = tok->astOperand1(); } else if (Token::simpleMatch(tok, "<=") && v1 && v1->isKnown()) { zeroValue = v1; nonZeroExpr = tok->astOperand2(); } else { return false; } const ValueType* vt = nonZeroExpr->valueType(); return vt && (vt->pointer || vt->sign == ValueType::UNSIGNED); } void CheckOther::unsignedLessThanZeroError(const Token *tok, const ValueFlow::Value * v, const std::string &varname) { reportError(getErrorPath(tok, v, "Unsigned less than zero"), Severity::style, "unsignedLessThanZero", "$symbol:" + varname + "\n" "Checking if unsigned expression '$symbol' is less than zero.\n" "The unsigned expression '$symbol' will never be negative so it " "is either pointless or an error to check if it is.", CWE570, Certainty::normal); } void CheckOther::pointerLessThanZeroError(const Token *tok, const ValueFlow::Value *v) { reportError(getErrorPath(tok, v, "Pointer less than zero"), Severity::style, "pointerLessThanZero", "A pointer can not be negative so it is either pointless or an error to check if it is.", CWE570, Certainty::normal); } void CheckOther::unsignedPositiveError(const Token *tok, const ValueFlow::Value * v, const std::string &varname) { reportError(getErrorPath(tok, v, "Unsigned positive"), Severity::style, "unsignedPositive", "$symbol:" + varname + "\n" "Unsigned expression '$symbol' can't be negative so it is unnecessary to test it.", CWE570, Certainty::normal); } void CheckOther::pointerPositiveError(const Token *tok, const ValueFlow::Value * v) { reportError(getErrorPath(tok, v, "Pointer positive"), Severity::style, "pointerPositive", "A pointer can not be negative so it is either pointless or an error to check if it is not.", CWE570, Certainty::normal); } /* check if a constructor in given class scope takes a reference */ static bool constructorTakesReference(const Scope * const classScope) { return std::any_of(classScope->functionList.begin(), classScope->functionList.end(), [&](const Function& constructor) { if (constructor.isConstructor()) { for (int argnr = 0U; argnr < constructor.argCount(); argnr++) { const Variable * const argVar = constructor.getArgumentVar(argnr); if (argVar && argVar->isReference()) { return true; } } } return false; }); } //--------------------------------------------------------------------------- // This check rule works for checking the "const A a = getA()" usage when getA() returns "const A &" or "A &". // In most scenarios, "const A & a = getA()" will be more efficient. //--------------------------------------------------------------------------- void CheckOther::checkRedundantCopy() { if (!mSettings->severity.isEnabled(Severity::performance) || mTokenizer->isC() || !mSettings->certainty.isEnabled(Certainty::inconclusive)) return; logChecker("CheckOther::checkRedundantCopy"); // c++,performance,inconclusive const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Variable* var : symbolDatabase->variableList()) { if (!var || var->isReference() || var->isPointer() || (!var->type() && !var->isStlType() && !(var->valueType() && var->valueType()->container)) || // bailout if var is of standard type, if it is a pointer or non-const (!var->isConst() && isVariableChanged(var, *mSettings))) continue; const Token* startTok = var->nameToken(); if (startTok->strAt(1) == "=") // %type% %name% = ... ; ; else if (Token::Match(startTok->next(), "(|{") && var->isClass()) { if (!var->typeScope() && !(var->valueType() && var->valueType()->container)) continue; // Object is instantiated. Warn if constructor takes arguments by value. if (var->typeScope() && constructorTakesReference(var->typeScope())) continue; } else if (Token::simpleMatch(startTok->next(), ";") && startTok->next()->isSplittedVarDeclEq()) { startTok = startTok->tokAt(2); } else continue; const Token* tok = startTok->next()->astOperand2(); if (!tok) continue; if (!Token::Match(tok->previous(), "%name% (")) continue; if (!Token::Match(tok->link(), ") )|}| ;")) // bailout for usage like "const A a = getA()+3" continue; const Token* dot = tok->astOperand1(); if (Token::simpleMatch(dot, ".")) { const Token* varTok = dot->astOperand1(); const int indirect = varTok->valueType() ? varTok->valueType()->pointer : 0; if (isVariableChanged(tok, tok->scope()->bodyEnd, indirect, varTok->varId(), /*globalvar*/ true, *mSettings)) continue; if (isTemporary(dot, &mSettings->library, /*unknown*/ true)) continue; } if (exprDependsOnThis(tok->previous())) continue; const Function* func = tok->previous()->function(); if (func && func->tokenDef->strAt(-1) == "&") { const Scope* fScope = func->functionScope; if (fScope && fScope->bodyEnd && Token::Match(fScope->bodyEnd->tokAt(-3), "return %var% ;")) { const Token* varTok = fScope->bodyEnd->tokAt(-2); if (varTok->variable() && !varTok->variable()->isGlobal() && (!varTok->variable()->type() || !varTok->variable()->type()->classScope || (varTok->variable()->valueType() && ValueFlow::getSizeOf(*varTok->variable()->valueType(), *mSettings) > 2 * mSettings->platform.sizeof_pointer))) redundantCopyError(startTok, startTok->str()); } } } } void CheckOther::redundantCopyError(const Token *tok,const std::string& varname) { reportError(tok, Severity::performance, "redundantCopyLocalConst", "$symbol:" + varname + "\n" "Use const reference for '$symbol' to avoid unnecessary data copying.\n" "The const variable '$symbol' is assigned a copy of the data. You can avoid " "the unnecessary data copying by converting '$symbol' to const reference.", CWE398, Certainty::inconclusive); // since #5618 that check became inconclusive } //--------------------------------------------------------------------------- // Checking for shift by negative values //--------------------------------------------------------------------------- static bool isNegative(const Token *tok, const Settings &settings) { return tok->valueType() && tok->valueType()->sign == ValueType::SIGNED && tok->getValueLE(-1LL, settings); } void CheckOther::checkNegativeBitwiseShift() { const bool portability = mSettings->severity.isEnabled(Severity::portability); logChecker("CheckOther::checkNegativeBitwiseShift"); for (const Token* tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (!tok->astOperand1() || !tok->astOperand2()) continue; if (!Token::Match(tok, "<<|>>|<<=|>>=")) continue; // don't warn if lhs is a class. this is an overloaded operator then if (tok->isCpp()) { const ValueType * lhsType = tok->astOperand1()->valueType(); if (!lhsType || !lhsType->isIntegral() || lhsType->pointer) continue; } // bailout if operation is protected by ?: bool ternary = false; for (const Token *parent = tok; parent; parent = parent->astParent()) { if (Token::Match(parent, "?|:")) { ternary = true; break; } } if (ternary) continue; // Get negative rhs value. preferably a value which doesn't have 'condition'. if (portability && isNegative(tok->astOperand1(), *mSettings)) negativeBitwiseShiftError(tok, 1); else if (isNegative(tok->astOperand2(), *mSettings)) negativeBitwiseShiftError(tok, 2); } } void CheckOther::negativeBitwiseShiftError(const Token *tok, int op) { if (op == 1) // LHS - this is used by intention in various software, if it // is used often in a project and works as expected then this is // a portability issue reportError(tok, Severity::portability, "shiftNegativeLHS", "Shifting a negative value is technically undefined behaviour", CWE758, Certainty::normal); else // RHS reportError(tok, Severity::error, "shiftNegative", "Shifting by a negative value is undefined behaviour", CWE758, Certainty::normal); } //--------------------------------------------------------------------------- // Check for incompletely filled buffers. //--------------------------------------------------------------------------- void CheckOther::checkIncompleteArrayFill() { if (!mSettings->certainty.isEnabled(Certainty::inconclusive)) return; const bool printWarning = mSettings->severity.isEnabled(Severity::warning); const bool printPortability = mSettings->severity.isEnabled(Severity::portability); if (!printPortability && !printWarning) return; logChecker("CheckOther::checkIncompleteArrayFill"); // warning,portability,inconclusive const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "memset|memcpy|memmove (") && Token::Match(tok->linkAt(1)->tokAt(-2), ", %num% )")) { const Token* tok2 = tok->tokAt(2); if (tok2->str() == "::") tok2 = tok2->next(); while (Token::Match(tok2, "%name% ::|.")) tok2 = tok2->tokAt(2); if (!Token::Match(tok2, "%var% ,")) continue; const Variable *var = tok2->variable(); if (!var || !var->isArray() || var->dimensions().empty() || !var->dimension(0)) continue; if (MathLib::toBigNumber(tok->linkAt(1)->strAt(-1)) == var->dimension(0)) { int size = mTokenizer->sizeOfType(var->typeStartToken()); if (size == 0 && var->valueType()->pointer) size = mSettings->platform.sizeof_pointer; else if (size == 0 && var->valueType()) size = ValueFlow::getSizeOf(*var->valueType(), *mSettings); const Token* tok3 = tok->next()->astOperand2()->astOperand1()->astOperand1(); if ((size != 1 && size != 100 && size != 0) || var->isPointer()) { if (printWarning) incompleteArrayFillError(tok, tok3->expressionString(), tok->str(), false); } else if (var->valueType()->type == ValueType::Type::BOOL && printPortability) // sizeof(bool) is not 1 on all platforms incompleteArrayFillError(tok, tok3->expressionString(), tok->str(), true); } } } } } void CheckOther::incompleteArrayFillError(const Token* tok, const std::string& buffer, const std::string& function, bool boolean) { if (boolean) reportError(tok, Severity::portability, "incompleteArrayFill", "$symbol:" + buffer + "\n" "$symbol:" + function + "\n" "Array '" + buffer + "' might be filled incompletely. Did you forget to multiply the size given to '" + function + "()' with 'sizeof(*" + buffer + ")'?\n" "The array '" + buffer + "' is filled incompletely. The function '" + function + "()' needs the size given in bytes, but the type 'bool' is larger than 1 on some platforms. Did you forget to multiply the size with 'sizeof(*" + buffer + ")'?", CWE131, Certainty::inconclusive); else reportError(tok, Severity::warning, "incompleteArrayFill", "$symbol:" + buffer + "\n" "$symbol:" + function + "\n" "Array '" + buffer + "' is filled incompletely. Did you forget to multiply the size given to '" + function + "()' with 'sizeof(*" + buffer + ")'?\n" "The array '" + buffer + "' is filled incompletely. The function '" + function + "()' needs the size given in bytes, but an element of the given array is larger than one byte. Did you forget to multiply the size with 'sizeof(*" + buffer + ")'?", CWE131, Certainty::inconclusive); } //--------------------------------------------------------------------------- // Detect NULL being passed to variadic function. //--------------------------------------------------------------------------- void CheckOther::checkVarFuncNullUB() { if (!mSettings->severity.isEnabled(Severity::portability)) return; logChecker("CheckOther::checkVarFuncNullUB"); // portability const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { // Is NULL passed to a function? if (Token::Match(tok,"[(,] NULL [,)]")) { // Locate function name in this function call. const Token *ftok = tok; int argnr = 1; while (ftok && ftok->str() != "(") { if (ftok->str() == ")") ftok = ftok->link(); else if (ftok->str() == ",") ++argnr; ftok = ftok->previous(); } ftok = ftok ? ftok->previous() : nullptr; if (ftok && ftok->isName()) { // If this is a variadic function then report error const Function *f = ftok->function(); if (f && f->argCount() <= argnr) { const Token *tok2 = f->argDef; tok2 = tok2 ? tok2->link() : nullptr; // goto ')' if (tok2 && Token::simpleMatch(tok2->tokAt(-1), "...")) varFuncNullUBError(tok); } } } } } } void CheckOther::varFuncNullUBError(const Token *tok) { reportError(tok, Severity::portability, "varFuncNullUB", "Passing NULL after the last typed argument to a variadic function leads to undefined behaviour.\n" "Passing NULL after the last typed argument to a variadic function leads to undefined behaviour.\n" "The C99 standard, in section 7.15.1.1, states that if the type used by va_arg() is not compatible with the type of the actual next argument (as promoted according to the default argument promotions), the behavior is undefined.\n" "The value of the NULL macro is an implementation-defined null pointer constant (7.17), which can be any integer constant expression with the value 0, or such an expression casted to (void*) (6.3.2.3). This includes values like 0, 0L, or even 0LL.\n" "In practice on common architectures, this will cause real crashes if sizeof(int) != sizeof(void*), and NULL is defined to 0 or any other null pointer constant that promotes to int.\n" "To reproduce you might be able to use this little code example on 64bit platforms. If the output includes \"ERROR\", the sentinel had only 4 out of 8 bytes initialized to zero and was not detected as the final argument to stop argument processing via va_arg(). Changing the 0 to (void*)0 or 0L will make the \"ERROR\" output go away.\n" "#include <stdarg.h>\n" "#include <stdio.h>\n" "\n" "void f(char *s, ...) {\n" " va_list ap;\n" " va_start(ap,s);\n" " for (;;) {\n" " char *p = va_arg(ap,char*);\n" " printf(\"%018p, %s\\n\", p, (long)p & 255 ? p : \"\");\n" " if(!p) break;\n" " }\n" " va_end(ap);\n" "}\n" "\n" "void g() {\n" " char *s2 = \"x\";\n" " char *s3 = \"ERROR\";\n" "\n" " // changing 0 to 0L for the 7th argument (which is intended to act as sentinel) makes the error go away on x86_64\n" " f(\"first\", s2, s2, s2, s2, s2, 0, s3, (char*)0);\n" "}\n" "\n" "void h() {\n" " int i;\n" " volatile unsigned char a[1000];\n" " for (i = 0; i<sizeof(a); i++)\n" " a[i] = -1;\n" "}\n" "\n" "int main() {\n" " h();\n" " g();\n" " return 0;\n" "}", CWE475, Certainty::normal); } void CheckOther::checkRedundantPointerOp() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("redundantPointerOp")) return; logChecker("CheckOther::checkRedundantPointerOp"); // style for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (tok->isExpandedMacro() && tok->str() == "(") tok = tok->link(); bool addressOfDeref{}; if (tok->isUnaryOp("&") && tok->astOperand1()->isUnaryOp("*")) addressOfDeref = true; else if (tok->isUnaryOp("*") && tok->astOperand1()->isUnaryOp("&")) addressOfDeref = false; else continue; // variable const Token *varTok = tok->astOperand1()->astOperand1(); if (!varTok || varTok->isExpandedMacro()) continue; if (!addressOfDeref) { // dereference of address if (tok->isExpandedMacro()) continue; if (varTok->valueType() && varTok->valueType()->pointer && varTok->valueType()->reference == Reference::LValue) continue; } const Variable *var = varTok->variable(); if (!var || (addressOfDeref && !var->isPointer())) continue; redundantPointerOpError(tok, var->name(), false, addressOfDeref); } } void CheckOther::redundantPointerOpError(const Token* tok, const std::string &varname, bool inconclusive, bool addressOfDeref) { std::string msg = "$symbol:" + varname + "\nRedundant pointer operation on '$symbol' - it's already a "; msg += addressOfDeref ? "pointer." : "variable."; reportError(tok, Severity::style, "redundantPointerOp", msg, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckOther::checkInterlockedDecrement() { if (!mSettings->platform.isWindows()) { return; } logChecker("CheckOther::checkInterlockedDecrement"); // windows-platform for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (tok->isName() && Token::Match(tok, "InterlockedDecrement ( & %name% ) ; if ( %name%|!|0")) { const Token* interlockedVarTok = tok->tokAt(3); const Token* checkStartTok = interlockedVarTok->tokAt(5); if ((Token::Match(checkStartTok, "0 %comp% %name% )") && checkStartTok->strAt(2) == interlockedVarTok->str()) || (Token::Match(checkStartTok, "! %name% )") && checkStartTok->strAt(1) == interlockedVarTok->str()) || (Token::Match(checkStartTok, "%name% )") && checkStartTok->str() == interlockedVarTok->str()) || (Token::Match(checkStartTok, "%name% %comp% 0 )") && checkStartTok->str() == interlockedVarTok->str())) { raceAfterInterlockedDecrementError(checkStartTok); } } else if (Token::Match(tok, "if ( ::| InterlockedDecrement ( & %name%")) { const Token* condEnd = tok->linkAt(1); const Token* funcTok = tok->tokAt(2); const Token* firstAccessTok = funcTok->str() == "::" ? funcTok->tokAt(4) : funcTok->tokAt(3); if (condEnd && condEnd->next() && condEnd->linkAt(1)) { const Token* ifEndTok = condEnd->linkAt(1); if (Token::Match(ifEndTok, "} return %name%")) { const Token* secondAccessTok = ifEndTok->tokAt(2); if (secondAccessTok->str() == firstAccessTok->str()) { raceAfterInterlockedDecrementError(secondAccessTok); } } else if (Token::Match(ifEndTok, "} else { return %name%")) { const Token* secondAccessTok = ifEndTok->tokAt(4); if (secondAccessTok->str() == firstAccessTok->str()) { raceAfterInterlockedDecrementError(secondAccessTok); } } } } } } void CheckOther::raceAfterInterlockedDecrementError(const Token* tok) { reportError(tok, Severity::error, "raceAfterInterlockedDecrement", "Race condition: non-interlocked access after InterlockedDecrement(). Use InterlockedDecrement() return value instead.", CWE362, Certainty::normal); } void CheckOther::checkUnusedLabel() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("unusedLabel")) return; logChecker("CheckOther::checkUnusedLabel"); // style,warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { const bool hasIfdef = mTokenizer->hasIfdef(scope->bodyStart, scope->bodyEnd); for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (!tok->scope()->isExecutable()) tok = tok->scope()->bodyEnd; if (Token::Match(tok, "{|}|; %name% :") && !tok->tokAt(1)->isKeyword()) { const std::string tmp("goto " + tok->strAt(1)); if (!Token::findsimplematch(scope->bodyStart->next(), tmp.c_str(), tmp.size(), scope->bodyEnd->previous()) && !tok->next()->isExpandedMacro()) unusedLabelError(tok->next(), tok->next()->scope()->type == Scope::eSwitch, hasIfdef); } } } } void CheckOther::unusedLabelError(const Token* tok, bool inSwitch, bool hasIfdef) { if (tok && !mSettings->severity.isEnabled(inSwitch ? Severity::warning : Severity::style)) return; std::string id = "unusedLabel"; if (inSwitch) id += "Switch"; if (hasIfdef) id += "Configuration"; std::string msg = "$symbol:" + (tok ? tok->str() : emptyString) + "\nLabel '$symbol' is not used."; if (hasIfdef) msg += " There is #if in function body so the label might be used in code that is removed by the preprocessor."; if (inSwitch) msg += " Should this be a 'case' of the enclosing switch()?"; reportError(tok, inSwitch ? Severity::warning : Severity::style, id, msg, CWE398, Certainty::normal); } static bool checkEvaluationOrderC(const Token * tok, const Token * tok2, const Token * parent, const Settings & settings, bool & selfAssignmentError) { // self assignment.. if (tok2 == tok && tok->str() == "=" && parent->str() == "=" && isSameExpression(false, tok->astOperand1(), parent->astOperand1(), settings, true, false)) { if (settings.severity.isEnabled(Severity::warning) && isSameExpression(true, tok->astOperand1(), parent->astOperand1(), settings, true, false)) selfAssignmentError = true; return false; } // Is expression used? bool foundError = false; visitAstNodes((parent->astOperand1() != tok2) ? parent->astOperand1() : parent->astOperand2(), [&](const Token *tok3) { if (tok3->str() == "&" && !tok3->astOperand2()) return ChildrenToVisit::none; // don't handle address-of for now if (tok3->str() == "(" && Token::simpleMatch(tok3->previous(), "sizeof")) return ChildrenToVisit::none; // don't care about sizeof usage if (isSameExpression(false, tok->astOperand1(), tok3, settings, true, false)) foundError = true; return foundError ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2; }); return foundError; } static bool checkEvaluationOrderCpp11(const Token * tok, const Token * tok2, const Token * parent, const Settings & settings) { if (tok->isAssignmentOp()) // TODO check assignment return false; if (tok->previous() == tok->astOperand1() && parent->isArithmeticalOp() && parent->isBinaryOp()) { if (parent->astParent() && parent->astParent()->isAssignmentOp() && isSameExpression(false, tok->astOperand1(), parent->astParent()->astOperand1(), settings, true, false)) return true; } bool foundUndefined{false}; visitAstNodes((parent->astOperand1() != tok2) ? parent->astOperand1() : parent->astOperand2(), [&](const Token *tok3) { if (tok3->str() == "&" && !tok3->astOperand2()) return ChildrenToVisit::none; // don't handle address-of for now if (tok3->str() == "(" && Token::simpleMatch(tok3->previous(), "sizeof")) return ChildrenToVisit::none; // don't care about sizeof usage if (isSameExpression(false, tok->astOperand1(), tok3, settings, true, false)) foundUndefined = true; return foundUndefined ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2; }); return foundUndefined; } static bool checkEvaluationOrderCpp17(const Token * tok, const Token * tok2, const Token * parent, const Settings & settings, bool & foundUnspecified) { if (tok->isAssignmentOp()) return false; bool foundUndefined{false}; visitAstNodes((parent->astOperand1() != tok2) ? parent->astOperand1() : parent->astOperand2(), [&](const Token *tok3) { if (tok3->str() == "&" && !tok3->astOperand2()) return ChildrenToVisit::none; // don't handle address-of for now if (tok3->str() == "(" && Token::simpleMatch(tok3->previous(), "sizeof")) return ChildrenToVisit::none; // don't care about sizeof usage if (isSameExpression(false, tok->astOperand1(), tok3, settings, true, false) && parent->isArithmeticalOp() && parent->isBinaryOp()) foundUndefined = true; if (tok3->tokType() == Token::eIncDecOp && isSameExpression(false, tok->astOperand1(), tok3->astOperand1(), settings, true, false)) { if (parent->isArithmeticalOp() && parent->isBinaryOp()) foundUndefined = true; else foundUnspecified = true; } return (foundUndefined || foundUnspecified) ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2; }); return foundUndefined || foundUnspecified; } void CheckOther::checkEvaluationOrder() { logChecker("CheckOther::checkEvaluationOrder"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * functionScope : symbolDatabase->functionScopes) { for (const Token* tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) { if (!tok->isIncDecOp() && !tok->isAssignmentOp()) continue; if (!tok->astOperand1()) continue; for (const Token *tok2 = tok;; tok2 = tok2->astParent()) { // If ast parent is a sequence point then break const Token * const parent = tok2->astParent(); if (!parent) break; if (Token::Match(parent, "%oror%|&&|?|:|;")) break; if (parent->str() == ",") { const Token *par = parent; while (Token::simpleMatch(par,",")) par = par->astParent(); // not function or in a while clause => break if (!(par && par->str() == "(" && par->astOperand2() && par->strAt(-1) != "while")) break; // control flow (if|while|etc) => break if (Token::simpleMatch(par->link(),") {")) break; // sequence point in function argument: dostuff((1,2),3) => break par = par->next(); while (par && (par->previous() != parent)) par = par->nextArgument(); if (!par) break; } if (parent->str() == "(" && parent->astOperand2()) break; bool foundError{false}, foundUnspecified{false}, bSelfAssignmentError{false}; if (mTokenizer->isCPP() && mSettings->standards.cpp >= Standards::CPP11) { if (mSettings->standards.cpp >= Standards::CPP17) foundError = checkEvaluationOrderCpp17(tok, tok2, parent, *mSettings, foundUnspecified); else foundError = checkEvaluationOrderCpp11(tok, tok2, parent, *mSettings); } else foundError = checkEvaluationOrderC(tok, tok2, parent, *mSettings, bSelfAssignmentError); if (foundError) { unknownEvaluationOrder(parent, foundUnspecified); break; } if (bSelfAssignmentError) { selfAssignmentError(parent, tok->astOperand1()->expressionString()); break; } } } } } void CheckOther::unknownEvaluationOrder(const Token* tok, bool isUnspecifiedBehavior) { isUnspecifiedBehavior ? reportError(tok, Severity::portability, "unknownEvaluationOrder", "Expression '" + (tok ? tok->expressionString() : std::string("x++, x++")) + "' depends on order of evaluation of side effects. Behavior is Unspecified according to c++17", CWE768, Certainty::normal) : reportError(tok, Severity::error, "unknownEvaluationOrder", "Expression '" + (tok ? tok->expressionString() : std::string("x = x++;")) + "' depends on order of evaluation of side effects", CWE768, Certainty::normal); } void CheckOther::checkAccessOfMovedVariable() { if (!mTokenizer->isCPP() || mSettings->standards.cpp < Standards::CPP11) return; if (!mSettings->isPremiumEnabled("accessMoved") && !mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckOther::checkAccessOfMovedVariable"); // c++11,warning const bool reportInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { const Token * scopeStart = scope->bodyStart; if (scope->function) { const Token * memberInitializationStart = scope->function->constructorMemberInitialization(); if (memberInitializationStart) scopeStart = memberInitializationStart; } for (const Token* tok = scopeStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->astParent()) continue; const ValueFlow::Value * movedValue = tok->getMovedValue(); if (!movedValue || movedValue->moveKind == ValueFlow::Value::MoveKind::NonMovedVariable) continue; if (movedValue->isInconclusive() && !reportInconclusive) continue; bool inconclusive = false; bool accessOfMoved = false; if (tok->strAt(1) == ".") { if (tok->next()->originalName() == "->") accessOfMoved = true; else inconclusive = true; } else { const ExprUsage usage = getExprUsage(tok, 0, *mSettings); if (usage == ExprUsage::Used) accessOfMoved = true; if (usage == ExprUsage::PassedByReference) accessOfMoved = !isVariableChangedByFunctionCall(tok, 0, *mSettings, &inconclusive); else if (usage == ExprUsage::Inconclusive) inconclusive = true; } if (accessOfMoved || (inconclusive && reportInconclusive)) accessMovedError(tok, tok->str(), movedValue, inconclusive || movedValue->isInconclusive()); } } } void CheckOther::accessMovedError(const Token *tok, const std::string &varname, const ValueFlow::Value *value, bool inconclusive) { if (!tok) { reportError(tok, Severity::warning, "accessMoved", "Access of moved variable 'v'.", CWE672, Certainty::normal); reportError(tok, Severity::warning, "accessForwarded", "Access of forwarded variable 'v'.", CWE672, Certainty::normal); return; } const char * errorId = nullptr; std::string kindString; switch (value->moveKind) { case ValueFlow::Value::MoveKind::MovedVariable: errorId = "accessMoved"; kindString = "moved"; break; case ValueFlow::Value::MoveKind::ForwardedVariable: errorId = "accessForwarded"; kindString = "forwarded"; break; default: return; } const std::string errmsg("$symbol:" + varname + "\nAccess of " + kindString + " variable '$symbol'."); const ErrorPath errorPath = getErrorPath(tok, value, errmsg); reportError(errorPath, Severity::warning, errorId, errmsg, CWE672, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckOther::checkFuncArgNamesDifferent() { const bool style = mSettings->severity.isEnabled(Severity::style); const bool inconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const bool warning = mSettings->severity.isEnabled(Severity::warning); if (!(warning || (style && inconclusive)) && !mSettings->isPremiumEnabled("funcArgNamesDifferent")) return; logChecker("CheckOther::checkFuncArgNamesDifferent"); // style,warning,inconclusive const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); // check every function for (const Scope *scope : symbolDatabase->functionScopes) { const Function * function = scope->function; // only check functions with arguments if (!function || function->argCount() == 0) continue; // only check functions with separate declarations and definitions if (function->argDef == function->arg) continue; // get the function argument name tokens std::vector<const Token *> declarations(function->argCount()); std::vector<const Token *> definitions(function->argCount()); const Token * decl = function->argDef->next(); for (int j = 0; j < function->argCount(); ++j) { declarations[j] = nullptr; definitions[j] = nullptr; // get the definition const Variable * variable = function->getArgumentVar(j); if (variable) { definitions[j] = variable->nameToken(); } // get the declaration (search for first token with varId) while (decl && !Token::Match(decl, ",|)|;")) { // skip everything after the assignment because // it could also have a varId or be the first // token with a varId if there is no name token if (decl->str() == "=") { decl = decl->nextArgument(); break; } // skip over template if (decl->link()) decl = decl->link(); else if (decl->varId()) declarations[j] = decl; decl = decl->next(); } if (Token::simpleMatch(decl, ",")) decl = decl->next(); } // check for different argument order if (warning) { bool order_different = false; for (int j = 0; j < function->argCount(); ++j) { if (!declarations[j] || !definitions[j] || declarations[j]->str() == definitions[j]->str()) continue; for (int k = 0; k < function->argCount(); ++k) { if (j != k && definitions[k] && declarations[j]->str() == definitions[k]->str()) { order_different = true; break; } } } if (order_different) { funcArgOrderDifferent(function->name(), function->argDef->next(), function->arg->next(), declarations, definitions); continue; } } // check for different argument names if (style && inconclusive) { for (int j = 0; j < function->argCount(); ++j) { if (declarations[j] && definitions[j] && declarations[j]->str() != definitions[j]->str()) funcArgNamesDifferent(function->name(), j, declarations[j], definitions[j]); } } } } void CheckOther::funcArgNamesDifferent(const std::string & functionName, nonneg int index, const Token* declaration, const Token* definition) { std::list<const Token *> tokens = { declaration,definition }; reportError(tokens, Severity::style, "funcArgNamesDifferent", "$symbol:" + functionName + "\n" "Function '$symbol' argument " + std::to_string(index + 1) + " names different: declaration '" + (declaration ? declaration->str() : std::string("A")) + "' definition '" + (definition ? definition->str() : std::string("B")) + "'.", CWE628, Certainty::inconclusive); } void CheckOther::funcArgOrderDifferent(const std::string & functionName, const Token* declaration, const Token* definition, const std::vector<const Token *> & declarations, const std::vector<const Token *> & definitions) { std::list<const Token *> tokens = { !declarations.empty() ? declarations[0] ? declarations[0] : declaration : nullptr, !definitions.empty() ? definitions[0] ? definitions[0] : definition : nullptr }; std::string msg = "$symbol:" + functionName + "\nFunction '$symbol' argument order different: declaration '"; for (std::size_t i = 0; i < declarations.size(); ++i) { if (i != 0) msg += ", "; if (declarations[i]) msg += declarations[i]->str(); } msg += "' definition '"; for (std::size_t i = 0; i < definitions.size(); ++i) { if (i != 0) msg += ", "; if (definitions[i]) msg += definitions[i]->str(); } msg += "'"; reportError(tokens, Severity::warning, "funcArgOrderDifferent", msg, CWE683, Certainty::normal); } static const Token *findShadowed(const Scope *scope, const Variable& var, int linenr) { if (!scope) return nullptr; for (const Variable &v : scope->varlist) { if (scope->isExecutable() && v.nameToken()->linenr() > linenr) continue; if (v.name() == var.name()) return v.nameToken(); } auto it = std::find_if(scope->functionList.cbegin(), scope->functionList.cend(), [&](const Function& f) { return f.type == Function::Type::eFunction && f.name() == var.name() && precedes(f.tokenDef, var.nameToken()); }); if (it != scope->functionList.end()) return it->tokenDef; if (scope->type == Scope::eLambda) return nullptr; const Token* shadowed = findShadowed(scope->nestedIn, var, linenr); if (!shadowed) shadowed = findShadowed(scope->functionOf, var, linenr); return shadowed; } void CheckOther::checkShadowVariables() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("shadowVariable")) return; logChecker("CheckOther::checkShadowVariables"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope & scope : symbolDatabase->scopeList) { if (!scope.isExecutable() || scope.type == Scope::eLambda) continue; const Scope *functionScope = &scope; while (functionScope && functionScope->type != Scope::ScopeType::eFunction && functionScope->type != Scope::ScopeType::eLambda) functionScope = functionScope->nestedIn; for (const Variable &var : scope.varlist) { if (var.nameToken() && var.nameToken()->isExpandedMacro()) // #8903 continue; if (functionScope && functionScope->type == Scope::ScopeType::eFunction && functionScope->function) { const auto & argList = functionScope->function->argumentList; auto it = std::find_if(argList.cbegin(), argList.cend(), [&](const Variable& arg) { return arg.nameToken() && var.name() == arg.name(); }); if (it != argList.end()) { shadowError(var.nameToken(), it->nameToken(), "argument"); continue; } } const Token *shadowed = findShadowed(scope.nestedIn, var, var.nameToken()->linenr()); if (!shadowed) shadowed = findShadowed(scope.functionOf, var, var.nameToken()->linenr()); if (!shadowed) continue; if (scope.type == Scope::eFunction && scope.className == var.name()) continue; if (functionScope->functionOf && functionScope->functionOf->isClassOrStructOrUnion() && functionScope->function && functionScope->function->isStatic() && shadowed->variable() && !shadowed->variable()->isLocal()) continue; shadowError(var.nameToken(), shadowed, (shadowed->varId() != 0) ? "variable" : "function"); } } } void CheckOther::shadowError(const Token *var, const Token *shadowed, const std::string& type) { ErrorPath errorPath; errorPath.emplace_back(shadowed, "Shadowed declaration"); errorPath.emplace_back(var, "Shadow variable"); const std::string &varname = var ? var->str() : type; const std::string Type = char(std::toupper(type[0])) + type.substr(1); const std::string id = "shadow" + Type; const std::string message = "$symbol:" + varname + "\nLocal variable \'$symbol\' shadows outer " + type; reportError(errorPath, Severity::style, id.c_str(), message, CWE398, Certainty::normal); } static bool isVariableExpression(const Token* tok) { if (tok->varId() != 0) return true; if (Token::simpleMatch(tok, ".")) return isVariableExpression(tok->astOperand1()) && isVariableExpression(tok->astOperand2()); if (Token::simpleMatch(tok, "[")) return isVariableExpression(tok->astOperand1()); return false; } static bool isVariableExprHidden(const Token* tok) { if (!tok) return false; if (!tok->astParent()) return false; if (Token::simpleMatch(tok->astParent(), "*") && Token::simpleMatch(tok->astSibling(), "0")) return true; if (Token::simpleMatch(tok->astParent(), "&&") && Token::simpleMatch(tok->astSibling(), "false")) return true; if (Token::simpleMatch(tok->astParent(), "||") && Token::simpleMatch(tok->astSibling(), "true")) return true; return false; } void CheckOther::checkKnownArgument() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("knownArgument")) return; logChecker("CheckOther::checkKnownArgument"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *functionScope : symbolDatabase->functionScopes) { for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) { if (!tok->hasKnownIntValue()) continue; if (Token::Match(tok, "++|--|%assign%")) continue; if (!Token::Match(tok->astParent(), "(|{|,")) continue; if (tok->astParent()->isCast() || (tok->isCast() && Token::Match(tok->astOperand2(), "++|--|%assign%"))) continue; int argn = -1; const Token* ftok = getTokenArgumentFunction(tok, argn); if (!ftok) continue; if (ftok->isCast()) continue; if (Token::Match(ftok, "if|while|switch|sizeof")) continue; if (tok == tok->astParent()->previous()) continue; if (isConstVarExpression(tok)) continue; if (Token::Match(tok->astOperand1(), "%name% (")) continue; const Token * tok2 = tok; if (isCPPCast(tok2)) tok2 = tok2->astOperand2(); if (isVariableExpression(tok2)) continue; if (tok->isComparisonOp() && isSameExpression( true, tok->astOperand1(), tok->astOperand2(), *mSettings, true, true)) continue; // ensure that there is a integer variable in expression with unknown value const Token* vartok = nullptr; visitAstNodes(tok, [&](const Token* child) { if (Token::Match(child, "%var%|.|[")) { if (child->hasKnownIntValue()) return ChildrenToVisit::none; if (astIsIntegral(child, false) && !astIsPointer(child) && child->values().empty()) { vartok = child; return ChildrenToVisit::done; } } return ChildrenToVisit::op1_and_op2; }); if (!vartok) continue; if (vartok->astSibling() && findAstNode(vartok->astSibling(), [](const Token* child) { return Token::simpleMatch(child, "sizeof"); })) continue; // ensure that function name does not contain "assert" std::string funcname = ftok->str(); strTolower(funcname); if (funcname.find("assert") != std::string::npos) continue; knownArgumentError(tok, ftok, &tok->values().front(), vartok->expressionString(), isVariableExprHidden(vartok)); } } } void CheckOther::knownArgumentError(const Token *tok, const Token *ftok, const ValueFlow::Value *value, const std::string &varexpr, bool isVariableExpressionHidden) { if (!tok) { reportError(tok, Severity::style, "knownArgument", "Argument 'x-x' to function 'func' is always 0. It does not matter what value 'x' has."); reportError(tok, Severity::style, "knownArgumentHiddenVariableExpression", "Argument 'x*0' to function 'func' is always 0. Constant literal calculation disable/hide variable expression 'x'."); return; } const MathLib::bigint intvalue = value->intvalue; const std::string &expr = tok->expressionString(); const std::string &fun = ftok->str(); std::string ftype = "function "; if (ftok->type()) ftype = "constructor "; else if (fun == "{") ftype = "init list "; const char *id; std::string errmsg = "Argument '" + expr + "' to " + ftype + fun + " is always " + std::to_string(intvalue) + ". "; if (!isVariableExpressionHidden) { id = "knownArgument"; errmsg += "It does not matter what value '" + varexpr + "' has."; } else { id = "knownArgumentHiddenVariableExpression"; errmsg += "Constant literal calculation disable/hide variable expression '" + varexpr + "'."; } const ErrorPath errorPath = getErrorPath(tok, value, errmsg); reportError(errorPath, Severity::style, id, errmsg, CWE570, Certainty::normal); } void CheckOther::checkKnownPointerToBool() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("knownPointerToBool")) return; logChecker("CheckOther::checkKnownPointerToBool"); // style const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope* functionScope : symbolDatabase->functionScopes) { for (const Token* tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) { if (!tok->hasKnownIntValue()) continue; if (!astIsPointer(tok)) continue; if (Token::Match(tok->astParent(), "?|!|&&|%oror%|%comp%")) continue; if (tok->astParent() && Token::Match(tok->astParent()->previous(), "if|while|switch|sizeof (")) continue; if (tok->isExpandedMacro()) continue; if (findParent(tok, [](const Token* parent) { return parent->isExpandedMacro(); })) continue; if (!isUsedAsBool(tok, *mSettings)) continue; const ValueFlow::Value& value = tok->values().front(); knownPointerToBoolError(tok, &value); } } } void CheckOther::knownPointerToBoolError(const Token* tok, const ValueFlow::Value* value) { if (!tok) { reportError(tok, Severity::style, "knownPointerToBool", "Pointer expression 'p' converted to bool is always true."); return; } std::string cond = bool_to_string(value->intvalue); const std::string& expr = tok->expressionString(); std::string errmsg = "Pointer expression '" + expr + "' converted to bool is always " + cond + "."; const ErrorPath errorPath = getErrorPath(tok, value, errmsg); reportError(errorPath, Severity::style, "knownPointerToBool", errmsg, CWE570, Certainty::normal); } void CheckOther::checkComparePointers() { logChecker("CheckOther::checkComparePointers"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *functionScope : symbolDatabase->functionScopes) { for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "<|>|<=|>=|-")) continue; const Token *tok1 = tok->astOperand1(); const Token *tok2 = tok->astOperand2(); if (!astIsPointer(tok1) || !astIsPointer(tok2)) continue; ValueFlow::Value v1 = ValueFlow::getLifetimeObjValue(tok1); ValueFlow::Value v2 = ValueFlow::getLifetimeObjValue(tok2); if (!v1.isLocalLifetimeValue() || !v2.isLocalLifetimeValue()) continue; const Variable *var1 = v1.tokvalue->variable(); const Variable *var2 = v2.tokvalue->variable(); if (!var1 || !var2) continue; if (v1.tokvalue->varId() == v2.tokvalue->varId()) continue; if (var1->isReference() || var2->isReference()) continue; if (var1->isRValueReference() || var2->isRValueReference()) continue; if (const Token* parent2 = getParentLifetime(v2.tokvalue, mSettings->library)) if (var1 == parent2->variable()) continue; if (const Token* parent1 = getParentLifetime(v1.tokvalue, mSettings->library)) if (var2 == parent1->variable()) continue; comparePointersError(tok, &v1, &v2); } } } void CheckOther::comparePointersError(const Token *tok, const ValueFlow::Value *v1, const ValueFlow::Value *v2) { ErrorPath errorPath; std::string verb = "Comparing"; if (Token::simpleMatch(tok, "-")) verb = "Subtracting"; const char * const id = (verb[0] == 'C') ? "comparePointers" : "subtractPointers"; if (v1) { errorPath.emplace_back(v1->tokvalue->variable()->nameToken(), "Variable declared here."); errorPath.insert(errorPath.end(), v1->errorPath.cbegin(), v1->errorPath.cend()); } if (v2) { errorPath.emplace_back(v2->tokvalue->variable()->nameToken(), "Variable declared here."); errorPath.insert(errorPath.end(), v2->errorPath.cbegin(), v2->errorPath.cend()); } errorPath.emplace_back(tok, ""); reportError( errorPath, Severity::error, id, verb + " pointers that point to different objects", CWE570, Certainty::normal); } void CheckOther::checkModuloOfOne() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("moduloofone")) return; logChecker("CheckOther::checkModuloOfOne"); // style for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (!tok->astOperand2() || !tok->astOperand1()) continue; if (tok->str() != "%") continue; if (!tok->valueType() || !tok->valueType()->isIntegral()) continue; // Value flow.. const ValueFlow::Value *value = tok->astOperand2()->getValue(1LL); if (value && value->isKnown()) checkModuloOfOneError(tok); } } void CheckOther::checkModuloOfOneError(const Token *tok) { reportError(tok, Severity::style, "moduloofone", "Modulo of one is always equal to zero"); } //----------------------------------------------------------------------------- // Overlapping write (undefined behavior) //----------------------------------------------------------------------------- static bool getBufAndOffset(const Token *expr, const Token *&buf, MathLib::bigint *offset, const Settings& settings, MathLib::bigint* sizeValue = nullptr) { if (!expr) return false; const Token *bufToken, *offsetToken; MathLib::bigint elementSize = 0; if (expr->isUnaryOp("&") && Token::simpleMatch(expr->astOperand1(), "[")) { bufToken = expr->astOperand1()->astOperand1(); offsetToken = expr->astOperand1()->astOperand2(); if (expr->astOperand1()->valueType()) elementSize = ValueFlow::getSizeOf(*expr->astOperand1()->valueType(), settings); } else if (Token::Match(expr, "+|-") && expr->isBinaryOp()) { const bool pointer1 = (expr->astOperand1()->valueType() && expr->astOperand1()->valueType()->pointer > 0); const bool pointer2 = (expr->astOperand2()->valueType() && expr->astOperand2()->valueType()->pointer > 0); if (pointer1 && !pointer2) { bufToken = expr->astOperand1(); offsetToken = expr->astOperand2(); auto vt = *expr->astOperand1()->valueType(); --vt.pointer; elementSize = ValueFlow::getSizeOf(vt, settings); } else if (!pointer1 && pointer2) { bufToken = expr->astOperand2(); offsetToken = expr->astOperand1(); auto vt = *expr->astOperand2()->valueType(); --vt.pointer; elementSize = ValueFlow::getSizeOf(vt, settings); } else { return false; } } else if (expr->valueType() && expr->valueType()->pointer > 0) { buf = expr; *offset = 0; auto vt = *expr->valueType(); --vt.pointer; elementSize = ValueFlow::getSizeOf(vt, settings); if (elementSize > 0) { *offset *= elementSize; if (sizeValue) *sizeValue *= elementSize; } return true; } else { return false; } if (!bufToken->valueType() || !bufToken->valueType()->pointer) return false; if (!offsetToken->hasKnownIntValue()) return false; buf = bufToken; *offset = offsetToken->getKnownIntValue(); if (elementSize > 0) { *offset *= elementSize; if (sizeValue) *sizeValue *= elementSize; } return true; } void CheckOther::checkOverlappingWrite() { logChecker("CheckOther::checkOverlappingWrite"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *functionScope : symbolDatabase->functionScopes) { for (const Token *tok = functionScope->bodyStart; tok != functionScope->bodyEnd; tok = tok->next()) { if (tok->isAssignmentOp()) { // check if LHS is a union member.. const Token * const lhs = tok->astOperand1(); if (!Token::simpleMatch(lhs, ".") || !lhs->isBinaryOp()) continue; const Variable * const lhsvar = lhs->astOperand1()->variable(); if (!lhsvar || !lhsvar->typeScope() || lhsvar->typeScope()->type != Scope::ScopeType::eUnion) continue; const Token* const lhsmember = lhs->astOperand2(); if (!lhsmember) continue; // Is other union member used in RHS? const Token *errorToken = nullptr; visitAstNodes(tok->astOperand2(), [lhsvar, lhsmember, &errorToken](const Token *rhs) { if (!Token::simpleMatch(rhs, ".")) return ChildrenToVisit::op1_and_op2; if (!rhs->isBinaryOp() || rhs->astOperand1()->variable() != lhsvar) return ChildrenToVisit::none; if (lhsmember->str() == rhs->astOperand2()->str()) return ChildrenToVisit::none; const Variable* rhsmembervar = rhs->astOperand2()->variable(); const Scope* varscope1 = lhsmember->variable() ? lhsmember->variable()->typeStartToken()->scope() : nullptr; const Scope* varscope2 = rhsmembervar ? rhsmembervar->typeStartToken()->scope() : nullptr; if (varscope1 && varscope1 == varscope2 && varscope1 != lhsvar->typeScope()) // lhsmember and rhsmember are declared in same anonymous scope inside union return ChildrenToVisit::none; errorToken = rhs->astOperand2(); return ChildrenToVisit::done; }); if (errorToken) overlappingWriteUnion(tok); } else if (Token::Match(tok, "%name% (")) { const Library::NonOverlappingData *nonOverlappingData = mSettings->library.getNonOverlappingData(tok); if (!nonOverlappingData) continue; const std::vector<const Token *> args = getArguments(tok); if (nonOverlappingData->ptr1Arg <= 0 || nonOverlappingData->ptr1Arg > args.size()) continue; if (nonOverlappingData->ptr2Arg <= 0 || nonOverlappingData->ptr2Arg > args.size()) continue; const Token *ptr1 = args[nonOverlappingData->ptr1Arg - 1]; if (ptr1->hasKnownIntValue() && ptr1->getKnownIntValue() == 0) continue; const Token *ptr2 = args[nonOverlappingData->ptr2Arg - 1]; if (ptr2->hasKnownIntValue() && ptr2->getKnownIntValue() == 0) continue; // TODO: nonOverlappingData->strlenArg const int sizeArg = std::max(nonOverlappingData->sizeArg, nonOverlappingData->countArg); if (sizeArg <= 0 || sizeArg > args.size()) { if (nonOverlappingData->sizeArg == -1) { ErrorPath errorPath; constexpr bool macro = true; constexpr bool pure = true; constexpr bool follow = true; if (!isSameExpression(macro, ptr1, ptr2, *mSettings, pure, follow, &errorPath)) continue; overlappingWriteFunction(tok); } continue; } const bool isCountArg = nonOverlappingData->countArg > 0; if (!args[sizeArg-1]->hasKnownIntValue()) continue; MathLib::bigint sizeValue = args[sizeArg-1]->getKnownIntValue(); const Token *buf1, *buf2; MathLib::bigint offset1, offset2; if (!getBufAndOffset(ptr1, buf1, &offset1, *mSettings, isCountArg ? &sizeValue : nullptr)) continue; if (!getBufAndOffset(ptr2, buf2, &offset2, *mSettings)) continue; if (offset1 < offset2 && offset1 + sizeValue <= offset2) continue; if (offset2 < offset1 && offset2 + sizeValue <= offset1) continue; ErrorPath errorPath; constexpr bool macro = true; constexpr bool pure = true; constexpr bool follow = true; if (!isSameExpression(macro, buf1, buf2, *mSettings, pure, follow, &errorPath)) continue; overlappingWriteFunction(tok); } } } } void CheckOther::overlappingWriteUnion(const Token *tok) { reportError(tok, Severity::error, "overlappingWriteUnion", "Overlapping read/write of union is undefined behavior"); } void CheckOther::overlappingWriteFunction(const Token *tok) { const std::string &funcname = tok ? tok->str() : emptyString; reportError(tok, Severity::error, "overlappingWriteFunction", "Overlapping read/write in " + funcname + "() is undefined behavior"); }
205,486
C++
.cpp
3,861
41.176897
353
0.55349
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,112
vf_conditionexpressions.cpp
danmar_cppcheck/lib/vf_conditionexpressions.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_conditionexpressions.h" #include "astutils.h" #include "forwardanalyzer.h" #include "symboldatabase.h" #include "errorlogger.h" #include "errortypes.h" #include "library.h" #include "settings.h" #include "sourcelocation.h" #include "token.h" #include "tokenlist.h" #include "valueptr.h" #include "vfvalue.h" #include "vf_analyzers.h" #include "vf_bailout.h" #include "vf_common.h" #include <algorithm> #include <iterator> #include <list> #include <string> #include <utility> #include <vector> namespace ValueFlow { static const Token* findIncompleteVar(const Token* start, const Token* end) { for (const Token* tok = start; tok != end; tok = tok->next()) { if (tok->isIncompleteVar()) return tok; } return nullptr; } static std::vector<const Token*> getConditions(const Token* tok, const char* op) { std::vector<const Token*> conds = {tok}; if (tok->str() == op) { std::vector<const Token*> args = astFlatten(tok, op); std::copy_if(args.cbegin(), args.cend(), std::back_inserter(conds), [&](const Token* tok2) { if (tok2->exprId() == 0) return false; if (tok2->hasKnownIntValue()) return false; if (Token::Match(tok2, "%var%|.") && !astIsBool(tok2)) return false; return true; }); } return conds; } static Value makeConditionValue(long long val, const Token* condTok, bool assume, bool impossible, const Settings& settings, SourceLocation loc = SourceLocation::current()) { Value v(val); v.setKnown(); if (impossible) { v.intvalue = !v.intvalue; v.setImpossible(); } v.condition = condTok; if (assume) v.errorPath.emplace_back(condTok, "Assuming condition '" + condTok->expressionString() + "' is true"); else v.errorPath.emplace_back(condTok, "Assuming condition '" + condTok->expressionString() + "' is false"); if (settings.debugnormal) setSourceLocation(v, loc, condTok); return v; } static bool isEscapeScope(const Token* tok, const Settings& settings, bool unknown = false) { if (!Token::simpleMatch(tok, "{")) return false; // TODO this search for termTok in all subscopes. It should check the end of the scope. const Token * termTok = Token::findmatch(tok, "return|continue|break|throw|goto", tok->link()); if (termTok && termTok->scope() == tok->scope()) return true; std::string unknownFunction; if (settings.library.isScopeNoReturn(tok->link(), &unknownFunction)) return unknownFunction.empty() || unknown; return false; } void analyzeConditionExpressions(const TokenList &tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger &errorLogger, const Settings &settings) { if (!settings.daca && !settings.vfOptions.doConditionExpressionAnalysis) { if (settings.debugwarnings) { ErrorMessage::FileLocation loc(tokenlist.getSourceFilePath(), 0, 0); const ErrorMessage errmsg({std::move(loc)}, tokenlist.getSourceFilePath(), Severity::debug, "Analysis of condition expressions is disabled. Use --check-level=exhaustive to enable it.", "normalCheckLevelConditionExpressions", Certainty::normal); errorLogger.reportErr(errmsg); } return; } for (const Scope * scope : symboldatabase.functionScopes) { if (const Token* incompleteTok = findIncompleteVar(scope->bodyStart, scope->bodyEnd)) { if (settings.debugwarnings) bailoutIncompleteVar(tokenlist, errorLogger, incompleteTok, "Skipping function due to incomplete variable " + incompleteTok->str()); continue; } if (settings.daca && !settings.vfOptions.doConditionExpressionAnalysis) continue; for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::simpleMatch(tok, "if (")) continue; Token* parenTok = tok->next(); if (!Token::simpleMatch(parenTok->link(), ") {")) continue; Token * blockTok = parenTok->link()->tokAt(1); const Token* condTok = parenTok->astOperand2(); if (condTok->exprId() == 0) continue; if (condTok->hasKnownIntValue()) continue; if (!isConstExpression(condTok, settings.library)) continue; const bool isOp = condTok->isComparisonOp() || condTok->tokType() == Token::eLogicalOp; const bool is1 = isOp || astIsBool(condTok); Token* startTok = blockTok; // Inner condition { for (const Token* condTok2 : getConditions(condTok, "&&")) { if (is1) { const bool isBool = astIsBool(condTok2) || Token::Match(condTok2, "%comp%|%oror%|&&"); auto a1 = makeSameExpressionAnalyzer(condTok2, makeConditionValue(1, condTok2, /*assume*/ true, !isBool, settings), settings); // don't set '1' for non-boolean expressions valueFlowGenericForward(startTok, startTok->link(), a1, tokenlist, errorLogger, settings); } auto a2 = makeOppositeExpressionAnalyzer(true, condTok2, makeConditionValue(0, condTok2, true, false, settings), settings); valueFlowGenericForward(startTok, startTok->link(), a2, tokenlist, errorLogger, settings); } } std::vector<const Token*> conds = getConditions(condTok, "||"); // Check else block if (Token::simpleMatch(startTok->link(), "} else {")) { startTok = startTok->link()->tokAt(2); for (const Token* condTok2:conds) { auto a1 = makeSameExpressionAnalyzer(condTok2, makeConditionValue(0, condTok2, false, false, settings), settings); valueFlowGenericForward(startTok, startTok->link(), a1, tokenlist, errorLogger, settings); if (is1) { auto a2 = makeOppositeExpressionAnalyzer(true, condTok2, makeConditionValue(isOp, condTok2, false, false, settings), settings); valueFlowGenericForward(startTok, startTok->link(), a2, tokenlist, errorLogger, settings); } } } // Check if the block terminates early if (isEscapeScope(blockTok, settings)) { const Scope* scope2 = scope; // If escaping a loop then only use the loop scope if (isBreakOrContinueScope(blockTok->link())) { scope2 = getLoopScope(blockTok->link()); if (!scope2) continue; } for (const Token* condTok2:conds) { auto a1 = makeSameExpressionAnalyzer(condTok2, makeConditionValue(0, condTok2, false, false, settings), settings); valueFlowGenericForward(startTok->link()->next(), scope2->bodyEnd, a1, tokenlist, errorLogger, settings); if (is1) { auto a2 = makeOppositeExpressionAnalyzer(true, condTok2, makeConditionValue(1, condTok2, false, false, settings), settings); valueFlowGenericForward(startTok->link()->next(), scope2->bodyEnd, a2, tokenlist, errorLogger, settings); } } } } } } }
9,054
C++
.cpp
184
36.190217
260
0.573833
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,113
vf_functionreturn.cpp
danmar_cppcheck/lib/vf_functionreturn.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_functionreturn.h" #include "astutils.h" #include "programmemory.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_bailout.h" #include "vf_settokenvalue.h" #include <algorithm> #include <cstddef> #include <iterator> #include <list> #include <string> #include <utility> #include <vector> namespace ValueFlow { static const Value* getKnownValueFromToken(const Token* tok) { if (!tok) return nullptr; auto it = std::find_if(tok->values().begin(), tok->values().end(), [&](const Value& v) { return (v.isIntValue() || v.isContainerSizeValue() || v.isFloatValue()) && v.isKnown(); }); if (it == tok->values().end()) return nullptr; return std::addressof(*it); } static const Value* getKnownValueFromTokens(const std::vector<const Token*>& toks) { if (toks.empty()) return nullptr; const Value* result = getKnownValueFromToken(toks.front()); if (!result) return nullptr; if (!std::all_of(std::next(toks.begin()), toks.end(), [&](const Token* tok) { return std::any_of(tok->values().begin(), tok->values().end(), [&](const Value& v) { return v.equalValue(*result) && v.valueKind == result->valueKind; }); })) return nullptr; return result; } static void setFunctionReturnValue(const Function* f, Token* tok, Value v, const Settings& settings) { if (f->hasVirtualSpecifier()) { if (v.isImpossible()) return; v.setPossible(); } else if (!v.isImpossible()) { v.setKnown(); } v.errorPath.emplace_back(tok, "Calling function '" + f->name() + "' returns " + v.toString()); setTokenValue(tok, std::move(v), settings); } void analyzeFunctionReturn(TokenList &tokenlist, ErrorLogger &errorLogger, const Settings& settings) { for (Token *tok = tokenlist.back(); tok; tok = tok->previous()) { if (tok->str() != "(" || !tok->astOperand1() || tok->isCast()) continue; const Function* function = nullptr; if (Token::Match(tok->previous(), "%name% (")) function = tok->previous()->function(); else function = tok->astOperand1()->function(); if (!function) continue; // TODO: Check if member variable is a pointer or reference if (function->isImplicitlyVirtual() && !function->hasFinalSpecifier()) continue; if (tok->hasKnownValue()) continue; std::vector<const Token*> returns = Function::findReturns(function); if (returns.empty()) continue; if (const Value* v = getKnownValueFromTokens(returns)) { setFunctionReturnValue(function, tok, *v, settings); continue; } // Arguments.. std::vector<const Token*> arguments = getArguments(tok); ProgramMemory programMemory; for (std::size_t i = 0; i < arguments.size(); ++i) { const Variable * const arg = function->getArgumentVar(i); if (!arg) { if (settings.debugwarnings) bailout(tokenlist, errorLogger, tok, "function return; unhandled argument type"); programMemory.clear(); break; } const Value* v = getKnownValueFromToken(arguments[i]); if (!v) continue; programMemory.setValue(arg->nameToken(), *v); } if (programMemory.empty() && !arguments.empty()) continue; std::vector<Value> values = execute(function->functionScope, programMemory, settings); for (const Value& v : values) { if (v.isUninitValue()) continue; setFunctionReturnValue(function, tok, v, settings); } } } }
4,975
C++
.cpp
125
30.4
105
0.582506
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,114
token.cpp
danmar_cppcheck/lib/token.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "token.h" #include "astutils.h" #include "errortypes.h" #include "library.h" #include "settings.h" #include "simplecpp.h" #include "symboldatabase.h" #include "tokenlist.h" #include "utils.h" #include "tokenrange.h" #include "valueflow.h" #include <algorithm> #include <cassert> #include <cctype> #include <climits> #include <cstdio> #include <cstring> #include <functional> #include <iostream> #include <iterator> #include <map> #include <set> #include <sstream> #include <stack> #include <type_traits> #include <unordered_set> #include <utility> namespace { struct less { template<class T, class U> bool operator()(const T &x, const U &y) const { return x < y; } }; } const std::list<ValueFlow::Value> TokenImpl::mEmptyValueList; Token::Token(TokensFrontBack &tokensFrontBack) : mTokensFrontBack(tokensFrontBack) , mIsC(mTokensFrontBack.list.isC()) , mIsCpp(mTokensFrontBack.list.isCPP()) { mImpl = new TokenImpl(); } Token::Token(const Token* tok) : Token(const_cast<Token*>(tok)->mTokensFrontBack) { fileIndex(tok->fileIndex()); linenr(tok->linenr()); } Token::~Token() { delete mImpl; } /* * Get a TokenRange which starts at this token and contains every token following it in order up to but not including 't' * e.g. for the sequence of tokens A B C D E, C.until(E) would yield the Range C D * note t can be nullptr to iterate all the way to the end. */ // cppcheck-suppress unusedFunction // only used in testtokenrange.cpp ConstTokenRange Token::until(const Token* t) const { return ConstTokenRange(this, t); } static const std::unordered_set<std::string> controlFlowKeywords = { "goto", "do", "if", "else", "for", "while", "switch", "case", "break", "continue", "return" }; void Token::update_property_info() { setFlag(fIsControlFlowKeyword, controlFlowKeywords.find(mStr) != controlFlowKeywords.end()); isStandardType(false); if (!mStr.empty()) { if (mStr == "true" || mStr == "false") tokType(eBoolean); else if (isStringLiteral(mStr)) { tokType(eString); isLong(isPrefixStringCharLiteral(mStr, '"', "L")); } else if (isCharLiteral(mStr)) { tokType(eChar); isLong(isPrefixStringCharLiteral(mStr, '\'', "L")); } else if (std::isalpha((unsigned char)mStr[0]) || mStr[0] == '_' || mStr[0] == '$') { // Name if (mImpl->mVarId) tokType(eVariable); else if (mTokensFrontBack.list.isKeyword(mStr) || mStr == "asm") // TODO: not a keyword tokType(eKeyword); else if (mTokType != eVariable && mTokType != eFunction && mTokType != eType && mTokType != eKeyword) tokType(eName); } else if (simplecpp::Token::isNumberLike(mStr)) { if (MathLib::isInt(mStr) || MathLib::isFloat(mStr)) tokType(eNumber); else tokType(eName); // assume it is a user defined literal } else if (mStr == "=" || mStr == "<<=" || mStr == ">>=" || (mStr.size() == 2U && mStr[1] == '=' && std::strchr("+-*/%&^|", mStr[0]))) tokType(eAssignmentOp); else if (mStr.size() == 1 && mStr.find_first_of(",[]()?:") != std::string::npos) tokType(eExtendedOp); else if (mStr=="<<" || mStr==">>" || (mStr.size()==1 && mStr.find_first_of("+-*/%") != std::string::npos)) tokType(eArithmeticalOp); else if (mStr.size() == 1 && mStr.find_first_of("&|^~") != std::string::npos) tokType(eBitOp); else if (mStr.size() <= 2 && (mStr == "&&" || mStr == "||" || mStr == "!")) tokType(eLogicalOp); else if (mStr.size() <= 2 && !mLink && (mStr == "==" || mStr == "!=" || mStr == "<" || mStr == "<=" || mStr == ">" || mStr == ">=")) tokType(eComparisonOp); else if (mStr == "<=>") tokType(eComparisonOp); else if (mStr.size() == 2 && (mStr == "++" || mStr == "--")) tokType(eIncDecOp); else if (mStr.size() == 1 && (mStr.find_first_of("{}") != std::string::npos || (mLink && mStr.find_first_of("<>") != std::string::npos))) tokType(eBracket); else if (mStr == "...") tokType(eEllipsis); else tokType(eOther); update_property_isStandardType(); } else { tokType(eNone); } } static const std::unordered_set<std::string> stdTypes = { "bool" , "_Bool" , "char" , "double" , "float" , "int" , "long" , "short" , "size_t" , "void" , "wchar_t" }; void Token::update_property_isStandardType() { if (mStr.size() < 3 || mStr.size() > 7) return; if (stdTypes.find(mStr)!=stdTypes.end()) { isStandardType(true); tokType(eType); } } bool Token::isUpperCaseName() const { if (!isName()) return false; return std::none_of(mStr.begin(), mStr.end(), [](char c) { return std::islower(c); }); } void Token::concatStr(std::string const& b) { mStr.pop_back(); mStr.append(getStringLiteral(b) + "\""); if (isCChar() && isStringLiteral(b) && b[0] != '"') { mStr.insert(0, b.substr(0, b.find('"'))); } update_property_info(); } std::string Token::strValue() const { assert(mTokType == eString); std::string ret(getStringLiteral(mStr)); std::string::size_type pos = 0U; while ((pos = ret.find('\\', pos)) != std::string::npos) { ret.erase(pos,1U); if (ret[pos] >= 'a') { if (ret[pos] == 'n') ret[pos] = '\n'; else if (ret[pos] == 'r') ret[pos] = '\r'; else if (ret[pos] == 't') ret[pos] = '\t'; } if (ret[pos] == '0') return ret.substr(0,pos); pos++; } return ret; } void Token::deleteNext(nonneg int count) { while (mNext && count > 0) { Token *n = mNext; // #8154 we are about to be unknown -> destroy the link to us if (n->mLink && n->mLink->mLink == n) n->mLink->link(nullptr); mNext = n->next(); delete n; --count; } if (mNext) mNext->previous(this); else mTokensFrontBack.back = this; } void Token::deletePrevious(nonneg int count) { while (mPrevious && count > 0) { Token *p = mPrevious; // #8154 we are about to be unknown -> destroy the link to us if (p->mLink && p->mLink->mLink == p) p->mLink->link(nullptr); mPrevious = p->previous(); delete p; --count; } if (mPrevious) mPrevious->next(this); else mTokensFrontBack.front = this; } void Token::swapWithNext() { if (mNext) { std::swap(mStr, mNext->mStr); std::swap(mTokType, mNext->mTokType); std::swap(mFlags, mNext->mFlags); std::swap(mImpl, mNext->mImpl); if (mImpl->mTemplateSimplifierPointers) // cppcheck-suppress shadowFunction - TODO: fix this for (auto *templateSimplifierPointer : *mImpl->mTemplateSimplifierPointers) { templateSimplifierPointer->token(this); } if (mNext->mImpl->mTemplateSimplifierPointers) // cppcheck-suppress shadowFunction - TODO: fix this for (auto *templateSimplifierPointer : *mNext->mImpl->mTemplateSimplifierPointers) { templateSimplifierPointer->token(mNext); } if (mNext->mLink) mNext->mLink->mLink = this; if (this->mLink) this->mLink->mLink = mNext; std::swap(mLink, mNext->mLink); } } void Token::takeData(Token *fromToken) { mStr = fromToken->mStr; tokType(fromToken->mTokType); mFlags = fromToken->mFlags; delete mImpl; mImpl = fromToken->mImpl; fromToken->mImpl = nullptr; if (mImpl->mTemplateSimplifierPointers) // cppcheck-suppress shadowFunction - TODO: fix this for (auto *templateSimplifierPointer : *mImpl->mTemplateSimplifierPointers) { templateSimplifierPointer->token(this); } mLink = fromToken->mLink; if (mLink) mLink->link(this); } void Token::deleteThis() { if (mNext) { // Copy next to this and delete next takeData(mNext); mNext->link(nullptr); // mark as unlinked deleteNext(); } else if (mPrevious) { // Copy previous to this and delete previous takeData(mPrevious); mPrevious->link(nullptr); deletePrevious(); } else { // We are the last token in the list, we can't delete // ourselves, so just make us empty str(";"); } } void Token::replace(Token *replaceThis, Token *start, Token *end) { // Fix the whole in the old location of start and end if (start->previous()) start->previous()->next(end->next()); if (end->next()) end->next()->previous(start->previous()); // Move start and end to their new location if (replaceThis->previous()) replaceThis->previous()->next(start); if (replaceThis->next()) replaceThis->next()->previous(end); start->previous(replaceThis->previous()); end->next(replaceThis->next()); if (end->mTokensFrontBack.back == end) { while (end->next()) end = end->next(); end->mTokensFrontBack.back = end; } // Update mProgressValue, fileIndex and linenr for (Token *tok = start; tok != end->next(); tok = tok->next()) tok->mImpl->mProgressValue = replaceThis->mImpl->mProgressValue; // Delete old token, which is replaced delete replaceThis; } static #if defined(__GNUC__) // GCC does not inline this by itself // need to use the old syntax since the C++11 [[xxx:always_inline]] cannot be used here inline __attribute__((always_inline)) #endif int multiComparePercent(const Token *tok, const char*& haystack, nonneg int varid) { ++haystack; // Compare only the first character of the string for optimization reasons switch (haystack[0]) { case 'v': if (haystack[3] == '%') { // %var% haystack += 4; if (tok->varId() != 0) return 1; } else { // %varid% if (varid == 0) { throw InternalError(tok, "Internal error. Token::Match called with varid 0. Please report this to Cppcheck developers"); } haystack += 6; if (tok->varId() == varid) return 1; } break; case 't': // Type (%type%) { haystack += 5; if (tok->isName() && tok->varId() == 0) return 1; } break; case 'a': // Accept any token (%any%) or assign (%assign%) { if (haystack[3] == '%') { // %any% haystack += 4; return 1; } // %assign% haystack += 7; if (tok->isAssignmentOp()) return 1; } break; case 'n': // Number (%num%) or name (%name%) { if (haystack[4] == '%') { // %name% haystack += 5; if (tok->isName()) return 1; } else { haystack += 4; if (tok->isNumber()) return 1; } } break; case 'c': { haystack += 1; // Character (%char%) if (haystack[0] == 'h') { haystack += 4; if (tok->tokType() == Token::eChar) return 1; } // Const operator (%cop%) else if (haystack[1] == 'p') { haystack += 3; if (tok->isConstOp()) return 1; } // Comparison operator (%comp%) else { haystack += 4; if (tok->isComparisonOp()) return 1; } } break; case 's': // String (%str%) { haystack += 4; if (tok->tokType() == Token::eString) return 1; } break; case 'b': // Bool (%bool%) { haystack += 5; if (tok->isBoolean()) return 1; } break; case 'o': { ++haystack; if (haystack[1] == '%') { // Op (%op%) if (haystack[0] == 'p') { haystack += 2; if (tok->isOp()) return 1; } // Or (%or%) else { haystack += 2; if (tok->tokType() == Token::eBitOp && tok->str() == "|") return 1; } } // Oror (%oror%) else { haystack += 4; if (tok->tokType() == Token::eLogicalOp && tok->str() == "||") return 1; } } break; default: //unknown %cmd%, abort throw InternalError(tok, "Unexpected command"); } if (*haystack == '|') haystack += 1; else return -1; return 0xFFFF; } static #if defined(__GNUC__) // need to use the old syntax since the C++11 [[xxx:always_inline]] cannot be used here inline __attribute__((always_inline)) #endif int multiCompareImpl(const Token *tok, const char *haystack, nonneg int varid) { const char *needle = tok->str().c_str(); const char *needlePointer = needle; for (;;) { if (needlePointer == needle && haystack[0] == '%' && haystack[1] != '|' && haystack[1] != '\0' && haystack[1] != ' ') { const int ret = multiComparePercent(tok, haystack, varid); if (ret < 2) return ret; } else if (*haystack == '|') { if (*needlePointer == 0) { // If needle is at the end, we have a match. return 1; } needlePointer = needle; ++haystack; } else if (*needlePointer == *haystack) { if (*needlePointer == '\0') return 1; ++needlePointer; ++haystack; } else if (*haystack == ' ' || *haystack == '\0') { if (needlePointer == needle) return 0; break; } // If haystack and needle don't share the same character, // find next '|' character. else { needlePointer = needle; do { ++haystack; if (*haystack == ' ' || *haystack == '\0') { return -1; } if (*haystack == '|') { break; } } while (true); ++haystack; } } if (*needlePointer == '\0') return 1; return -1; } // cppcheck-suppress unusedFunction - used in tests only int Token::multiCompare(const Token *tok, const char *haystack, nonneg int varid) { return multiCompareImpl(tok, haystack, varid); } bool Token::simpleMatch(const Token *tok, const char pattern[], size_t pattern_len) { if (!tok) return false; // shortcut const char *current = pattern; const char *end = pattern + pattern_len; // cppcheck-suppress shadowFunction - TODO: fix this const char *next = static_cast<const char*>(std::memchr(pattern, ' ', pattern_len)); if (!next) next = end; while (*current) { const std::size_t length = next - current; if (!tok || length != tok->mStr.length() || std::strncmp(current, tok->mStr.c_str(), length) != 0) return false; current = next; if (*next) { next = std::strchr(++current, ' '); if (!next) next = end; } tok = tok->next(); } return true; } bool Token::firstWordEquals(const char *str, const char *word) { for (;;) { if (*str != *word) return (*str == ' ' && *word == 0); if (*str == 0) break; ++str; ++word; } return true; } const char *Token::chrInFirstWord(const char *str, char c) { for (;;) { if (*str == ' ' || *str == 0) return nullptr; if (*str == c) return str; ++str; } } bool Token::Match(const Token *tok, const char pattern[], nonneg int varid) { if (!(*pattern)) return true; const char *p = pattern; while (true) { // Skip spaces in pattern.. while (*p == ' ') ++p; // No token => Success! if (*p == '\0') break; if (!tok) { // If we have no tokens, pattern "!!else" should return true if (p[0] == '!' && p[1] == '!' && p[2] != '\0') { while (*p && *p != ' ') ++p; continue; } return false; } // [.. => search for a one-character token.. if (p[0] == '[' && chrInFirstWord(p, ']')) { if (tok->str().length() != 1) return false; const char *temp = p+1; bool chrFound = false; int count = 0; while (*temp && *temp != ' ') { if (*temp == ']') { ++count; } else if (*temp == tok->str()[0]) { chrFound = true; break; } ++temp; } if (count > 1 && tok->str()[0] == ']') chrFound = true; if (!chrFound) return false; p = temp; } // Parse "not" options. Token can be anything except the given one else if (p[0] == '!' && p[1] == '!' && p[2] != '\0') { p += 2; if (firstWordEquals(p, tok->str().c_str())) return false; } // Parse multi options, such as void|int|char (accept token which is one of these 3) else { const int res = multiCompareImpl(tok, p, varid); if (res == 0) { // Empty alternative matches, use the same token on next round while (*p && *p != ' ') ++p; continue; } if (res == -1) { // No match return false; } } // using strchr() for the other instances leads to a performance decrease if (!(p = strchr(p, ' '))) break; tok = tok->next(); } // The end of the pattern has been reached and nothing wrong has been found return true; } nonneg int Token::getStrLength(const Token *tok) { assert(tok != nullptr); assert(tok->mTokType == eString); const std::string s(replaceEscapeSequences(getStringLiteral(tok->str()))); const auto pos = s.find('\0'); return pos < s.size() ? pos : s.size(); } nonneg int Token::getStrArraySize(const Token *tok) { assert(tok != nullptr); assert(tok->tokType() == eString); // cppcheck-suppress shadowFunction - TODO: fix this const std::string str(getStringLiteral(tok->str())); int sizeofstring = 1; for (int i = 0; i < (int)str.size(); i++) { if (str[i] == '\\') ++i; ++sizeofstring; } return sizeofstring; } nonneg int Token::getStrSize(const Token *tok, const Settings &settings) { assert(tok != nullptr && tok->tokType() == eString); nonneg int sizeofType = 1; if (tok->valueType()) { ValueType vt(*tok->valueType()); vt.pointer = 0; sizeofType = ValueFlow::getSizeOf(vt, settings); } return getStrArraySize(tok) * sizeofType; } void Token::move(Token *srcStart, Token *srcEnd, Token *newLocation) { /**[newLocation] -> b -> c -> [srcStart] -> [srcEnd] -> f */ // Fix the gap, which tokens to be moved will leave srcStart->previous()->next(srcEnd->next()); srcEnd->next()->previous(srcStart->previous()); // Fix the tokens to be moved srcEnd->next(newLocation->next()); srcStart->previous(newLocation); // Fix the tokens at newLocation newLocation->next()->previous(srcEnd); newLocation->next(srcStart); // Update _progressValue for (Token *tok = srcStart; tok != srcEnd->next(); tok = tok->next()) tok->mImpl->mProgressValue = newLocation->mImpl->mProgressValue; } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* nextArgumentImpl(T *thisTok) { for (T* tok = thisTok; tok; tok = tok->next()) { if (tok->str() == ",") return tok->next(); if (tok->link() && Token::Match(tok, "(|{|[|<")) tok = tok->link(); else if (Token::Match(tok, ")|;")) return nullptr; } return nullptr; } const Token* Token::nextArgument() const { return nextArgumentImpl(this); } Token *Token::nextArgument() { return nextArgumentImpl(this); } const Token* Token::nextArgumentBeforeCreateLinks2() const { for (const Token* tok = this; tok; tok = tok->next()) { if (tok->str() == ",") return tok->next(); if (tok->link() && Token::Match(tok, "(|{|[")) tok = tok->link(); else if (tok->str() == "<") { const Token* temp = tok->findClosingBracket(); if (temp) tok = temp; } else if (Token::Match(tok, ")|;")) return nullptr; } return nullptr; } const Token* Token::nextTemplateArgument() const { for (const Token* tok = this; tok; tok = tok->next()) { if (tok->str() == ",") return tok->next(); if (tok->link() && Token::Match(tok, "(|{|[|<")) tok = tok->link(); else if (Token::Match(tok, ">|;")) return nullptr; } return nullptr; } static bool isOperator(const Token *tok) { if (tok->link()) tok = tok->link(); // TODO handle multi token operators return tok->strAt(-1) == "operator"; } const Token * Token::findClosingBracket() const { if (mStr != "<") return nullptr; if (!mPrevious) return nullptr; if (!(mPrevious->isName() || Token::simpleMatch(mPrevious, "]") || Token::Match(mPrevious->previous(), "operator %op% <") || Token::Match(mPrevious->tokAt(-2), "operator [([] [)]] <"))) return nullptr; const Token *closing = nullptr; const bool templateParameter(strAt(-1) == "template"); std::set<std::string> templateParameters; bool isDecl = true; for (const Token *prev = previous(); prev; prev = prev->previous()) { if (prev->str() == "=") isDecl = false; if (Token::simpleMatch(prev, "template <")) isDecl = true; if (Token::Match(prev, "[;{}]")) break; } unsigned int depth = 0; for (closing = this; closing != nullptr; closing = closing->next()) { if (Token::Match(closing, "{|[|(")) { closing = closing->link(); if (!closing) return nullptr; // #6803 } else if (Token::Match(closing, "}|]|)|;")) return nullptr; // we can make some guesses for template parameters else if (closing->str() == "<" && closing->previous() && (closing->previous()->isName() || Token::simpleMatch(closing->previous(), "]") || isOperator(closing->previous())) && (templateParameter ? templateParameters.find(closing->strAt(-1)) == templateParameters.end() : true)) ++depth; else if (closing->str() == ">") { if (--depth == 0) return closing; } else if (closing->str() == ">>" || closing->str() == ">>=") { if (!isDecl && depth == 1) continue; if (depth <= 2) return closing; depth -= 2; } // save named template parameter else if (templateParameter && depth == 1 && Token::Match(closing, "[,=]") && closing->previous()->isName() && !Token::Match(closing->previous(), "class|typename|.") && !Token::Match(closing->tokAt(-2), "=|::")) templateParameters.insert(closing->strAt(-1)); } return closing; } Token * Token::findClosingBracket() { // return value of const function return const_cast<Token*>(static_cast<const Token*>(this)->findClosingBracket()); } const Token * Token::findOpeningBracket() const { if (mStr != ">") return nullptr; const Token *opening = nullptr; unsigned int depth = 0; for (opening = this; opening != nullptr; opening = opening->previous()) { if (Token::Match(opening, "}|]|)")) { opening = opening->link(); if (!opening) return nullptr; } else if (Token::Match(opening, "{|{|(|;")) return nullptr; else if (opening->str() == ">") ++depth; else if (opening->str() == "<") { if (--depth == 0) return opening; } } return opening; } Token * Token::findOpeningBracket() { // return value of const function return const_cast<Token*>(static_cast<const Token*>(this)->findOpeningBracket()); } //--------------------------------------------------------------------------- template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T *findsimplematchImpl(T * const startTok, const char pattern[], size_t pattern_len) { for (T* tok = startTok; tok; tok = tok->next()) { if (Token::simpleMatch(tok, pattern, pattern_len)) return tok; } return nullptr; } const Token *Token::findsimplematch(const Token * const startTok, const char pattern[], size_t pattern_len) { return findsimplematchImpl(startTok, pattern, pattern_len); } Token *Token::findsimplematch(Token * const startTok, const char pattern[], size_t pattern_len) { return findsimplematchImpl(startTok, pattern, pattern_len); } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T *findsimplematchImpl(T * const startTok, const char pattern[], size_t pattern_len, const Token * const end) { for (T* tok = startTok; tok && tok != end; tok = tok->next()) { if (Token::simpleMatch(tok, pattern, pattern_len)) return tok; } return nullptr; } const Token *Token::findsimplematch(const Token * const startTok, const char pattern[], size_t pattern_len, const Token * const end) { return findsimplematchImpl(startTok, pattern, pattern_len, end); } Token *Token::findsimplematch(Token * const startTok, const char pattern[], size_t pattern_len, const Token * const end) { return findsimplematchImpl(startTok, pattern, pattern_len, end); } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T *findmatchImpl(T * const startTok, const char pattern[], const nonneg int varId) { for (T* tok = startTok; tok; tok = tok->next()) { if (Token::Match(tok, pattern, varId)) return tok; } return nullptr; } const Token *Token::findmatch(const Token * const startTok, const char pattern[], const nonneg int varId) { return findmatchImpl(startTok, pattern, varId); } Token *Token::findmatch(Token * const startTok, const char pattern[], const nonneg int varId) { return findmatchImpl(startTok, pattern, varId); } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T *findmatchImpl(T * const startTok, const char pattern[], const Token * const end, const nonneg int varId) { for (T* tok = startTok; tok && tok != end; tok = tok->next()) { if (Token::Match(tok, pattern, varId)) return tok; } return nullptr; } const Token *Token::findmatch(const Token * const startTok, const char pattern[], const Token * const end, const nonneg int varId) { return findmatchImpl(startTok, pattern, end, varId); } Token *Token::findmatch(Token * const startTok, const char pattern[], const Token * const end, const nonneg int varId) { return findmatchImpl(startTok, pattern, end, varId); } void Token::function(const Function *f) { mImpl->mFunction = f; if (f) { if (f->isLambda()) tokType(eLambda); else tokType(eFunction); } else if (mTokType == eFunction) tokType(eName); } Token* Token::insertToken(const std::string& tokenStr, const std::string& originalNameStr, const std::string& macroNameStr, bool prepend) { Token *newToken; if (mStr.empty()) newToken = this; else newToken = new Token(mTokensFrontBack); newToken->str(tokenStr); newToken->originalName(originalNameStr); newToken->setMacroName(macroNameStr); if (newToken != this) { newToken->mImpl->mLineNumber = mImpl->mLineNumber; newToken->mImpl->mFileIndex = mImpl->mFileIndex; newToken->mImpl->mProgressValue = mImpl->mProgressValue; if (prepend) { if (this->previous()) { newToken->previous(this->previous()); newToken->previous()->next(newToken); } else { mTokensFrontBack.front = newToken; } this->previous(newToken); newToken->next(this); } else { if (this->next()) { newToken->next(this->next()); newToken->next()->previous(newToken); } else { mTokensFrontBack.back = newToken; } this->next(newToken); newToken->previous(this); } if (mImpl->mScopeInfo) { // If the brace is immediately closed there is no point opening a new scope for it if (newToken->str() == "{") { std::string nextScopeNameAddition; // This might be the opening of a member function Token *tok1 = newToken; while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept")) tok1 = tok1->previous(); if (tok1->previous() && tok1->strAt(-1) == ")") { tok1 = tok1->linkAt(-1); if (Token::Match(tok1->previous(), "throw|noexcept")) { tok1 = tok1->previous(); while (Token::Match(tok1->previous(), "const|volatile|final|override|&|&&|noexcept")) tok1 = tok1->previous(); if (tok1->strAt(-1) != ")") return newToken; } else if (Token::Match(newToken->tokAt(-2), ":|, %name%")) { tok1 = tok1->tokAt(-2); if (tok1->strAt(-1) != ")") return newToken; } if (tok1->strAt(-1) == ">") tok1 = tok1->previous()->findOpeningBracket(); if (tok1 && Token::Match(tok1->tokAt(-3), "%name% :: %name%")) { tok1 = tok1->tokAt(-2); // cppcheck-suppress shadowFunction - TODO: fix this std::string scope = tok1->strAt(-1); while (Token::Match(tok1->tokAt(-2), ":: %name%")) { scope = tok1->strAt(-3) + " :: " + scope; tok1 = tok1->tokAt(-2); } nextScopeNameAddition += scope; } } // Or it might be a namespace/class/struct if (Token::Match(newToken->previous(), "%name%|>")) { Token* nameTok = newToken->previous(); while (nameTok && !Token::Match(nameTok, "namespace|class|struct|union %name% {|::|:|<")) { nameTok = nameTok->previous(); } if (nameTok) { for (nameTok = nameTok->next(); nameTok && !Token::Match(nameTok, "{|:|<"); nameTok = nameTok->next()) { nextScopeNameAddition.append(nameTok->str()); nextScopeNameAddition.append(" "); } if (!nextScopeNameAddition.empty()) nextScopeNameAddition.pop_back(); } } // New scope is opening, record it here std::shared_ptr<ScopeInfo2> newScopeInfo = std::make_shared<ScopeInfo2>(mImpl->mScopeInfo->name, nullptr, mImpl->mScopeInfo->usingNamespaces); if (!newScopeInfo->name.empty() && !nextScopeNameAddition.empty()) newScopeInfo->name.append(" :: "); newScopeInfo->name.append(nextScopeNameAddition); nextScopeNameAddition = ""; newToken->scopeInfo(std::move(newScopeInfo)); } else if (newToken->str() == "}") { Token* matchingTok = newToken->previous(); int depth = 0; while (matchingTok && (depth != 0 || !Token::simpleMatch(matchingTok, "{"))) { if (Token::simpleMatch(matchingTok, "}")) depth++; if (Token::simpleMatch(matchingTok, "{")) depth--; matchingTok = matchingTok->previous(); } if (matchingTok && matchingTok->previous()) { newToken->mImpl->mScopeInfo = matchingTok->previous()->scopeInfo(); } } else { if (prepend && newToken->previous()) { newToken->mImpl->mScopeInfo = newToken->previous()->scopeInfo(); } else { newToken->mImpl->mScopeInfo = mImpl->mScopeInfo; } if (newToken->str() == ";") { const Token* statementStart; for (statementStart = newToken; statementStart->previous() && !Token::Match(statementStart->previous(), ";|{"); statementStart = statementStart->previous()) {} if (Token::Match(statementStart, "using namespace %name% ::|;")) { const Token * tok1 = statementStart->tokAt(2); std::string nameSpace; while (tok1 && tok1->str() != ";") { if (!nameSpace.empty()) nameSpace += " "; nameSpace += tok1->str(); tok1 = tok1->next(); } mImpl->mScopeInfo->usingNamespaces.insert(nameSpace); } } } } } return newToken; } void Token::eraseTokens(Token *begin, const Token *end) { if (!begin || begin == end) return; while (begin->next() && begin->next() != end) { begin->deleteNext(); } } void Token::createMutualLinks(Token *begin, Token *end) { assert(begin != nullptr); assert(end != nullptr); assert(begin != end); begin->link(end); end->link(begin); } void Token::printOut() const { printOut(std::cout, ""); } void Token::printOut(std::ostream& out, const char *title) const { if (title && title[0]) out << "\n### " << title << " ###\n"; out << stringifyList(stringifyOptions::forPrintOut(), nullptr, nullptr) << std::endl; } void Token::printOut(std::ostream& out, const char *title, const std::vector<std::string> &fileNames) const { if (title && title[0]) out << "\n### " << title << " ###\n"; out << stringifyList(stringifyOptions::forPrintOut(), &fileNames, nullptr) << std::endl; } // cppcheck-suppress unusedFunction - used for debugging void Token::printLines(std::ostream& out, int lines) const { const Token *end = this; while (end && end->linenr() < lines + linenr()) end = end->next(); out << stringifyList(stringifyOptions::forDebugExprId(), nullptr, end) << std::endl; } std::string Token::stringify(const stringifyOptions& options) const { std::string ret; if (options.attributes) { if (isUnsigned()) ret += "unsigned "; else if (isSigned()) ret += "signed "; if (isComplex()) ret += "_Complex "; if (isLong()) { if (!(mTokType == eString || mTokType == eChar)) ret += "long "; } } if (options.macro && isExpandedMacro()) ret += '$'; if (isName() && mStr.find(' ') != std::string::npos) { for (const char i : mStr) { if (i != ' ') ret += i; } } else if (mStr[0] != '\"' || mStr.find('\0') == std::string::npos) ret += mStr; else { for (const char i : mStr) { if (i == '\0') ret += "\\0"; else ret += i; } } if (options.varid && mImpl->mVarId != 0) { ret += '@'; ret += (options.idtype ? "var" : ""); ret += std::to_string(mImpl->mVarId); } else if (options.exprid && mImpl->mExprId != 0) { ret += '@'; ret += (options.idtype ? "expr" : ""); if ((mImpl->mExprId & (1U << efIsUnique)) != 0) ret += "UNIQUE"; else ret += std::to_string(mImpl->mExprId); } return ret; } std::string Token::stringify(bool varid, bool attributes, bool macro) const { stringifyOptions options; options.varid = varid; options.attributes = attributes; options.macro = macro; return stringify(options); } std::string Token::stringifyList(const stringifyOptions& options, const std::vector<std::string>* fileNames, const Token* end) const { if (this == end) return ""; std::string ret; unsigned int lineNumber = mImpl->mLineNumber - (options.linenumbers ? 1U : 0U); // cppcheck-suppress shadowFunction - TODO: fix this unsigned int fileIndex = options.files ? ~0U : mImpl->mFileIndex; std::map<int, unsigned int> lineNumbers; for (const Token *tok = this; tok != end; tok = tok->next()) { assert(tok && "end precedes token"); if (!tok) return ret; bool fileChange = false; if (tok->mImpl->mFileIndex != fileIndex) { if (fileIndex != ~0U) { lineNumbers[fileIndex] = tok->mImpl->mFileIndex; } fileIndex = tok->mImpl->mFileIndex; if (options.files) { ret += "\n\n##file "; if (fileNames && fileNames->size() > tok->mImpl->mFileIndex) ret += fileNames->at(tok->mImpl->mFileIndex); else ret += std::to_string(fileIndex); ret += '\n'; } lineNumber = lineNumbers[fileIndex]; fileChange = true; } if (options.linebreaks && (lineNumber != tok->linenr() || fileChange)) { if (lineNumber+4 < tok->linenr() && fileIndex == tok->mImpl->mFileIndex) { ret += '\n'; ret += std::to_string(lineNumber+1); ret += ":\n|\n"; ret += std::to_string(tok->linenr()-1); ret += ":\n"; ret += std::to_string(tok->linenr()); ret += ": "; } else if (this == tok && options.linenumbers) { ret += std::to_string(tok->linenr()); ret += ": "; } else if (lineNumber > tok->linenr()) { lineNumber = tok->linenr(); ret += '\n'; if (options.linenumbers) { ret += std::to_string(lineNumber); ret += ':'; ret += ' '; } } else { while (lineNumber < tok->linenr()) { ++lineNumber; ret += '\n'; if (options.linenumbers) { ret += std::to_string(lineNumber); ret += ':'; if (lineNumber == tok->linenr()) ret += ' '; } } } lineNumber = tok->linenr(); } ret += tok->stringify(options); // print token if (tok->next() != end && (!options.linebreaks || (tok->next()->linenr() == tok->linenr() && tok->next()->fileIndex() == tok->fileIndex()))) ret += ' '; } if (options.linebreaks && (options.files || options.linenumbers)) ret += '\n'; return ret; } std::string Token::stringifyList(bool varid, bool attributes, bool linenumbers, bool linebreaks, bool files, const std::vector<std::string>* fileNames, const Token* end) const { stringifyOptions options; options.varid = varid; options.attributes = attributes; options.macro = attributes; options.linenumbers = linenumbers; options.linebreaks = linebreaks; options.files = files; return stringifyList(options, fileNames, end); } std::string Token::stringifyList(const Token* end, bool attributes) const { return stringifyList(false, attributes, false, false, false, nullptr, end); } std::string Token::stringifyList(bool varid) const { return stringifyList(varid, false, true, true, true, nullptr, nullptr); } void Token::astParent(Token* tok) { const Token* tok2 = tok; while (tok2) { if (this == tok2) throw InternalError(this, "Internal error. AST cyclic dependency."); tok2 = tok2->astParent(); } // Clear children to avoid nodes referenced twice if (this->astParent()) { Token* parent = this->astParent(); if (parent->astOperand1() == this) parent->mImpl->mAstOperand1 = nullptr; if (parent->astOperand2() == this) parent->mImpl->mAstOperand2 = nullptr; } mImpl->mAstParent = tok; } void Token::astOperand1(Token *tok) { if (mImpl->mAstOperand1) mImpl->mAstOperand1->astParent(nullptr); // goto parent operator if (tok) { tok = tok->astTop(); tok->astParent(this); } mImpl->mAstOperand1 = tok; } void Token::astOperand2(Token *tok) { if (mImpl->mAstOperand2) mImpl->mAstOperand2->astParent(nullptr); // goto parent operator if (tok) { tok = tok->astTop(); tok->astParent(this); } mImpl->mAstOperand2 = tok; } static const Token* goToLeftParenthesis(const Token* start, const Token* end) { // move start to lpar in such expression: '(*it).x' int par = 0; for (const Token *tok = start; tok && tok != end; tok = tok->next()) { if (tok->str() == "(") ++par; else if (tok->str() == ")") { if (par == 0) start = tok->link(); else --par; } } return start; } static const Token* goToRightParenthesis(const Token* start, const Token* end) { // move end to rpar in such expression: '2>(x+1)' int par = 0; for (const Token *tok = end; tok && tok != start; tok = tok->previous()) { if (tok->str() == ")") ++par; else if (tok->str() == "(") { if (par == 0) end = tok->link(); else --par; } } return end; } std::pair<const Token *, const Token *> Token::findExpressionStartEndTokens() const { const Token * const top = this; // find start node in AST tree const Token *start = top; while (start->astOperand1() && precedes(start->astOperand1(), start)) start = start->astOperand1(); // find end node in AST tree const Token *end = top; while (end->astOperand1() && (end->astOperand2() || end->isUnaryPreOp())) { // lambda.. if (end->str() == "[") { const Token *lambdaEnd = findLambdaEndToken(end); if (lambdaEnd) { end = lambdaEnd; break; } } if (Token::Match(end,"(|[|{") && !(Token::Match(end, "( ::| %type%") && !end->astOperand2())) { end = end->link(); break; } end = end->astOperand2() ? end->astOperand2() : end->astOperand1(); } // skip parentheses start = goToLeftParenthesis(start, end); end = goToRightParenthesis(start, end); if (Token::simpleMatch(end, "{")) end = end->link(); if (precedes(top, start)) throw InternalError(start, "Cannot find start of expression"); if (succeeds(top, end)) throw InternalError(end, "Cannot find end of expression"); return std::pair<const Token *, const Token *>(start,end); } bool Token::isCalculation() const { if (!Token::Match(this, "%cop%|++|--")) return false; if (Token::Match(this, "*|&")) { // dereference or address-of? if (!this->astOperand2()) return false; if (this->astOperand2()->str() == "[") return false; // type specification? std::stack<const Token *> operands; operands.push(this); while (!operands.empty()) { const Token *op = operands.top(); operands.pop(); if (op->isNumber() || op->varId() > 0) return true; if (op->astOperand1()) operands.push(op->astOperand1()); if (op->astOperand2()) operands.push(op->astOperand2()); else if (Token::Match(op, "*|&")) return false; } // type specification => return false return false; } return true; } bool Token::isUnaryPreOp() const { if (!astOperand1() || astOperand2()) return false; if (this->tokType() != Token::eIncDecOp) return true; const Token *tokbefore = mPrevious; const Token *tokafter = mNext; for (int distance = 1; distance < 10 && tokbefore; distance++) { if (tokbefore == mImpl->mAstOperand1) return false; if (tokafter == mImpl->mAstOperand1) return true; tokbefore = tokbefore->mPrevious; tokafter = tokafter->mPrevious; } return false; // <- guess } static std::string stringFromTokenRange(const Token* start, const Token* end) { std::string ret; if (end) end = end->next(); for (const Token *tok = start; tok && tok != end; tok = tok->next()) { if (tok->isUnsigned()) ret += "unsigned "; if (tok->isLong() && !tok->isLiteral()) ret += "long "; if (tok->tokType() == Token::eString) { for (const unsigned char c: tok->str()) { if (c == '\n') ret += "\\n"; else if (c == '\r') ret += "\\r"; else if (c == '\t') ret += "\\t"; else if (c >= ' ' && c <= 126) ret += c; else { char str[10]; sprintf(str, "\\x%02x", c); ret += str; } } } else if (tok->originalName().empty() || tok->isUnsigned() || tok->isLong()) { ret += tok->str(); } else ret += tok->originalName(); if (Token::Match(tok, "%name%|%num% %name%|%num%")) ret += ' '; } return ret; } std::string Token::expressionString() const { const auto tokens = findExpressionStartEndTokens(); return stringFromTokenRange(tokens.first, tokens.second); } static void astStringXml(const Token *tok, nonneg int indent, std::ostream &out) { const std::string strindent(indent, ' '); out << strindent << "<token str=\"" << tok->str() << '\"'; if (tok->varId()) out << " varId=\"" << tok->varId() << '\"'; if (tok->variable()) out << " variable=\"" << tok->variable() << '\"'; if (tok->function()) out << " function=\"" << tok->function() << '\"'; if (!tok->values().empty()) out << " values=\"" << &tok->values() << '\"'; if (!tok->astOperand1() && !tok->astOperand2()) { out << "/>" << std::endl; } else { out << '>' << std::endl; if (tok->astOperand1()) astStringXml(tok->astOperand1(), indent+2U, out); if (tok->astOperand2()) astStringXml(tok->astOperand2(), indent+2U, out); out << strindent << "</token>" << std::endl; } } void Token::printAst(bool verbose, bool xml, const std::vector<std::string> &fileNames, std::ostream &out) const { if (!xml) out << "\n\n##AST" << std::endl; std::set<const Token *> printed; for (const Token *tok = this; tok; tok = tok->next()) { if (!tok->mImpl->mAstParent && tok->mImpl->mAstOperand1) { if (printed.find(tok) != printed.end()) continue; printed.insert(tok); if (xml) { out << "<ast scope=\"" << tok->scope() << "\" fileIndex=\"" << tok->fileIndex() << "\" linenr=\"" << tok->linenr() << "\" column=\"" << tok->column() << "\">" << std::endl; astStringXml(tok, 2U, out); out << "</ast>" << std::endl; } else if (verbose) out << "[" << fileNames[tok->fileIndex()] << ":" << tok->linenr() << "]" << std::endl << tok->astStringVerbose() << std::endl; else out << tok->astString(" ") << std::endl; if (tok->str() == "(") tok = tok->link(); } } } static void indent(std::string &str, const nonneg int indent1, const nonneg int indent2) { for (int i = 0; i < indent1; ++i) str += ' '; for (int i = indent1; i < indent2; i += 2) str += "| "; } void Token::astStringVerboseRecursive(std::string& ret, const nonneg int indent1, const nonneg int indent2) const { if (isExpandedMacro()) ret += '$'; ret += mStr; if (mImpl->mValueType) ret += " \'" + mImpl->mValueType->str() + '\''; if (function()) { std::ostringstream ostr; ostr << std::hex << function(); ret += " f:" + ostr.str(); } ret += '\n'; if (mImpl->mAstOperand1) { int i1 = indent1, i2 = indent2 + 2; if (indent1 == indent2 && !mImpl->mAstOperand2) i1 += 2; indent(ret, indent1, indent2); ret += mImpl->mAstOperand2 ? "|-" : "`-"; mImpl->mAstOperand1->astStringVerboseRecursive(ret, i1, i2); } if (mImpl->mAstOperand2) { int i1 = indent1, i2 = indent2 + 2; if (indent1 == indent2) i1 += 2; indent(ret, indent1, indent2); ret += "`-"; mImpl->mAstOperand2->astStringVerboseRecursive(ret, i1, i2); } } std::string Token::astStringVerbose() const { std::string ret; astStringVerboseRecursive(ret); return ret; } // cppcheck-suppress unusedFunction // used in test std::string Token::astStringZ3() const { if (!astOperand1()) return str(); if (!astOperand2()) return "(" + str() + " " + astOperand1()->astStringZ3() + ")"; return "(" + str() + " " + astOperand1()->astStringZ3() + " " + astOperand2()->astStringZ3() + ")"; } void Token::printValueFlow(bool xml, std::ostream &out) const { std::string outs; // cppcheck-suppress shadowFunction int fileIndex = -1; int line = 0; if (xml) outs += " <valueflow>\n"; else outs += "\n\n##Value flow\n"; for (const Token *tok = this; tok; tok = tok->next()) { // cppcheck-suppress shadowFunction - TODO: fix this const auto* const values = tok->mImpl->mValues; if (!values) continue; if (values->empty()) // Values might be removed by removeContradictions continue; if (xml) { outs += " <values id=\""; outs += id_string(values); outs += "\">"; outs += '\n'; } else { if (fileIndex != tok->fileIndex()) { outs += "File "; outs += tok->mTokensFrontBack.list.getFiles()[tok->fileIndex()]; outs += '\n'; line = 0; } if (line != tok->linenr()) { outs += "Line "; outs += std::to_string(tok->linenr()); outs += '\n'; } } fileIndex = tok->fileIndex(); line = tok->linenr(); if (!xml) { ValueFlow::Value::ValueKind valueKind = values->front().valueKind; const bool same = std::all_of(values->begin(), values->end(), [&](const ValueFlow::Value& value) { return value.valueKind == valueKind; }); outs += " "; outs += tok->str(); outs += " "; if (same) { switch (valueKind) { case ValueFlow::Value::ValueKind::Impossible: case ValueFlow::Value::ValueKind::Known: outs += "always "; break; case ValueFlow::Value::ValueKind::Inconclusive: outs += "inconclusive "; break; case ValueFlow::Value::ValueKind::Possible: outs += "possible "; break; } } if (values->size() > 1U) outs += '{'; } for (const ValueFlow::Value& value : *values) { if (xml) { outs += " <value "; switch (value.valueType) { case ValueFlow::Value::ValueType::INT: if (tok->valueType() && tok->valueType()->sign == ValueType::UNSIGNED) { outs += "intvalue=\""; outs += std::to_string(static_cast<MathLib::biguint>(value.intvalue)); outs += '\"'; } else { outs += "intvalue=\""; outs += std::to_string(value.intvalue); outs += '\"'; } break; case ValueFlow::Value::ValueType::TOK: outs += "tokvalue=\""; outs += id_string(value.tokvalue); outs += '\"'; break; case ValueFlow::Value::ValueType::FLOAT: outs += "floatvalue=\""; outs += std::to_string(value.floatValue); // TODO: should this be MathLib::toString()? outs += '\"'; break; case ValueFlow::Value::ValueType::MOVED: outs += "movedvalue=\""; outs += ValueFlow::Value::toString(value.moveKind); outs += '\"'; break; case ValueFlow::Value::ValueType::UNINIT: outs += "uninit=\"1\""; break; case ValueFlow::Value::ValueType::BUFFER_SIZE: outs += "buffer-size=\""; outs += std::to_string(value.intvalue); outs += "\""; break; case ValueFlow::Value::ValueType::CONTAINER_SIZE: outs += "container-size=\""; outs += std::to_string(value.intvalue); outs += '\"'; break; case ValueFlow::Value::ValueType::ITERATOR_START: outs += "iterator-start=\""; outs += std::to_string(value.intvalue); outs += '\"'; break; case ValueFlow::Value::ValueType::ITERATOR_END: outs += "iterator-end=\""; outs += std::to_string(value.intvalue); outs += '\"'; break; case ValueFlow::Value::ValueType::LIFETIME: outs += "lifetime=\""; outs += id_string(value.tokvalue); outs += '\"'; outs += " lifetime-scope=\""; outs += ValueFlow::Value::toString(value.lifetimeScope); outs += "\""; outs += " lifetime-kind=\""; outs += ValueFlow::Value::toString(value.lifetimeKind); outs += "\""; break; case ValueFlow::Value::ValueType::SYMBOLIC: outs += "symbolic=\""; outs += id_string(value.tokvalue); outs += '\"'; outs += " symbolic-delta=\""; outs += std::to_string(value.intvalue); outs += '\"'; break; } outs += " bound=\""; outs += ValueFlow::Value::toString(value.bound); outs += "\""; if (value.condition) { outs += " condition-line=\""; outs += std::to_string(value.condition->linenr()); outs += '\"'; } if (value.isKnown()) outs += " known=\"true\""; else if (value.isPossible()) outs += " possible=\"true\""; else if (value.isImpossible()) outs += " impossible=\"true\""; else if (value.isInconclusive()) outs += " inconclusive=\"true\""; outs += " path=\""; outs += std::to_string(value.path); outs += "\""; outs += "/>\n"; } else { if (&value != &values->front()) outs += ","; outs += value.toString(); } } if (xml) outs += " </values>\n"; else if (values->size() > 1U) outs += "}\n"; else outs += '\n'; } if (xml) outs += " </valueflow>\n"; out << outs; } const ValueFlow::Value * Token::getValueLE(const MathLib::bigint val, const Settings &settings) const { if (!mImpl->mValues) return nullptr; return ValueFlow::findValue(*mImpl->mValues, settings, [&](const ValueFlow::Value& v) { return !v.isImpossible() && v.isIntValue() && v.intvalue <= val; }); } const ValueFlow::Value * Token::getValueGE(const MathLib::bigint val, const Settings &settings) const { if (!mImpl->mValues) return nullptr; return ValueFlow::findValue(*mImpl->mValues, settings, [&](const ValueFlow::Value& v) { return !v.isImpossible() && v.isIntValue() && v.intvalue >= val; }); } const ValueFlow::Value * Token::getInvalidValue(const Token *ftok, nonneg int argnr, const Settings &settings) const { if (!mImpl->mValues) return nullptr; const ValueFlow::Value *ret = nullptr; for (std::list<ValueFlow::Value>::const_iterator it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) { if (it->isImpossible()) continue; if ((it->isIntValue() && !settings.library.isIntArgValid(ftok, argnr, it->intvalue)) || (it->isFloatValue() && !settings.library.isFloatArgValid(ftok, argnr, it->floatValue))) { if (!ret || ret->isInconclusive() || (ret->condition && !it->isInconclusive())) ret = &(*it); if (!ret->isInconclusive() && !ret->condition) break; } } if (ret) { if (ret->isInconclusive() && !settings.certainty.isEnabled(Certainty::inconclusive)) return nullptr; if (ret->condition && !settings.severity.isEnabled(Severity::warning)) return nullptr; } return ret; } const Token *Token::getValueTokenMinStrSize(const Settings &settings, MathLib::bigint* path) const { if (!mImpl->mValues) return nullptr; const Token *ret = nullptr; int minsize = INT_MAX; for (std::list<ValueFlow::Value>::const_iterator it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) { if (it->isTokValue() && it->tokvalue && it->tokvalue->tokType() == Token::eString) { const int size = getStrSize(it->tokvalue, settings); if (!ret || size < minsize) { minsize = size; ret = it->tokvalue; if (path) *path = it->path; } } } return ret; } const Token *Token::getValueTokenMaxStrLength() const { if (!mImpl->mValues) return nullptr; const Token *ret = nullptr; int maxlength = 0; for (std::list<ValueFlow::Value>::const_iterator it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) { if (it->isTokValue() && it->tokvalue && it->tokvalue->tokType() == Token::eString) { const int length = getStrLength(it->tokvalue); if (!ret || length > maxlength) { maxlength = length; ret = it->tokvalue; } } } return ret; } static bool isAdjacent(const ValueFlow::Value& x, const ValueFlow::Value& y) { if (x.bound != ValueFlow::Value::Bound::Point && x.bound == y.bound) return true; if (x.valueType == ValueFlow::Value::ValueType::FLOAT) return false; return std::abs(x.intvalue - y.intvalue) == 1; } static bool removePointValue(std::list<ValueFlow::Value>& values, std::list<ValueFlow::Value>::iterator& x) { const bool isPoint = x->bound == ValueFlow::Value::Bound::Point; if (!isPoint) x->decreaseRange(); else x = values.erase(x); return isPoint; } static bool removeContradiction(std::list<ValueFlow::Value>& values) { bool result = false; for (auto itx = values.begin(); itx != values.end(); ++itx) { if (itx->isNonValue()) continue; auto ity = itx; ++ity; for (; ity != values.end(); ++ity) { if (ity->isNonValue()) continue; if (*itx == *ity) continue; if (itx->valueType != ity->valueType) continue; if (itx->isImpossible() == ity->isImpossible()) continue; if (itx->isSymbolicValue() && !ValueFlow::Value::sameToken(itx->tokvalue, ity->tokvalue)) continue; if (!itx->equalValue(*ity)) { auto compare = [](const std::list<ValueFlow::Value>::const_iterator& x, const std::list<ValueFlow::Value>::const_iterator& y) { return x->compareValue(*y, less{}); }; auto itMax = std::max(itx, ity, compare); auto itMin = std::min(itx, ity, compare); // TODO: Adjust non-points instead of removing them if (itMax->isImpossible() && itMax->bound == ValueFlow::Value::Bound::Upper) { values.erase(itMin); return true; } if (itMin->isImpossible() && itMin->bound == ValueFlow::Value::Bound::Lower) { values.erase(itMax); return true; } continue; } const bool removex = !itx->isImpossible() || ity->isKnown(); const bool removey = !ity->isImpossible() || itx->isKnown(); if (itx->bound == ity->bound) { if (removex) values.erase(itx); if (removey) values.erase(ity); // itx and ity are invalidated return true; } result = removex || removey; bool bail = false; if (removex && removePointValue(values, itx)) bail = true; if (removey && removePointValue(values, ity)) bail = true; if (bail) return true; } } return result; } using ValueIterator = std::list<ValueFlow::Value>::iterator; template<class Iterator> // NOLINTNEXTLINE(performance-unnecessary-value-param) - false positive static ValueIterator removeAdjacentValues(std::list<ValueFlow::Value>& values, ValueIterator x, Iterator start, Iterator last) { if (!isAdjacent(*x, **start)) return std::next(x); auto it = std::adjacent_find(start, last, [](ValueIterator x, ValueIterator y) { return !isAdjacent(*x, *y); }); if (it == last) it--; (*it)->bound = x->bound; std::for_each(std::move(start), std::move(it), [&](ValueIterator y) { values.erase(y); }); return values.erase(x); } static void mergeAdjacent(std::list<ValueFlow::Value>& values) { for (auto x = values.begin(); x != values.end();) { if (x->isNonValue()) { x++; continue; } if (x->bound == ValueFlow::Value::Bound::Point) { x++; continue; } std::vector<ValueIterator> adjValues; for (auto y = values.begin(); y != values.end(); y++) { if (x == y) continue; if (y->isNonValue()) continue; if (x->valueType != y->valueType) continue; if (x->valueKind != y->valueKind) continue; if (x->isSymbolicValue() && !ValueFlow::Value::sameToken(x->tokvalue, y->tokvalue)) continue; if (x->bound != y->bound) { if (y->bound != ValueFlow::Value::Bound::Point && isAdjacent(*x, *y)) { adjValues.clear(); break; } // No adjacent points for floating points if (x->valueType == ValueFlow::Value::ValueType::FLOAT) continue; if (y->bound != ValueFlow::Value::Bound::Point) continue; } if (x->bound == ValueFlow::Value::Bound::Lower && !y->compareValue(*x, less{})) continue; if (x->bound == ValueFlow::Value::Bound::Upper && !x->compareValue(*y, less{})) continue; adjValues.push_back(y); } if (adjValues.empty()) { x++; continue; } std::sort(adjValues.begin(), adjValues.end(), [&values](ValueIterator xx, ValueIterator yy) { (void)values; assert(xx != values.end() && yy != values.end()); return xx->compareValue(*yy, less{}); }); if (x->bound == ValueFlow::Value::Bound::Lower) x = removeAdjacentValues(values, x, adjValues.rbegin(), adjValues.rend()); else if (x->bound == ValueFlow::Value::Bound::Upper) x = removeAdjacentValues(values, x, adjValues.begin(), adjValues.end()); } } static void removeOverlaps(std::list<ValueFlow::Value>& values) { for (const ValueFlow::Value& x : values) { if (x.isNonValue()) continue; values.remove_if([&](const ValueFlow::Value& y) { if (y.isNonValue()) return false; if (&x == &y) return false; if (x.valueType != y.valueType) return false; if (x.valueKind != y.valueKind) return false; // TODO: Remove points covered in a lower or upper bound // TODO: Remove lower or upper bound already covered by a lower and upper bound if (!x.equalValue(y)) return false; if (x.bound != y.bound) return false; return true; }); } mergeAdjacent(values); } // Removing contradictions is an NP-hard problem. Instead we run multiple // passes to try to catch most contradictions static void removeContradictions(std::list<ValueFlow::Value>& values) { removeOverlaps(values); for (int i = 0; i < 4; i++) { if (!removeContradiction(values)) return; removeOverlaps(values); } } static bool sameValueType(const ValueFlow::Value& x, const ValueFlow::Value& y) { if (x.valueType != y.valueType) return false; // Symbolic are the same type if they share the same tokvalue if (x.isSymbolicValue()) return x.tokvalue->exprId() == 0 || x.tokvalue->exprId() == y.tokvalue->exprId(); return true; } bool Token::addValue(const ValueFlow::Value &value) { if (value.isKnown() && mImpl->mValues) { // Clear all other values of the same type since value is known mImpl->mValues->remove_if([&](const ValueFlow::Value& x) { return sameValueType(x, value); }); } // Don't add a value if its already known if (!value.isKnown() && mImpl->mValues && std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& x) { return x.isKnown() && sameValueType(x, value) && !x.equalValue(value); })) return false; // assert(value.isKnown() || !mImpl->mValues || std::none_of(mImpl->mValues->begin(), mImpl->mValues->end(), // [&](const ValueFlow::Value& x) { // return x.isKnown() && sameValueType(x, value); // })); if (mImpl->mValues) { // Don't handle more than 10 values for performance reasons // TODO: add setting? if (mImpl->mValues->size() >= 10U) return false; // if value already exists, don't add it again std::list<ValueFlow::Value>::iterator it; for (it = mImpl->mValues->begin(); it != mImpl->mValues->end(); ++it) { // different types => continue if (it->valueType != value.valueType) continue; if (it->isImpossible() != value.isImpossible()) continue; // different value => continue if (!it->equalValue(value)) continue; if ((value.isTokValue() || value.isLifetimeValue()) && (it->tokvalue != value.tokvalue) && (it->tokvalue->str() != value.tokvalue->str())) continue; // same value, but old value is inconclusive so replace it if (it->isInconclusive() && !value.isInconclusive() && !value.isImpossible()) { *it = value; if (it->varId == 0) it->varId = mImpl->mVarId; break; } // Same value already exists, don't add new value return false; } // Add value if (it == mImpl->mValues->end()) { ValueFlow::Value v(value); if (v.varId == 0) v.varId = mImpl->mVarId; if (v.isKnown() && v.isIntValue()) mImpl->mValues->push_front(std::move(v)); else mImpl->mValues->push_back(std::move(v)); } } else { ValueFlow::Value v(value); if (v.varId == 0) v.varId = mImpl->mVarId; mImpl->mValues = new std::list<ValueFlow::Value>; mImpl->mValues->push_back(std::move(v)); } removeContradictions(*mImpl->mValues); return true; } void Token::assignProgressValues(Token *tok) { int total_count = 0; for (Token *tok2 = tok; tok2; tok2 = tok2->next()) ++total_count; int count = 0; for (Token *tok2 = tok; tok2; tok2 = tok2->next()) tok2->mImpl->mProgressValue = count++ *100 / total_count; } void Token::assignIndexes() { // cppcheck-suppress shadowFunction - TODO: fix this int index = (mPrevious ? mPrevious->mImpl->mIndex : 0) + 1; for (Token *tok = this; tok; tok = tok->next()) tok->mImpl->mIndex = index++; } void Token::setValueType(ValueType *vt) { if (vt != mImpl->mValueType) { delete mImpl->mValueType; mImpl->mValueType = vt; } } const ValueType *Token::argumentType() const { const Token *top = this; while (top && !Token::Match(top->astParent(), ",|(")) top = top->astParent(); return top ? top->mImpl->mValueType : nullptr; } void Token::type(const ::Type *t) { mImpl->mType = t; if (t) { tokType(eType); isEnumType(mImpl->mType->isEnumType()); } else if (mTokType == eType) tokType(eName); } const ::Type* Token::typeOf(const Token* tok, const Token** typeTok) { if (!tok) return nullptr; if (typeTok != nullptr) *typeTok = tok; const Token* lhsVarTok{}; if (tok->type()) return tok->type(); if (tok->variable()) return tok->variable()->type(); if (tok->function()) return tok->function()->retType; if (Token::simpleMatch(tok, "return")) { // cppcheck-suppress shadowFunction - TODO: fix this const Scope *scope = tok->scope(); if (!scope) return nullptr; // cppcheck-suppress shadowFunction - TODO: fix this const Function *function = scope->function; if (!function) return nullptr; return function->retType; } if (Token::Match(tok->previous(), "%type%|= (|{")) return typeOf(tok->previous(), typeTok); if (Token::simpleMatch(tok, "=") && (lhsVarTok = getLHSVariableToken(tok)) != tok->next()) return Token::typeOf(lhsVarTok, typeTok); if (Token::simpleMatch(tok, ".")) return Token::typeOf(tok->astOperand2(), typeTok); if (Token::simpleMatch(tok, "[")) return Token::typeOf(tok->astOperand1(), typeTok); if (Token::simpleMatch(tok, "{")) { int argnr; const Token* ftok = getTokenArgumentFunction(tok, argnr); if (argnr < 0) return nullptr; if (!ftok) return nullptr; if (ftok == tok) return nullptr; std::vector<const Variable*> vars = getArgumentVars(ftok, argnr); if (vars.empty()) return nullptr; if (std::all_of( vars.cbegin(), vars.cend(), [&](const Variable* var) { return var->type() == vars.front()->type(); })) return vars.front()->type(); } return nullptr; } std::pair<const Token*, const Token*> Token::typeDecl(const Token* tok, bool pointedToType) { if (!tok) return {}; if (tok->type()) return {tok, tok->next()}; if (tok->variable()) { const Variable *var = tok->variable(); if (!var->typeStartToken() || !var->typeEndToken()) return {}; if (pointedToType && astIsSmartPointer(var->nameToken())) { const ValueType* vt = var->valueType(); if (vt && vt->smartPointerTypeToken) return { vt->smartPointerTypeToken, vt->smartPointerTypeToken->linkAt(-1) }; } if (pointedToType && astIsIterator(var->nameToken())) { const ValueType* vt = var->valueType(); if (vt && vt->containerTypeToken) return { vt->containerTypeToken, vt->containerTypeToken->linkAt(-1) }; } std::pair<const Token*, const Token*> result; if (Token::simpleMatch(var->typeStartToken(), "auto")) { const Token * tok2 = var->declEndToken(); if (Token::Match(tok2, "; %varid% =", var->declarationId())) tok2 = tok2->tokAt(2); if (Token::simpleMatch(tok2, "=") && Token::Match(tok2->astOperand2(), "!!=") && tok != tok2->astOperand2()) { tok2 = tok2->astOperand2(); if (Token::simpleMatch(tok2, "[") && tok2->astOperand1()) { const ValueType* vt = tok2->astOperand1()->valueType(); if (vt && vt->containerTypeToken) return { vt->containerTypeToken, vt->containerTypeToken->linkAt(-1) }; } const Token* varTok = tok2; // try to find a variable if (Token::Match(varTok, ":: %name%")) varTok = varTok->next(); while (Token::Match(varTok, "%name% ::")) varTok = varTok->tokAt(2); std::pair<const Token*, const Token*> r = typeDecl(varTok); if (r.first) return r; if (pointedToType && tok2->astOperand1() && Token::simpleMatch(tok2, "new")) { if (Token::simpleMatch(tok2->astOperand1(), "(")) return { tok2->next(), tok2->astOperand1() }; const Token* declEnd = nextAfterAstRightmostLeaf(tok2->astOperand1()); if (Token::simpleMatch(declEnd, "<") && declEnd->link()) declEnd = declEnd->link()->next(); return { tok2->next(), declEnd }; } const Token *typeBeg{}, *typeEnd{}; if (tok2->str() == "::" && Token::simpleMatch(tok2->astOperand2(), "{")) { // empty initlist typeBeg = previousBeforeAstLeftmostLeaf(tok2); typeEnd = tok2->astOperand2(); } else if (tok2->str() == "{") { typeBeg = previousBeforeAstLeftmostLeaf(tok2); typeEnd = tok2; } if (typeBeg) result = { typeBeg->next(), typeEnd }; // handle smart pointers/iterators first } if (astIsRangeBasedForDecl(var->nameToken()) && astIsContainer(var->nameToken()->astParent()->astOperand2())) { // range-based for const ValueType* vt = var->nameToken()->astParent()->astOperand2()->valueType(); if (vt && vt->containerTypeToken) return { vt->containerTypeToken, vt->containerTypeToken->linkAt(-1) }; } } if (result.first) return result; return {var->typeStartToken(), var->typeEndToken()->next()}; } if (Token::simpleMatch(tok, "return")) { // cppcheck-suppress shadowFunction - TODO: fix this const Scope* scope = tok->scope(); if (!scope) return {}; // cppcheck-suppress shadowFunction - TODO: fix this const Function* function = scope->function; if (!function) return {}; return { function->retDef, function->returnDefEnd() }; } if (tok->previous() && tok->previous()->function()) { // cppcheck-suppress shadowFunction - TODO: fix this const Function *function = tok->previous()->function(); return {function->retDef, function->returnDefEnd()}; } if (Token::simpleMatch(tok, "=")) return Token::typeDecl(tok->astOperand1()); if (Token::simpleMatch(tok, ".")) return Token::typeDecl(tok->astOperand2()); const ::Type * t = typeOf(tok); if (!t || !t->classDef) return {}; return {t->classDef->next(), t->classDef->tokAt(2)}; } std::string Token::typeStr(const Token* tok) { if (tok->valueType()) { const ValueType * vt = tok->valueType(); std::string ret = vt->str(); if (!ret.empty()) return ret; } std::pair<const Token*, const Token*> r = Token::typeDecl(tok); if (!r.first || !r.second) return ""; return r.first->stringifyList(r.second, false); } void Token::scopeInfo(std::shared_ptr<ScopeInfo2> newScopeInfo) { mImpl->mScopeInfo = std::move(newScopeInfo); } std::shared_ptr<ScopeInfo2> Token::scopeInfo() const { return mImpl->mScopeInfo; } bool Token::hasKnownIntValue() const { if (!mImpl->mValues) return false; return std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [](const ValueFlow::Value& value) { return value.isKnown() && value.isIntValue(); }); } bool Token::hasKnownValue() const { return mImpl->mValues && std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), std::mem_fn(&ValueFlow::Value::isKnown)); } bool Token::hasKnownValue(ValueFlow::Value::ValueType t) const { return mImpl->mValues && std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& value) { return value.isKnown() && value.valueType == t; }); } bool Token::hasKnownSymbolicValue(const Token* tok) const { if (tok->exprId() == 0) return false; return mImpl->mValues && std::any_of(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& value) { return value.isKnown() && value.isSymbolicValue() && value.tokvalue && value.tokvalue->exprId() == tok->exprId(); }); } const ValueFlow::Value* Token::getKnownValue(ValueFlow::Value::ValueType t) const { if (!mImpl->mValues) return nullptr; auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [&](const ValueFlow::Value& value) { return value.isKnown() && value.valueType == t; }); return it == mImpl->mValues->end() ? nullptr : &*it; } const ValueFlow::Value* Token::getValue(const MathLib::bigint val) const { if (!mImpl->mValues) return nullptr; const auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [=](const ValueFlow::Value& value) { return value.isIntValue() && !value.isImpossible() && value.intvalue == val; }); return it == mImpl->mValues->end() ? nullptr : &*it; } template<class Compare> static const ValueFlow::Value* getCompareValue(const std::list<ValueFlow::Value>& values, bool condition, MathLib::bigint path, Compare compare) { const ValueFlow::Value* ret = nullptr; for (const ValueFlow::Value& value : values) { if (!value.isIntValue()) continue; if (value.isImpossible()) continue; if (path > -0 && value.path != 0 && value.path != path) continue; if ((!ret || compare(value.intvalue, ret->intvalue)) && ((value.condition != nullptr) == condition)) ret = &value; } return ret; } const ValueFlow::Value* Token::getMaxValue(bool condition, MathLib::bigint path) const { if (!mImpl->mValues) return nullptr; return getCompareValue(*mImpl->mValues, condition, path, std::greater<MathLib::bigint>{}); } const ValueFlow::Value* Token::getMinValue(bool condition, MathLib::bigint path) const { if (!mImpl->mValues) return nullptr; return getCompareValue(*mImpl->mValues, condition, path, std::less<MathLib::bigint>{}); } const ValueFlow::Value* Token::getMovedValue() const { if (!mImpl->mValues) return nullptr; const auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [](const ValueFlow::Value& value) { return value.isMovedValue() && !value.isImpossible() && value.moveKind != ValueFlow::Value::MoveKind::NonMovedVariable; }); return it == mImpl->mValues->end() ? nullptr : &*it; } // cppcheck-suppress unusedFunction const ValueFlow::Value* Token::getContainerSizeValue(const MathLib::bigint val) const { if (!mImpl->mValues) return nullptr; const auto it = std::find_if(mImpl->mValues->begin(), mImpl->mValues->end(), [=](const ValueFlow::Value& value) { return value.isContainerSizeValue() && !value.isImpossible() && value.intvalue == val; }); return it == mImpl->mValues->end() ? nullptr : &*it; } TokenImpl::~TokenImpl() { delete mOriginalName; delete mValueType; delete mValues; if (mTemplateSimplifierPointers) { for (auto *templateSimplifierPointer : *mTemplateSimplifierPointers) { templateSimplifierPointer->token(nullptr); } } delete mTemplateSimplifierPointers; while (mCppcheckAttributes) { CppcheckAttributes *c = mCppcheckAttributes; mCppcheckAttributes = mCppcheckAttributes->next; delete c; } } void TokenImpl::setCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint value) { CppcheckAttributes *attr = mCppcheckAttributes; while (attr && attr->type != type) attr = attr->next; if (attr) attr->value = value; else { attr = new CppcheckAttributes; attr->type = type; attr->value = value; attr->next = mCppcheckAttributes; mCppcheckAttributes = attr; } } bool TokenImpl::getCppcheckAttribute(TokenImpl::CppcheckAttributes::Type type, MathLib::bigint &value) const { CppcheckAttributes *attr = mCppcheckAttributes; while (attr && attr->type != type) attr = attr->next; if (attr) value = attr->value; return attr != nullptr; } Token* findTypeEnd(Token* tok) { while (Token::Match(tok, "%name%|.|::|*|&|&&|<|(|template|decltype|sizeof")) { if (Token::Match(tok, "(|<")) tok = tok->link(); if (!tok) return nullptr; tok = tok->next(); } return tok; } Token* findLambdaEndScope(Token* tok) { if (!Token::simpleMatch(tok, "[")) return nullptr; tok = tok->link(); if (!Token::Match(tok, "] (|{")) return nullptr; tok = tok->linkAt(1); if (Token::simpleMatch(tok, "}")) return tok; if (Token::simpleMatch(tok, ") {")) return tok->linkAt(1); if (!Token::simpleMatch(tok, ")")) return nullptr; tok = tok->next(); while (Token::Match(tok, "mutable|constexpr|consteval|noexcept|.")) { if (Token::simpleMatch(tok, "noexcept (")) tok = tok->linkAt(1); if (Token::simpleMatch(tok, ".")) { tok = findTypeEnd(tok); break; } tok = tok->next(); } if (Token::simpleMatch(tok, "{")) return tok->link(); return nullptr; } const Token* findLambdaEndScope(const Token* tok) { return findLambdaEndScope(const_cast<Token*>(tok)); } const std::string& Token::fileName() const { return mTokensFrontBack.list.getFiles()[mImpl->mFileIndex]; }
87,992
C++
.cpp
2,410
27.00249
179
0.526813
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,115
keywords.cpp
danmar_cppcheck/lib/keywords.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "keywords.h" #include "utils.h" // see https://en.cppreference.com/w/c/keyword #define C90_KEYWORDS \ "auto", "break", "case", "char", "const", "continue", "default", \ "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "int", "long", \ "register", "return", "short", "signed", "sizeof", "static", "struct", "switch", "typedef", \ "union", "unsigned", "void", "volatile", "while" #define C99_KEYWORDS \ "inline", "restrict", "_Bool", "_Complex", "_Imaginary" #define C11_KEYWORDS \ "_Alignas", "_Alignof", "_Atomic", "_Generic", "_Noreturn", "_Static_assert", "_Thread_local" #define C23_KEYWORDS \ "alignas", "alignof", "bool", "constexpr", "false", "nullptr", "static_assert", "thread_local", "true", "typeof", "typeof_unqual", \ "_BitInt", "_Decimal128", "_Decimal32", "_Decimal64" static const std::unordered_set<std::string> c89_keywords_all = { C90_KEYWORDS }; static const std::unordered_set<std::string> c89_keywords = { C90_KEYWORDS }; static const std::unordered_set<std::string> c99_keywords_all = { C90_KEYWORDS, C99_KEYWORDS }; static const std::unordered_set<std::string> c99_keywords = { C99_KEYWORDS }; static const std::unordered_set<std::string> c11_keywords_all = { C90_KEYWORDS, C99_KEYWORDS, C11_KEYWORDS }; static const std::unordered_set<std::string> c11_keywords = { C11_KEYWORDS }; static const std::unordered_set<std::string> c17_keywords_all = { C90_KEYWORDS, C99_KEYWORDS, C11_KEYWORDS }; static const std::unordered_set<std::string> c17_keywords = { }; static const std::unordered_set<std::string> c23_keywords_all = { C90_KEYWORDS, C99_KEYWORDS, C11_KEYWORDS, C23_KEYWORDS }; static const std::unordered_set<std::string> c23_keywords = { C23_KEYWORDS }; // see https://en.cppreference.com/w/cpp/keyword #define CPP03_KEYWORDS \ "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", \ "class", "compl", "const", "const_cast", "continue", "default", \ "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", \ "float", "for", "friend", "goto", "if", "inline", "int", "long", \ "mutable", "namespace", "new", "not", "not_eq", "operator", \ "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", \ "return", "short", "signed", "sizeof", "static", \ "static_cast", "struct", "switch", "template", "this", "throw", \ "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", \ "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq" #define CPP11_KEYWORDS \ "alignas", "alignof", "char16_t", "char32_t", "constexpr", "decltype", \ "noexcept", "nullptr", "static_assert", "thread_local" #define CPP20_KEYWORDS \ "char8_t", "concept", "consteval", "constinit", "co_await", \ "co_return", "co_yield", "requires" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-macros" #endif #define CPP_TMTS_KEYWORDS \ "atomic_cancel", "atomic_commit", "atomic_noexcept", "synchronized" #define CPP_REFL_TS_KEYWORDS \ "reflexpr" #ifdef __clang__ #pragma clang diagnostic pop #endif static const std::unordered_set<std::string> cpp03_keywords_all = { CPP03_KEYWORDS }; static const std::unordered_set<std::string> cpp03_keywords = { CPP03_KEYWORDS }; static const std::unordered_set<std::string> cpp11_keywords_all = { CPP03_KEYWORDS, CPP11_KEYWORDS }; static const std::unordered_set<std::string> cpp11_keywords = { CPP11_KEYWORDS }; static const std::unordered_set<std::string> cpp14_keywords_all = { CPP03_KEYWORDS, CPP11_KEYWORDS }; static const std::unordered_set<std::string> cpp14_keywords = { }; static const std::unordered_set<std::string> cpp17_keywords_all = { CPP03_KEYWORDS, CPP11_KEYWORDS }; static const std::unordered_set<std::string> cpp17_keywords = { }; static const std::unordered_set<std::string> cpp20_keywords_all = { CPP03_KEYWORDS, CPP11_KEYWORDS, CPP20_KEYWORDS }; static const std::unordered_set<std::string> cpp20_keywords = { CPP20_KEYWORDS }; static const std::unordered_set<std::string> cpp23_keywords = { }; static const std::unordered_set<std::string> cpp23_keywords_all = { CPP03_KEYWORDS, CPP11_KEYWORDS, CPP20_KEYWORDS }; static const std::unordered_set<std::string> cpp26_keywords = { }; static const std::unordered_set<std::string> cpp26_keywords_all = { CPP03_KEYWORDS, CPP11_KEYWORDS, CPP20_KEYWORDS }; // cppcheck-suppress unusedFunction const std::unordered_set<std::string>& Keywords::getAll(Standards::cstd_t cStd) { // cppcheck-suppress missingReturn switch (cStd) { case Standards::cstd_t::C89: return c89_keywords_all; case Standards::cstd_t::C99: return c99_keywords_all; case Standards::cstd_t::C11: return c11_keywords_all; case Standards::cstd_t::C17: return c17_keywords_all; case Standards::cstd_t::C23: return c23_keywords_all; } cppcheck::unreachable(); } // cppcheck-suppress unusedFunction const std::unordered_set<std::string>& Keywords::getAll(Standards::cppstd_t cppStd) { // cppcheck-suppress missingReturn switch (cppStd) { case Standards::cppstd_t::CPP03: return cpp03_keywords_all; case Standards::cppstd_t::CPP11: return cpp11_keywords_all; case Standards::cppstd_t::CPP14: return cpp14_keywords_all; case Standards::cppstd_t::CPP17: return cpp17_keywords_all; case Standards::cppstd_t::CPP20: return cpp20_keywords_all; case Standards::cppstd_t::CPP23: return cpp23_keywords_all; case Standards::cppstd_t::CPP26: return cpp26_keywords_all; } cppcheck::unreachable(); } // cppcheck-suppress unusedFunction const std::unordered_set<std::string>& Keywords::getOnly(Standards::cstd_t cStd) { // cppcheck-suppress missingReturn switch (cStd) { case Standards::cstd_t::C89: return c89_keywords; case Standards::cstd_t::C99: return c99_keywords; case Standards::cstd_t::C11: return c11_keywords; case Standards::cstd_t::C17: return c17_keywords; case Standards::cstd_t::C23: return c23_keywords; } cppcheck::unreachable(); } // cppcheck-suppress unusedFunction const std::unordered_set<std::string>& Keywords::getOnly(Standards::cppstd_t cppStd) { // cppcheck-suppress missingReturn switch (cppStd) { case Standards::cppstd_t::CPP03: return cpp03_keywords; case Standards::cppstd_t::CPP11: return cpp11_keywords; case Standards::cppstd_t::CPP14: return cpp14_keywords; case Standards::cppstd_t::CPP17: return cpp17_keywords; case Standards::cppstd_t::CPP20: return cpp20_keywords; case Standards::cppstd_t::CPP23: return cpp23_keywords; case Standards::cppstd_t::CPP26: return cpp26_keywords; } cppcheck::unreachable(); }
7,815
C++
.cpp
207
33.932367
136
0.684558
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,116
pathanalysis.cpp
danmar_cppcheck/lib/pathanalysis.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pathanalysis.h" #include "astutils.h" #include "symboldatabase.h" #include "token.h" #include "vfvalue.h" #include <algorithm> #include <string> #include <tuple> const Scope* PathAnalysis::findOuterScope(const Scope * scope) { if (!scope) return nullptr; if (scope->isLocal() && scope->type != Scope::eSwitch) return findOuterScope(scope->nestedIn); return scope; } static const Token* assignExpr(const Token* tok) { while (tok->astParent() && astIsLHS(tok)) { if (Token::Match(tok->astParent(), "%assign%")) return tok->astParent(); tok = tok->astParent(); } return nullptr; } std::pair<bool, bool> PathAnalysis::checkCond(const Token * tok, bool& known) { if (tok->hasKnownIntValue()) { known = true; return std::make_pair(tok->values().front().intvalue, !tok->values().front().intvalue); } auto it = std::find_if(tok->values().cbegin(), tok->values().cend(), [](const ValueFlow::Value& v) { return v.isIntValue(); }); // If all possible values are the same, then assume all paths have the same value if (it != tok->values().cend() && std::all_of(it, tok->values().cend(), [&](const ValueFlow::Value& v) { if (v.isIntValue()) return v.intvalue == it->intvalue; return true; })) { known = false; return std::make_pair(it->intvalue, !it->intvalue); } return std::make_pair(true, true); } PathAnalysis::Progress PathAnalysis::forwardRecursive(const Token* tok, Info info, const std::function<PathAnalysis::Progress(const Info&)>& f) { if (!tok) return Progress::Continue; if (tok->astOperand1() && forwardRecursive(tok->astOperand1(), info, f) == Progress::Break) return Progress::Break; info.tok = tok; if (f(info) == Progress::Break) return Progress::Break; if (tok->astOperand2() && forwardRecursive(tok->astOperand2(), std::move(info), f) == Progress::Break) return Progress::Break; return Progress::Continue; } PathAnalysis::Progress PathAnalysis::forwardRange(const Token* startToken, const Token* endToken, Info info, const std::function<PathAnalysis::Progress(const Info&)>& f) const { for (const Token *tok = startToken; precedes(tok, endToken); tok = tok->next()) { if (Token::Match(tok, "asm|goto|break|continue")) return Progress::Break; if (Token::Match(tok, "return|throw")) { forwardRecursive(tok, std::move(info), f); return Progress::Break; // Evaluate RHS of assignment before LHS } if (const Token* assignTok = assignExpr(tok)) { if (forwardRecursive(assignTok->astOperand2(), info, f) == Progress::Break) return Progress::Break; if (forwardRecursive(assignTok->astOperand1(), info, f) == Progress::Break) return Progress::Break; tok = nextAfterAstRightmostLeaf(assignTok); if (!tok) return Progress::Break; } else if (Token::simpleMatch(tok, "}") && Token::simpleMatch(tok->link()->previous(), ") {") && Token::Match(tok->link()->linkAt(-1)->previous(), "if|while|for (")) { const Token * blockStart = tok->link()->linkAt(-1)->previous(); const Token * condTok = getCondTok(blockStart); if (!condTok) continue; info.errorPath.emplace_back(condTok, "Assuming condition is true."); // Traverse a loop a second time if (Token::Match(blockStart, "for|while (")) { const Token* endCond = blockStart->linkAt(1); bool traverseLoop = true; // Only traverse simple for loops if (Token::simpleMatch(blockStart, "for") && !Token::Match(endCond->tokAt(-3), "; ++|--|%var% %var%|++|-- ) {")) traverseLoop = false; // Traverse loop a second time if (traverseLoop) { // Traverse condition if (forwardRecursive(condTok, info, f) == Progress::Break) return Progress::Break; // TODO: Should we traverse the body: forwardRange(tok->link(), tok, info, f)? } } if (Token::simpleMatch(tok, "} else {")) { tok = tok->linkAt(2); } } else if (Token::Match(tok, "if|while|for (") && Token::simpleMatch(tok->linkAt(1), ") {")) { const Token * endCond = tok->linkAt(1); const Token * endBlock = endCond->linkAt(1); const Token * condTok = getCondTok(tok); if (!condTok) continue; // Traverse condition if (forwardRange(tok->next(), tok->linkAt(1), info, f) == Progress::Break) return Progress::Break; Info i = info; i.known = false; i.errorPath.emplace_back(condTok, "Assuming condition is true."); // Check if condition is true or false bool checkThen = false; bool checkElse = false; std::tie(checkThen, checkElse) = checkCond(condTok, i.known); // Traverse then block if (checkThen) { if (forwardRange(endCond->next(), endBlock, i, f) == Progress::Break) return Progress::Break; } // Traverse else block if (Token::simpleMatch(endBlock, "} else {")) { if (checkElse) { i.errorPath.back().second = "Assuming condition is false."; const Progress result = forwardRange(endCond->next(), endBlock, std::move(i), f); if (result == Progress::Break) return Progress::Break; } tok = endBlock->linkAt(2); } else { tok = endBlock; } } else if (Token::simpleMatch(tok, "} else {")) { tok = tok->linkAt(2); } else { info.tok = tok; if (f(info) == Progress::Break) return Progress::Break; } // Prevent infinite recursion if (tok->next() == start) break; } return Progress::Continue; } void PathAnalysis::forward(const std::function<Progress(const Info&)>& f) const { const Scope * endScope = findOuterScope(start->scope()); if (!endScope) return; const Token * endToken = endScope->bodyEnd; Info info{start, ErrorPath{}, true}; forwardRange(start, endToken, std::move(info), f); } bool reaches(const Token * start, const Token * dest, const Library& library, ErrorPath* errorPath) { PathAnalysis::Info info = PathAnalysis{start, library}.forwardFind([&](const PathAnalysis::Info& i) { return (i.tok == dest); }); if (!info.tok) return false; if (errorPath) errorPath->insert(errorPath->end(), info.errorPath.cbegin(), info.errorPath.cend()); return true; }
7,829
C++
.cpp
183
33.868852
175
0.590123
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,117
vf_switchvariable.cpp
danmar_cppcheck/lib/vf_switchvariable.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_switchvariable.h" #include "mathlib.h" #include "settings.h" #include "sourcelocation.h" #include "symboldatabase.h" #include "token.h" #include "vfvalue.h" #include "vf_bailout.h" #include "vf_reverse.h" #include <list> #include <string> #include <utility> namespace ValueFlow { // Deprecated static void valueFlowReverse(const TokenList& tokenlist, Token* tok, const Token* const varToken, Value val, ErrorLogger& errorLogger, const Settings& settings, SourceLocation loc = SourceLocation::current()) { valueFlowReverse(tok, nullptr, varToken, {std::move(val)}, tokenlist, errorLogger, settings, loc); } void analyzeSwitchVariable(const TokenList &tokenlist, const SymbolDatabase& symboldatabase, ErrorLogger &errorLogger, const Settings &settings) { for (const Scope &scope : symboldatabase.scopeList) { if (scope.type != Scope::ScopeType::eSwitch) continue; if (!Token::Match(scope.classDef, "switch ( %var% ) {")) continue; const Token *vartok = scope.classDef->tokAt(2); const Variable *var = vartok->variable(); if (!var) continue; // bailout: global non-const variables if (!(var->isLocal() || var->isArgument()) && !var->isConst()) { if (settings.debugwarnings) bailout(tokenlist, errorLogger, vartok, "switch variable " + var->name() + " is global"); continue; } for (const Token *tok = scope.bodyStart->next(); tok != scope.bodyEnd; tok = tok->next()) { if (tok->str() == "{") { tok = tok->link(); continue; } if (Token::Match(tok, "case %num% :")) { std::list<Value> values; values.emplace_back(MathLib::toBigNumber(tok->strAt(1))); values.back().condition = tok; values.back().errorPath.emplace_back(tok, "case " + tok->strAt(1) + ": " + vartok->str() + " is " + tok->strAt(1) + " here."); bool known = false; if ((Token::simpleMatch(tok->previous(), "{") || Token::simpleMatch(tok->tokAt(-2), "break ;")) && !Token::Match(tok->tokAt(3), ";| case")) known = true; while (Token::Match(tok->tokAt(3), ";| case %num% :")) { known = false; tok = tok->tokAt(3); if (!tok->isName()) tok = tok->next(); values.emplace_back(MathLib::toBigNumber(tok->strAt(1))); values.back().condition = tok; values.back().errorPath.emplace_back(tok, "case " + tok->strAt(1) + ": " + vartok->str() + " is " + tok->strAt(1) + " here."); } for (auto val = values.cbegin(); val != values.cend(); ++val) { valueFlowReverse(tokenlist, const_cast<Token*>(scope.classDef), vartok, *val, errorLogger, settings); } if (vartok->variable()->scope()) { if (known) values.back().setKnown(); // FIXME We must check if there is a return. See #9276 /* valueFlowForwardVariable(tok->tokAt(3), vartok->variable()->scope()->bodyEnd, vartok->variable(), vartok->varId(), values, values.back().isKnown(), false, tokenlist, errorLogger, settings); */ } } } } } }
5,334
C++
.cpp
111
30.324324
159
0.465094
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,118
checknullpointer.cpp
danmar_cppcheck/lib/checknullpointer.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checknullpointer.h" #include "astutils.h" #include "ctu.h" #include "errorlogger.h" #include "errortypes.h" #include "findtoken.h" #include "library.h" #include "mathlib.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "valueflow.h" #include <algorithm> #include <cctype> #include <map> #include <set> #include <vector> //--------------------------------------------------------------------------- // CWE ids used: static const CWE CWE_NULL_POINTER_DEREFERENCE(476U); static const CWE CWE_INCORRECT_CALCULATION(682U); // Register this check class (by creating a static instance of it) namespace { CheckNullPointer instance; } //--------------------------------------------------------------------------- static bool checkNullpointerFunctionCallPlausibility(const Function* func, unsigned int arg) { return !func || (func->argCount() >= arg && func->getArgumentVar(arg - 1) && func->getArgumentVar(arg - 1)->isPointer()); } /** * @brief parse a function call and extract information about variable usage * @param tok first token * @param var variables that the function read / write. * @param library --library files data * @param checkNullArg perform isnullargbad check for each argument? */ void CheckNullPointer::parseFunctionCall(const Token &tok, std::list<const Token *> &var, const Library &library, bool checkNullArg) { if (Token::Match(&tok, "%name% ( )") || !tok.tokAt(2)) return; const std::vector<const Token *> args = getArguments(&tok); for (int argnr = 1; argnr <= args.size(); ++argnr) { const Token *param = args[argnr - 1]; if ((!checkNullArg || library.isnullargbad(&tok, argnr)) && checkNullpointerFunctionCallPlausibility(tok.function(), argnr)) var.push_back(param); else if (tok.function()) { const Variable* argVar = tok.function()->getArgumentVar(argnr-1); if (argVar && argVar->isStlStringType() && !argVar->isArrayOrPointer()) var.push_back(param); } } if (library.formatstr_function(&tok)) { const int formatStringArgNr = library.formatstr_argno(&tok); if (formatStringArgNr < 0 || formatStringArgNr >= args.size()) return; // 1st parameter.. if (Token::Match(&tok, "snprintf|vsnprintf|fnprintf|vfnprintf") && args.size() > 1 && !(args[1] && args[1]->hasKnownIntValue() && args[1]->getKnownIntValue() == 0)) // Only if length (second parameter) is not zero var.push_back(args[0]); if (args[formatStringArgNr]->tokType() != Token::eString) return; const std::string &formatString = args[formatStringArgNr]->strValue(); int argnr = formatStringArgNr + 1; const bool scan = library.formatstr_scan(&tok); bool percent = false; for (std::string::const_iterator i = formatString.cbegin(); i != formatString.cend(); ++i) { if (*i == '%') { percent = !percent; } else if (percent) { percent = false; bool _continue = false; while (!std::isalpha((unsigned char)*i)) { if (*i == '*') { if (scan) _continue = true; else argnr++; } ++i; if (i == formatString.end()) return; } if (_continue) continue; if (argnr < args.size() && (*i == 'n' || *i == 's' || scan)) var.push_back(args[argnr]); if (*i != 'm') // %m is a non-standard glibc extension that requires no parameter argnr++; } } } } namespace { const std::set<std::string> stl_stream = { "fstream", "ifstream", "iostream", "istream", "istringstream", "ofstream", "ostream", "ostringstream", "stringstream", "wistringstream", "wostringstream", "wstringstream" }; } /** * Is there a pointer dereference? Everything that should result in * a nullpointer dereference error message will result in a true * return value. If it's unknown if the pointer is dereferenced false * is returned. * @param tok token for the pointer * @param unknown it is not known if there is a pointer dereference (could be reported as a debug message) * @return true => there is a dereference */ bool CheckNullPointer::isPointerDeRef(const Token *tok, bool &unknown) const { return isPointerDeRef(tok, unknown, *mSettings); } bool CheckNullPointer::isPointerDeRef(const Token *tok, bool &unknown, const Settings &settings, bool checkNullArg) { unknown = false; // Is pointer used as function parameter? if (Token::Match(tok->previous(), "[(,] %name% [,)]")) { const Token *ftok = tok->previous(); while (ftok && ftok->str() != "(") { if (ftok->str() == ")") ftok = ftok->link(); ftok = ftok->previous(); } if (ftok && ftok->previous()) { std::list<const Token *> varlist; parseFunctionCall(*ftok->previous(), varlist, settings.library, checkNullArg); if (std::find(varlist.cbegin(), varlist.cend(), tok) != varlist.cend()) { return true; } } } if (tok->str() == "(" && !tok->scope()->isExecutable()) return false; const Token* parent = tok->astParent(); if (!parent) return false; const bool addressOf = parent->astParent() && parent->astParent()->str() == "&"; if (parent->str() == "." && astIsRHS(tok)) return isPointerDeRef(parent, unknown, settings); const bool firstOperand = parent->astOperand1() == tok; parent = astParentSkipParens(tok); if (!parent) return false; // Dereferencing pointer.. const Token* grandParent = parent->astParent(); if (parent->isUnaryOp("*") && !(grandParent && isUnevaluated(grandParent->previous()))) { // declaration of function pointer if (tok->variable() && tok->variable()->nameToken() == tok) return false; if (!addressOf) return true; } // array access if (firstOperand && parent->str() == "[" && !addressOf) return true; // address of member variable / array element const Token *parent2 = parent; while (Token::Match(parent2, "[|.")) parent2 = parent2->astParent(); if (parent2 != parent && parent2 && parent2->isUnaryOp("&")) return false; // read/write member variable if (firstOperand && parent->originalName() == "->" && !addressOf) return true; // If its a function pointer then check if its called if (tok->variable() && tok->variable()->isPointer() && Token::Match(tok->variable()->nameToken(), "%name% ) (") && Token::Match(tok, "%name% (")) return true; if (Token::Match(tok, "%var% = %var% .") && tok->varId() == tok->tokAt(2)->varId()) return true; // std::string dereferences nullpointers if (Token::Match(parent->tokAt(-3), "std :: string|wstring (|{ %name% )|}")) return true; if (Token::Match(parent->previous(), "%name% (|{ %name% )|}")) { const Variable* var = tok->tokAt(-2)->variable(); if (var && !var->isPointer() && !var->isArray() && var->isStlStringType()) return true; } // streams dereference nullpointers if (Token::Match(parent, "<<|>>") && !firstOperand) { const Variable* var = tok->variable(); if (var && var->isPointer() && Token::Match(var->typeStartToken(), "char|wchar_t")) { // Only outputting or reading to char* can cause problems const Token* tok2 = parent; // Find start of statement for (; tok2; tok2 = tok2->previous()) { if (Token::Match(tok2->previous(), ";|{|}|:")) break; } if (Token::Match(tok2, "std :: cout|cin|cerr")) return true; if (tok2 && tok2->varId() != 0) { const Variable* var2 = tok2->variable(); if (var2 && var2->isStlType(stl_stream)) return true; } } } const Variable *ovar = nullptr; if (Token::Match(parent, "+|==|!=") || (parent->str() == "=" && !firstOperand)) { if (parent->astOperand1() == tok && parent->astOperand2()) ovar = parent->astOperand2()->variable(); else if (parent->astOperand1() && parent->astOperand2() == tok) ovar = parent->astOperand1()->variable(); } if (ovar && !ovar->isPointer() && !ovar->isArray() && ovar->isStlStringType()) return true; // assume that it's not a dereference (no false positives) return false; } static bool isNullablePointer(const Token* tok) { if (!tok) return false; if (Token::simpleMatch(tok, "new") && tok->varId() == 0) return false; if (astIsPointer(tok)) return true; if (astIsSmartPointer(tok)) return true; if (Token::simpleMatch(tok, ".")) return isNullablePointer(tok->astOperand2()); if (const Variable* var = tok->variable()) { return (var->isPointer() || var->isSmartPointer()); } return false; } void CheckNullPointer::nullPointerByDeRefAndCheck() { const bool printInconclusive = (mSettings->certainty.isEnabled(Certainty::inconclusive)); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { auto pred = [printInconclusive](const Token* tok) -> bool { if (!tok) return false; if (Token::Match(tok, "%num%|%char%|%str%")) return false; if (!isNullablePointer(tok) || (tok->str() == "." && isNullablePointer(tok->astOperand2()) && tok->astOperand2()->getValue(0))) // avoid duplicate warning return false; // Can pointer be NULL? const ValueFlow::Value *value = tok->getValue(0); if (!value) return false; if (!printInconclusive && value->isInconclusive()) return false; return true; }; std::vector<const Token *> tokens = findTokensSkipDeadAndUnevaluatedCode(mSettings->library, scope->bodyStart, scope->bodyEnd, pred); for (const Token *tok : tokens) { const ValueFlow::Value *value = tok->getValue(0); // Pointer dereference. bool unknown = false; if (!isPointerDeRef(tok, unknown)) { if (unknown) nullPointerError(tok, tok->expressionString(), value, true); continue; } nullPointerError(tok, tok->expressionString(), value, value->isInconclusive()); } } } void CheckNullPointer::nullPointer() { logChecker("CheckNullPointer::nullPointer"); nullPointerByDeRefAndCheck(); } namespace { const std::set<std::string> stl_istream = { "fstream", "ifstream", "iostream", "istream", "istringstream", "stringstream", "wistringstream", "wstringstream" }; } /** Dereferencing null constant (simplified token list) */ void CheckNullPointer::nullConstantDereference() { logChecker("CheckNullPointer::nullConstantDereference"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { if (scope->function == nullptr || !scope->function->hasBody()) // We only look for functions with a body continue; const Token *tok = scope->bodyStart; if (scope->function->isConstructor()) tok = scope->function->token; // Check initialization list for (; tok != scope->bodyEnd; tok = tok->next()) { if (isUnevaluated(tok)) tok = tok->linkAt(1); else if (Token::simpleMatch(tok, "* 0")) { if (Token::Match(tok->previous(), "return|throw|;|{|}|:|[|(|,") || tok->previous()->isOp()) { nullPointerError(tok); } } else if (Token::Match(tok, "0 [") && (tok->strAt(-1) != "&" || !Token::Match(tok->linkAt(1)->next(), "[.(]"))) nullPointerError(tok); else if (Token::Match(tok->previous(), "!!. %name% (|{") && (tok->strAt(-1) != "::" || tok->strAt(-2) == "std")) { if (Token::Match(tok->tokAt(2), "0|NULL|nullptr )|}") && tok->varId()) { // constructor call const Variable *var = tok->variable(); if (var && !var->isPointer() && !var->isArray() && var->isStlStringType()) nullPointerError(tok); } else { // function call std::list<const Token *> var; parseFunctionCall(*tok, var, mSettings->library); // is one of the var items a NULL pointer? for (const Token *vartok : var) { if (vartok->hasKnownIntValue() && vartok->getKnownIntValue() == 0) nullPointerError(vartok); } } } else if (Token::Match(tok, "std :: string|wstring ( 0|NULL|nullptr )")) nullPointerError(tok); else if (Token::Match(tok->previous(), "::|. %name% (")) { const std::vector<const Token *> &args = getArguments(tok); for (int argnr = 0; argnr < args.size(); ++argnr) { const Token *argtok = args[argnr]; if (!argtok->hasKnownIntValue()) continue; if (argtok->values().front().intvalue != 0) continue; if (mSettings->library.isnullargbad(tok, argnr+1)) nullPointerError(argtok); } } else if (Token::Match(tok->previous(), ">> 0|NULL|nullptr")) { // Only checking input stream operations is safe here, because otherwise 0 can be an integer as well const Token* tok2 = tok->previous(); // Find start of statement for (; tok2; tok2 = tok2->previous()) { if (Token::Match(tok2->previous(), ";|{|}|:|(")) break; } if (tok2 && tok2->previous() && tok2->strAt(-1)=="(") continue; if (Token::simpleMatch(tok2, "std :: cin")) nullPointerError(tok); if (tok2 && tok2->varId() != 0) { const Variable *var = tok2->variable(); if (var && var->isStlType(stl_istream)) nullPointerError(tok); } } const Variable *ovar = nullptr; const Token *tokNull = nullptr; if (Token::Match(tok, "0|NULL|nullptr ==|!=|>|>=|<|<= %var%")) { if (!Token::Match(tok->tokAt(3),".|[")) { ovar = tok->tokAt(2)->variable(); tokNull = tok; } } else if (Token::Match(tok, "%var% ==|!=|>|>=|<|<= 0|NULL|nullptr") || Token::Match(tok, "%var% =|+ 0|NULL|nullptr )|]|,|;|+")) { ovar = tok->variable(); tokNull = tok->tokAt(2); } if (ovar && !ovar->isPointer() && !ovar->isArray() && ovar->isStlStringType() && tokNull && tokNull->originalName() != "'\\0'") nullPointerError(tokNull); } } } void CheckNullPointer::nullPointerError(const Token *tok, const std::string &varname, const ValueFlow::Value *value, bool inconclusive) { const std::string errmsgcond("$symbol:" + varname + '\n' + ValueFlow::eitherTheConditionIsRedundant(value ? value->condition : nullptr) + " or there is possible null pointer dereference: $symbol."); const std::string errmsgdefarg("$symbol:" + varname + "\nPossible null pointer dereference if the default parameter value is used: $symbol"); if (!tok) { reportError(tok, Severity::error, "nullPointer", "Null pointer dereference", CWE_NULL_POINTER_DEREFERENCE, Certainty::normal); reportError(tok, Severity::warning, "nullPointerDefaultArg", errmsgdefarg, CWE_NULL_POINTER_DEREFERENCE, Certainty::normal); reportError(tok, Severity::warning, "nullPointerRedundantCheck", errmsgcond, CWE_NULL_POINTER_DEREFERENCE, Certainty::normal); return; } if (!value) { reportError(tok, Severity::error, "nullPointer", "Null pointer dereference", CWE_NULL_POINTER_DEREFERENCE, inconclusive ? Certainty::inconclusive : Certainty::normal); return; } if (!mSettings->isEnabled(value, inconclusive) && !mSettings->isPremiumEnabled("nullPointer")) return; const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer dereference"); if (value->condition) { reportError(errorPath, Severity::warning, "nullPointerRedundantCheck", errmsgcond, CWE_NULL_POINTER_DEREFERENCE, inconclusive || value->isInconclusive() ? Certainty::inconclusive : Certainty::normal); } else if (value->defaultArg) { reportError(errorPath, Severity::warning, "nullPointerDefaultArg", errmsgdefarg, CWE_NULL_POINTER_DEREFERENCE, inconclusive || value->isInconclusive() ? Certainty::inconclusive : Certainty::normal); } else { std::string errmsg = std::string(value->isKnown() ? "Null" : "Possible null") + " pointer dereference"; if (!varname.empty()) errmsg = "$symbol:" + varname + '\n' + errmsg + ": $symbol"; reportError(errorPath, value->isKnown() ? Severity::error : Severity::warning, "nullPointer", errmsg, CWE_NULL_POINTER_DEREFERENCE, inconclusive || value->isInconclusive() ? Certainty::inconclusive : Certainty::normal); } } void CheckNullPointer::arithmetic() { logChecker("CheckNullPointer::arithmetic"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "-|+|+=|-=|++|--")) continue; const Token *pointerOperand; const Token *numericOperand; if (tok->astOperand1() && tok->astOperand1()->valueType() && tok->astOperand1()->valueType()->pointer != 0) { pointerOperand = tok->astOperand1(); numericOperand = tok->astOperand2(); } else if (tok->astOperand2() && tok->astOperand2()->valueType() && tok->astOperand2()->valueType()->pointer != 0) { pointerOperand = tok->astOperand2(); numericOperand = tok->astOperand1(); } else continue; if (numericOperand && numericOperand->valueType() && !numericOperand->valueType()->isIntegral()) continue; const ValueFlow::Value* numValue = numericOperand ? numericOperand->getValue(0) : nullptr; if (numValue && numValue->intvalue == 0) // don't warn for arithmetic with 0 continue; const ValueFlow::Value* value = pointerOperand->getValue(0); if (!value) continue; if (!mSettings->certainty.isEnabled(Certainty::inconclusive) && value->isInconclusive()) continue; if (value->condition && !mSettings->severity.isEnabled(Severity::warning)) continue; if (value->condition) redundantConditionWarning(tok, value, value->condition, value->isInconclusive()); else pointerArithmeticError(tok, value, value->isInconclusive()); } } } static std::string arithmeticTypeString(const Token *tok) { if (tok && tok->str()[0] == '-') return "subtraction"; if (tok && tok->str()[0] == '+') return "addition"; return "arithmetic"; } void CheckNullPointer::pointerArithmeticError(const Token* tok, const ValueFlow::Value *value, bool inconclusive) { // cppcheck-suppress shadowFunction - TODO: fix this std::string arithmetic = arithmeticTypeString(tok); std::string errmsg; if (tok && tok->str()[0] == '-') { errmsg = "Overflow in pointer arithmetic, NULL pointer is subtracted."; } else { errmsg = "Pointer " + arithmetic + " with NULL pointer."; } const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer " + arithmetic); reportError(errorPath, Severity::error, "nullPointerArithmetic", errmsg, CWE_INCORRECT_CALCULATION, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckNullPointer::redundantConditionWarning(const Token* tok, const ValueFlow::Value *value, const Token *condition, bool inconclusive) { // cppcheck-suppress shadowFunction - TODO: fix this std::string arithmetic = arithmeticTypeString(tok); std::string errmsg; if (tok && tok->str()[0] == '-') { errmsg = ValueFlow::eitherTheConditionIsRedundant(condition) + " or there is overflow in pointer " + arithmetic + "."; } else { errmsg = ValueFlow::eitherTheConditionIsRedundant(condition) + " or there is pointer arithmetic with NULL pointer."; } const ErrorPath errorPath = getErrorPath(tok, value, "Null pointer " + arithmetic); reportError(errorPath, Severity::warning, "nullPointerArithmeticRedundantCheck", errmsg, CWE_INCORRECT_CALCULATION, inconclusive ? Certainty::inconclusive : Certainty::normal); } // NOLINTNEXTLINE(readability-non-const-parameter) - used as callback so we need to preserve the signature static bool isUnsafeUsage(const Settings &settings, const Token *vartok, MathLib::bigint *value) { (void)value; bool unknown = false; return CheckNullPointer::isPointerDeRef(vartok, unknown, settings); } // a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now // see https://trac.cppcheck.net/ticket/12108 for more details #ifdef __clang__ inline namespace CheckNullPointer_internal #else namespace #endif { /* data for multifile checking */ class MyFileInfo : public Check::FileInfo { public: /** function arguments that are dereferenced without checking if they are null */ std::list<CTU::FileInfo::UnsafeUsage> unsafeUsage; /** Convert data into xml string */ std::string toString() const override { return CTU::toString(unsafeUsage); } }; } Check::FileInfo *CheckNullPointer::getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const { const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::getUnsafeUsage(tokenizer, settings, isUnsafeUsage); if (unsafeUsage.empty()) return nullptr; auto *fileInfo = new MyFileInfo; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } Check::FileInfo * CheckNullPointer::loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const { const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::loadUnsafeUsageListFromXml(xmlElement); if (unsafeUsage.empty()) return nullptr; auto *fileInfo = new MyFileInfo; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } bool CheckNullPointer::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) { if (!ctu) return false; bool foundErrors = false; (void)settings; // This argument is unused CheckNullPointer dummy(nullptr, &settings, &errorLogger); dummy. logChecker("CheckNullPointer::analyseWholeProgram"); // unusedfunctions const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> callsMap = ctu->getCallsMap(); for (const Check::FileInfo* fi1 : fileInfo) { const auto *fi = dynamic_cast<const MyFileInfo*>(fi1); if (!fi) continue; for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeUsage) { for (int warning = 0; warning <= 1; warning++) { if (warning == 1 && !settings.severity.isEnabled(Severity::warning)) break; const std::list<ErrorMessage::FileLocation> &locationList = CTU::FileInfo::getErrorPath(CTU::FileInfo::InvalidValueType::null, unsafeUsage, callsMap, "Dereferencing argument ARG that is null", nullptr, warning, settings.maxCtuDepth); if (locationList.empty()) continue; const ErrorMessage errmsg(locationList, emptyString, warning ? Severity::warning : Severity::error, "Null pointer dereference: " + unsafeUsage.myArgumentName, "ctunullpointer", CWE_NULL_POINTER_DEREFERENCE, Certainty::normal); errorLogger.reportErr(errmsg); foundErrors = true; break; } } } return foundErrors; }
26,945
C++
.cpp
573
37.022688
221
0.583869
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,119
preprocessor.cpp
danmar_cppcheck/lib/preprocessor.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "preprocessor.h" #include "errorlogger.h" #include "errortypes.h" #include "library.h" #include "path.h" #include "platform.h" #include "settings.h" #include "standards.h" #include "suppressions.h" #include "utils.h" #include <algorithm> #include <array> #include <cstddef> #include <iterator> #include <sstream> #include <utility> #include <simplecpp.h> static bool sameline(const simplecpp::Token *tok1, const simplecpp::Token *tok2) { return tok1 && tok2 && tok1->location.sameline(tok2->location); } Directive::Directive(const simplecpp::Location & _loc, std::string _str) : file(_loc.file()), linenr(_loc.line), str(std::move(_str)) {} Directive::Directive(std::string _file, const int _linenr, std::string _str) : file(std::move(_file)), linenr(_linenr), str(std::move(_str)) {} Directive::DirectiveToken::DirectiveToken(const simplecpp::Token & _tok) : line(_tok.location.line), column(_tok.location.col), tokStr(_tok.str()) {} char Preprocessor::macroChar = char(1); Preprocessor::Preprocessor(const Settings& settings, ErrorLogger &errorLogger) : mSettings(settings), mErrorLogger(errorLogger) {} Preprocessor::~Preprocessor() { for (const std::pair<const std::string, simplecpp::TokenList*>& tokenList : mTokenLists) delete tokenList.second; } namespace { struct BadInlineSuppression { BadInlineSuppression(std::string file, const int line, std::string msg) : file(std::move(file)), line(line), errmsg(std::move(msg)) {} std::string file; int line; std::string errmsg; }; } static bool parseInlineSuppressionCommentToken(const simplecpp::Token *tok, std::list<SuppressionList::Suppression> &inlineSuppressions, std::list<BadInlineSuppression> &bad) { const std::string cppchecksuppress("cppcheck-suppress"); const std::string &comment = tok->str(); if (comment.size() < cppchecksuppress.size()) return false; const std::string::size_type pos1 = comment.find_first_not_of("/* \t"); if (pos1 == std::string::npos) return false; if (pos1 + cppchecksuppress.size() >= comment.size()) return false; if (comment.substr(pos1, cppchecksuppress.size()) != cppchecksuppress) return false; // check if it has a prefix const std::string::size_type posEndComment = comment.find_first_of(" [", pos1+cppchecksuppress.size()); // skip spaces after "cppcheck-suppress" and its possible prefix const std::string::size_type pos2 = comment.find_first_not_of(' ', posEndComment); if (pos2 == std::string::npos) return false; SuppressionList::Type errorType = SuppressionList::Type::unique; // determine prefix if specified if (posEndComment >= (pos1 + cppchecksuppress.size() + 1)) { if (comment.at(pos1 + cppchecksuppress.size()) != '-') return false; const unsigned int argumentLength = posEndComment - (pos1 + cppchecksuppress.size() + 1); const std::string suppressTypeString = comment.substr(pos1 + cppchecksuppress.size() + 1, argumentLength); if ("file" == suppressTypeString) errorType = SuppressionList::Type::file; else if ("begin" == suppressTypeString) errorType = SuppressionList::Type::blockBegin; else if ("end" == suppressTypeString) errorType = SuppressionList::Type::blockEnd; else if ("macro" == suppressTypeString) errorType = SuppressionList::Type::macro; else return false; } if (comment[pos2] == '[') { // multi suppress format std::string errmsg; std::vector<SuppressionList::Suppression> suppressions = SuppressionList::parseMultiSuppressComment(comment, &errmsg); for (SuppressionList::Suppression &s : suppressions) { s.type = errorType; s.lineNumber = tok->location.line; } if (!errmsg.empty()) bad.emplace_back(tok->location.file(), tok->location.line, std::move(errmsg)); std::copy_if(suppressions.cbegin(), suppressions.cend(), std::back_inserter(inlineSuppressions), [](const SuppressionList::Suppression& s) { return !s.errorId.empty(); }); } else { //single suppress format std::string errmsg; SuppressionList::Suppression s; if (!s.parseComment(comment, &errmsg)) return false; s.type = errorType; s.lineNumber = tok->location.line; if (!s.errorId.empty()) inlineSuppressions.push_back(std::move(s)); if (!errmsg.empty()) bad.emplace_back(tok->location.file(), tok->location.line, std::move(errmsg)); } return true; } static std::string getRelativeFilename(const simplecpp::Token* tok, const Settings &settings) { std::string relativeFilename(tok->location.file()); if (settings.relativePaths) { for (const std::string & basePath : settings.basePaths) { const std::string bp = basePath + "/"; if (relativeFilename.compare(0,bp.size(),bp)==0) { relativeFilename = relativeFilename.substr(bp.size()); } } } return Path::simplifyPath(std::move(relativeFilename)); } static void addInlineSuppressions(const simplecpp::TokenList &tokens, const Settings &settings, SuppressionList &suppressions, std::list<BadInlineSuppression> &bad) { std::list<SuppressionList::Suppression> inlineSuppressionsBlockBegin; bool onlyComments = true; for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) { if (!tok->comment) { onlyComments = false; continue; } std::list<SuppressionList::Suppression> inlineSuppressions; if (!parseInlineSuppressionCommentToken(tok, inlineSuppressions, bad)) continue; if (!sameline(tok->previous, tok)) { // find code after comment.. if (tok->next) { tok = tok->next; while (tok->comment) { parseInlineSuppressionCommentToken(tok, inlineSuppressions, bad); if (tok->next) { tok = tok->next; } else { break; } } } } if (inlineSuppressions.empty()) continue; // It should never happen if (!tok) continue; // Relative filename const std::string relativeFilename = getRelativeFilename(tok, settings); // Macro name std::string macroName; if (tok->str() == "#" && tok->next && tok->next->str() == "define") { const simplecpp::Token *macroNameTok = tok->next->next; if (sameline(tok, macroNameTok) && macroNameTok->name) { macroName = macroNameTok->str(); } } // Add the suppressions. for (SuppressionList::Suppression &suppr : inlineSuppressions) { suppr.fileName = relativeFilename; if (SuppressionList::Type::blockBegin == suppr.type) { inlineSuppressionsBlockBegin.push_back(std::move(suppr)); } else if (SuppressionList::Type::blockEnd == suppr.type) { bool throwError = true; if (!inlineSuppressionsBlockBegin.empty()) { const SuppressionList::Suppression lastBeginSuppression = inlineSuppressionsBlockBegin.back(); auto supprBegin = inlineSuppressionsBlockBegin.begin(); while (supprBegin != inlineSuppressionsBlockBegin.end()) { if (lastBeginSuppression.lineNumber != supprBegin->lineNumber) { ++supprBegin; continue; } if (suppr.symbolName == supprBegin->symbolName && suppr.lineNumber > supprBegin->lineNumber) { suppr.lineBegin = supprBegin->lineNumber; suppr.lineEnd = suppr.lineNumber; suppr.lineNumber = supprBegin->lineNumber; suppr.type = SuppressionList::Type::block; inlineSuppressionsBlockBegin.erase(supprBegin); suppressions.addSuppression(std::move(suppr)); throwError = false; break; } ++supprBegin; } } if (throwError) { // NOLINTNEXTLINE(bugprone-use-after-move) - moved only when thrownError is false bad.emplace_back(suppr.fileName, suppr.lineNumber, "Suppress End: No matching begin"); } } else if (SuppressionList::Type::unique == suppr.type || suppr.type == SuppressionList::Type::macro) { // special handling when suppressing { warnings for backwards compatibility const bool thisAndNextLine = tok->previous && tok->previous->previous && tok->next && !sameline(tok->previous->previous, tok->previous) && tok->location.line + 1 == tok->next->location.line && tok->location.fileIndex == tok->next->location.fileIndex && tok->previous->str() == "{"; suppr.thisAndNextLine = thisAndNextLine; suppr.lineNumber = tok->location.line; suppr.macroName = macroName; suppressions.addSuppression(std::move(suppr)); } else if (SuppressionList::Type::file == suppr.type) { if (onlyComments) suppressions.addSuppression(std::move(suppr)); else bad.emplace_back(suppr.fileName, suppr.lineNumber, "File suppression should be at the top of the file"); } } } for (const SuppressionList::Suppression & suppr: inlineSuppressionsBlockBegin) // cppcheck-suppress useStlAlgorithm bad.emplace_back(suppr.fileName, suppr.lineNumber, "Suppress Begin: No matching end"); } void Preprocessor::inlineSuppressions(const simplecpp::TokenList &tokens, SuppressionList &suppressions) { if (!mSettings.inlineSuppressions) return; std::list<BadInlineSuppression> err; ::addInlineSuppressions(tokens, mSettings, suppressions, err); for (std::map<std::string,simplecpp::TokenList*>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) { if (it->second) ::addInlineSuppressions(*it->second, mSettings, suppressions, err); } for (const BadInlineSuppression &bad : err) { error(bad.file, bad.line, bad.errmsg); } } std::vector<RemarkComment> Preprocessor::getRemarkComments(const simplecpp::TokenList &tokens) const { std::vector<RemarkComment> ret; addRemarkComments(tokens, ret); for (std::map<std::string,simplecpp::TokenList*>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) { if (it->second) addRemarkComments(*it->second, ret); } return ret; } std::list<Directive> Preprocessor::createDirectives(const simplecpp::TokenList &tokens) const { // directive list.. std::list<Directive> directives; std::vector<const simplecpp::TokenList *> list; list.reserve(1U + mTokenLists.size()); list.push_back(&tokens); for (std::map<std::string, simplecpp::TokenList *>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) { list.push_back(it->second); } for (const simplecpp::TokenList *tokenList : list) { for (const simplecpp::Token *tok = tokenList->cfront(); tok; tok = tok->next) { if ((tok->op != '#') || (tok->previous && tok->previous->location.line == tok->location.line)) continue; if (tok->next && tok->next->str() == "endfile") continue; Directive directive(tok->location, emptyString); for (const simplecpp::Token *tok2 = tok; tok2 && tok2->location.line == directive.linenr; tok2 = tok2->next) { if (tok2->comment) continue; if (!directive.str.empty() && (tok2->location.col > tok2->previous->location.col + tok2->previous->str().size())) directive.str += ' '; if (directive.str == "#" && tok2->str() == "file") directive.str += "include"; else directive.str += tok2->str(); directive.strTokens.emplace_back(*tok2); } directives.push_back(std::move(directive)); } } return directives; } static std::string readcondition(const simplecpp::Token *iftok, const std::set<std::string> &defined, const std::set<std::string> &undefined) { const simplecpp::Token *cond = iftok->next; if (!sameline(iftok,cond)) return ""; const simplecpp::Token *next1 = cond->next; const simplecpp::Token *next2 = next1 ? next1->next : nullptr; const simplecpp::Token *next3 = next2 ? next2->next : nullptr; unsigned int len = 1; if (sameline(iftok,next1)) len = 2; if (sameline(iftok,next2)) len = 3; if (sameline(iftok,next3)) len = 4; if (len == 1 && cond->str() == "0") return "0"; if (len == 1 && cond->name) { if (defined.find(cond->str()) == defined.end()) return cond->str(); } if (len == 2 && cond->op == '!' && next1->name) { if (defined.find(next1->str()) == defined.end()) return next1->str() + "=0"; } if (len == 3 && cond->op == '(' && next1->name && next2->op == ')') { if (defined.find(next1->str()) == defined.end() && undefined.find(next1->str()) == undefined.end()) return next1->str(); } if (len == 3 && cond->name && next1->str() == "==" && next2->number) { if (defined.find(cond->str()) == defined.end()) return cond->str() + '=' + cond->next->next->str(); } std::set<std::string> configset; for (; sameline(iftok,cond); cond = cond->next) { if (cond->op == '!') { if (!sameline(iftok,cond->next) || !cond->next->name) break; if (cond->next->str() == "defined") continue; configset.insert(cond->next->str() + "=0"); continue; } if (cond->str() != "defined") continue; const simplecpp::Token *dtok = cond->next; if (!dtok) break; if (dtok->op == '(') dtok = dtok->next; if (sameline(iftok,dtok) && dtok->name && defined.find(dtok->str()) == defined.end() && undefined.find(dtok->str()) == undefined.end()) configset.insert(dtok->str()); } std::string cfgStr; for (const std::string &s : configset) { if (!cfgStr.empty()) cfgStr += ';'; cfgStr += s; } return cfgStr; } static bool hasDefine(const std::string &userDefines, const std::string &cfg) { if (cfg.empty()) { return false; } std::string::size_type pos = 0; while (pos < userDefines.size()) { pos = userDefines.find(cfg, pos); if (pos == std::string::npos) break; const std::string::size_type pos2 = pos + cfg.size(); if ((pos == 0 || userDefines[pos-1U] == ';') && (pos2 == userDefines.size() || userDefines[pos2] == '=')) return true; pos = pos2; } return false; } static std::string cfg(const std::vector<std::string> &configs, const std::string &userDefines) { std::set<std::string> configs2(configs.cbegin(), configs.cend()); std::string ret; for (const std::string &c : configs2) { if (c.empty()) continue; if (c == "0") return ""; if (hasDefine(userDefines, c)) continue; if (!ret.empty()) ret += ';'; ret += c; } return ret; } static bool isUndefined(const std::string &cfg, const std::set<std::string> &undefined) { for (std::string::size_type pos1 = 0U; pos1 < cfg.size();) { const std::string::size_type pos2 = cfg.find(';',pos1); const std::string def = (pos2 == std::string::npos) ? cfg.substr(pos1) : cfg.substr(pos1, pos2 - pos1); const std::string::size_type eq = def.find('='); if (eq == std::string::npos && undefined.find(def) != undefined.end()) return true; if (eq != std::string::npos && undefined.find(def.substr(0,eq)) != undefined.end() && def.substr(eq) != "=0") return true; pos1 = (pos2 == std::string::npos) ? pos2 : pos2 + 1U; } return false; } static bool getConfigsElseIsFalse(const std::vector<std::string> &configs_if, const std::string &userDefines) { return std::any_of(configs_if.cbegin(), configs_if.cend(), [=](const std::string &cfg) { return hasDefine(userDefines, cfg); }); } static const simplecpp::Token *gotoEndIf(const simplecpp::Token *cmdtok) { int level = 0; while (nullptr != (cmdtok = cmdtok->next)) { if (cmdtok->op == '#' && !sameline(cmdtok->previous,cmdtok) && sameline(cmdtok, cmdtok->next)) { if (startsWith(cmdtok->next->str(),"if")) ++level; else if (cmdtok->next->str() == "endif") { --level; if (level < 0) return cmdtok; } } } return nullptr; } static void getConfigs(const simplecpp::TokenList &tokens, std::set<std::string> &defined, const std::string &userDefines, const std::set<std::string> &undefined, std::set<std::string> &ret) { std::vector<std::string> configs_if; std::vector<std::string> configs_ifndef; std::string elseError; for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) { if (tok->op != '#' || sameline(tok->previous, tok)) continue; const simplecpp::Token *cmdtok = tok->next; if (!sameline(tok, cmdtok)) continue; if (cmdtok->str() == "ifdef" || cmdtok->str() == "ifndef" || cmdtok->str() == "if") { std::string config; if (cmdtok->str() == "ifdef" || cmdtok->str() == "ifndef") { const simplecpp::Token *expr1 = cmdtok->next; if (sameline(tok,expr1) && expr1->name && !sameline(tok,expr1->next)) config = expr1->str(); if (defined.find(config) != defined.end()) config.clear(); } else if (cmdtok->str() == "if") { config = readcondition(cmdtok, defined, undefined); } // skip undefined configurations.. if (isUndefined(config, undefined)) config.clear(); bool ifndef = false; if (cmdtok->str() == "ifndef") ifndef = true; else { const std::array<std::string, 6> match{"if", "!", "defined", "(", config, ")"}; std::size_t i = 0; ifndef = true; for (const simplecpp::Token *t = cmdtok; i < match.size(); t = t->next) { if (!t || t->str() != match[i++]) { ifndef = false; break; } } } // include guard.. if (ifndef && tok->location.fileIndex > 0) { bool includeGuard = true; for (const simplecpp::Token *t = tok->previous; t; t = t->previous) { if (t->location.fileIndex == tok->location.fileIndex) { includeGuard = false; break; } } if (includeGuard) { configs_if.emplace_back(/*std::string()*/); configs_ifndef.emplace_back(/*std::string()*/); continue; } } configs_if.push_back((cmdtok->str() == "ifndef") ? std::string() : config); configs_ifndef.push_back((cmdtok->str() == "ifndef") ? std::move(config) : std::string()); ret.insert(cfg(configs_if,userDefines)); } else if (cmdtok->str() == "elif" || cmdtok->str() == "else") { if (getConfigsElseIsFalse(configs_if,userDefines)) { tok = gotoEndIf(tok); if (!tok) break; tok = tok->previous; continue; } if (cmdtok->str() == "else" && cmdtok->next && !sameline(cmdtok,cmdtok->next) && sameline(cmdtok->next, cmdtok->next->next) && cmdtok->next->op == '#' && cmdtok->next->next->str() == "error") { const std::string &ifcfg = cfg(configs_if, userDefines); if (!ifcfg.empty()) { if (!elseError.empty()) elseError += ';'; elseError += ifcfg; } } if (!configs_if.empty()) configs_if.pop_back(); if (cmdtok->str() == "elif") { std::string config = readcondition(cmdtok, defined, undefined); if (isUndefined(config,undefined)) config.clear(); configs_if.push_back(std::move(config)); ret.insert(cfg(configs_if, userDefines)); } else if (!configs_ifndef.empty()) { configs_if.push_back(configs_ifndef.back()); ret.insert(cfg(configs_if, userDefines)); } } else if (cmdtok->str() == "endif" && !sameline(tok, cmdtok->next)) { if (!configs_if.empty()) configs_if.pop_back(); if (!configs_ifndef.empty()) configs_ifndef.pop_back(); } else if (cmdtok->str() == "error") { if (!configs_ifndef.empty() && !configs_ifndef.back().empty()) { if (configs_ifndef.size() == 1U) ret.erase(emptyString); std::vector<std::string> configs(configs_if); configs.push_back(configs_ifndef.back()); ret.erase(cfg(configs, userDefines)); std::set<std::string> temp; temp.swap(ret); for (const std::string &c: temp) { if (c.find(configs_ifndef.back()) != std::string::npos) ret.insert(c); else if (c.empty()) ret.insert(""); else ret.insert(c + ";" + configs_ifndef.back()); } if (!elseError.empty()) elseError += ';'; elseError += cfg(configs_ifndef, userDefines); } if (!configs_if.empty() && !configs_if.back().empty()) { const std::string &last = configs_if.back(); if (last.size() > 2U && last.compare(last.size()-2U,2,"=0") == 0) { std::vector<std::string> configs(configs_if); ret.erase(cfg(configs, userDefines)); configs[configs.size() - 1U] = last.substr(0,last.size()-2U); if (configs.size() == 1U) ret.erase(""); if (!elseError.empty()) elseError += ';'; elseError += cfg(configs, userDefines); } } } else if (cmdtok->str() == "define" && sameline(tok, cmdtok->next) && cmdtok->next->name) { defined.insert(cmdtok->next->str()); } } if (!elseError.empty()) ret.insert(std::move(elseError)); } std::set<std::string> Preprocessor::getConfigs(const simplecpp::TokenList &tokens) const { std::set<std::string> ret = { "" }; if (!tokens.cfront()) return ret; std::set<std::string> defined = { "__cplusplus" }; ::getConfigs(tokens, defined, mSettings.userDefines, mSettings.userUndefs, ret); for (std::map<std::string, simplecpp::TokenList*>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) { if (!mSettings.configurationExcluded(it->first)) ::getConfigs(*(it->second), defined, mSettings.userDefines, mSettings.userUndefs, ret); } return ret; } static void splitcfg(const std::string &cfg, std::list<std::string> &defines, const std::string &defaultValue) { for (std::string::size_type defineStartPos = 0U; defineStartPos < cfg.size();) { const std::string::size_type defineEndPos = cfg.find(';', defineStartPos); std::string def = (defineEndPos == std::string::npos) ? cfg.substr(defineStartPos) : cfg.substr(defineStartPos, defineEndPos - defineStartPos); if (!defaultValue.empty() && def.find('=') == std::string::npos) def += '=' + defaultValue; defines.push_back(std::move(def)); if (defineEndPos == std::string::npos) break; defineStartPos = defineEndPos + 1U; } } static simplecpp::DUI createDUI(const Settings &mSettings, const std::string &cfg, const std::string &filename) { // TODO: make it possible to specify platform-dependent sizes simplecpp::DUI dui; splitcfg(mSettings.userDefines, dui.defines, "1"); if (!cfg.empty()) splitcfg(cfg, dui.defines, emptyString); for (const std::string &def : mSettings.library.defines()) { const std::string::size_type pos = def.find_first_of(" ("); if (pos == std::string::npos) { dui.defines.push_back(def); continue; } std::string s = def; if (s[pos] == ' ') { s[pos] = '='; } else { s[s.find(')')+1] = '='; } dui.defines.push_back(std::move(s)); } dui.undefined = mSettings.userUndefs; // -U dui.includePaths = mSettings.includePaths; // -I dui.includes = mSettings.userIncludes; // --include // TODO: use mSettings.standards.stdValue instead // TODO: error out on unknown language? const Standards::Language lang = Path::identify(filename, mSettings.cppHeaderProbe); if (lang == Standards::Language::CPP) { dui.std = mSettings.standards.getCPP(); splitcfg(mSettings.platform.getLimitsDefines(Standards::getCPP(dui.std)), dui.defines, ""); } else if (lang == Standards::Language::C) { dui.std = mSettings.standards.getC(); splitcfg(mSettings.platform.getLimitsDefines(Standards::getC(dui.std)), dui.defines, ""); } dui.clearIncludeCache = mSettings.clearIncludeCache; return dui; } bool Preprocessor::hasErrors(const simplecpp::Output &output) { switch (output.type) { case simplecpp::Output::ERROR: case simplecpp::Output::INCLUDE_NESTED_TOO_DEEPLY: case simplecpp::Output::SYNTAX_ERROR: case simplecpp::Output::UNHANDLED_CHAR_ERROR: case simplecpp::Output::EXPLICIT_INCLUDE_NOT_FOUND: case simplecpp::Output::FILE_NOT_FOUND: case simplecpp::Output::DUI_ERROR: return true; case simplecpp::Output::WARNING: case simplecpp::Output::MISSING_HEADER: case simplecpp::Output::PORTABILITY_BACKSLASH: break; } return false; } bool Preprocessor::hasErrors(const simplecpp::OutputList &outputList) { const auto it = std::find_if(outputList.cbegin(), outputList.cend(), [](const simplecpp::Output &output) { return hasErrors(output); }); return it != outputList.cend(); } void Preprocessor::handleErrors(const simplecpp::OutputList& outputList, bool throwError) { const bool showerror = (!mSettings.userDefines.empty() && !mSettings.force); reportOutput(outputList, showerror); if (throwError) { const auto it = std::find_if(outputList.cbegin(), outputList.cend(), [](const simplecpp::Output &output){ return hasErrors(output); }); if (it != outputList.cend()) { throw *it; } } } bool Preprocessor::loadFiles(const simplecpp::TokenList &rawtokens, std::vector<std::string> &files) { const simplecpp::DUI dui = createDUI(mSettings, emptyString, files[0]); simplecpp::OutputList outputList; mTokenLists = simplecpp::load(rawtokens, files, dui, &outputList); handleErrors(outputList, false); return !hasErrors(outputList); } void Preprocessor::removeComments(simplecpp::TokenList &tokens) { tokens.removeComments(); for (std::pair<const std::string, simplecpp::TokenList*>& tokenList : mTokenLists) { if (tokenList.second) tokenList.second->removeComments(); } } void Preprocessor::setPlatformInfo(simplecpp::TokenList &tokens, const Settings& settings) { tokens.sizeOfType["bool"] = settings.platform.sizeof_bool; tokens.sizeOfType["short"] = settings.platform.sizeof_short; tokens.sizeOfType["int"] = settings.platform.sizeof_int; tokens.sizeOfType["long"] = settings.platform.sizeof_long; tokens.sizeOfType["long long"] = settings.platform.sizeof_long_long; tokens.sizeOfType["float"] = settings.platform.sizeof_float; tokens.sizeOfType["double"] = settings.platform.sizeof_double; tokens.sizeOfType["long double"] = settings.platform.sizeof_long_double; tokens.sizeOfType["bool *"] = settings.platform.sizeof_pointer; tokens.sizeOfType["short *"] = settings.platform.sizeof_pointer; tokens.sizeOfType["int *"] = settings.platform.sizeof_pointer; tokens.sizeOfType["long *"] = settings.platform.sizeof_pointer; tokens.sizeOfType["long long *"] = settings.platform.sizeof_pointer; tokens.sizeOfType["float *"] = settings.platform.sizeof_pointer; tokens.sizeOfType["double *"] = settings.platform.sizeof_pointer; tokens.sizeOfType["long double *"] = settings.platform.sizeof_pointer; } simplecpp::TokenList Preprocessor::preprocess(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, bool throwError) { const simplecpp::DUI dui = createDUI(mSettings, cfg, files[0]); simplecpp::OutputList outputList; std::list<simplecpp::MacroUsage> macroUsage; std::list<simplecpp::IfCond> ifCond; simplecpp::TokenList tokens2(files); simplecpp::preprocess(tokens2, tokens1, files, mTokenLists, dui, &outputList, &macroUsage, &ifCond); mMacroUsage = std::move(macroUsage); mIfCond = std::move(ifCond); handleErrors(outputList, throwError); tokens2.removeComments(); return tokens2; } std::string Preprocessor::getcode(const simplecpp::TokenList &tokens1, const std::string &cfg, std::vector<std::string> &files, const bool writeLocations) { simplecpp::TokenList tokens2 = preprocess(tokens1, cfg, files, false); unsigned int prevfile = 0; unsigned int line = 1; std::ostringstream ret; for (const simplecpp::Token *tok = tokens2.cfront(); tok; tok = tok->next) { if (writeLocations && tok->location.fileIndex != prevfile) { ret << "\n#line " << tok->location.line << " \"" << tok->location.file() << "\"\n"; prevfile = tok->location.fileIndex; line = tok->location.line; } if (tok->previous && line >= tok->location.line) // #7912 ret << ' '; while (tok->location.line > line) { ret << '\n'; line++; } if (!tok->macro.empty()) ret << Preprocessor::macroChar; ret << tok->str(); } return ret.str(); } void Preprocessor::reportOutput(const simplecpp::OutputList &outputList, bool showerror) { for (const simplecpp::Output &out : outputList) { switch (out.type) { case simplecpp::Output::ERROR: if (!startsWith(out.msg,"#error") || showerror) error(out.location.file(), out.location.line, out.msg); break; case simplecpp::Output::WARNING: case simplecpp::Output::PORTABILITY_BACKSLASH: break; case simplecpp::Output::MISSING_HEADER: { const std::string::size_type pos1 = out.msg.find_first_of("<\""); const std::string::size_type pos2 = out.msg.find_first_of(">\"", pos1 + 1U); if (pos1 < pos2 && pos2 != std::string::npos) missingInclude(out.location.file(), out.location.line, out.msg.substr(pos1+1, pos2-pos1-1), out.msg[pos1] == '\"' ? UserHeader : SystemHeader); } break; case simplecpp::Output::INCLUDE_NESTED_TOO_DEEPLY: case simplecpp::Output::SYNTAX_ERROR: case simplecpp::Output::UNHANDLED_CHAR_ERROR: error(out.location.file(), out.location.line, out.msg); break; case simplecpp::Output::EXPLICIT_INCLUDE_NOT_FOUND: case simplecpp::Output::FILE_NOT_FOUND: case simplecpp::Output::DUI_ERROR: error(emptyString, 0, out.msg); break; } } } void Preprocessor::error(const std::string &filename, unsigned int linenr, const std::string &msg) { std::list<ErrorMessage::FileLocation> locationList; if (!filename.empty()) { std::string file = Path::fromNativeSeparators(filename); if (mSettings.relativePaths) file = Path::getRelativePath(file, mSettings.basePaths); locationList.emplace_back(file, linenr, 0); } mErrorLogger.reportErr(ErrorMessage(std::move(locationList), mFile0, Severity::error, msg, "preprocessorErrorDirective", Certainty::normal)); } // Report that include is missing void Preprocessor::missingInclude(const std::string &filename, unsigned int linenr, const std::string &header, HeaderTypes headerType) { if (!mSettings.checks.isEnabled(Checks::missingInclude)) return; std::list<ErrorMessage::FileLocation> locationList; if (!filename.empty()) { locationList.emplace_back(filename, linenr, 0); } ErrorMessage errmsg(std::move(locationList), mFile0, Severity::information, (headerType==SystemHeader) ? "Include file: <" + header + "> not found. Please note: Cppcheck does not need standard library headers to get proper results." : "Include file: \"" + header + "\" not found.", (headerType==SystemHeader) ? "missingIncludeSystem" : "missingInclude", Certainty::normal); mErrorLogger.reportErr(errmsg); } void Preprocessor::getErrorMessages(ErrorLogger &errorLogger, const Settings &settings) { Preprocessor preprocessor(settings, errorLogger); preprocessor.missingInclude(emptyString, 1, emptyString, UserHeader); preprocessor.missingInclude(emptyString, 1, emptyString, SystemHeader); preprocessor.error(emptyString, 1, "#error message"); // #error .. } void Preprocessor::dump(std::ostream &out) const { // Create a xml dump. if (!mMacroUsage.empty()) { out << " <macro-usage>" << std::endl; for (const simplecpp::MacroUsage &macroUsage: mMacroUsage) { out << " <macro" << " name=\"" << macroUsage.macroName << "\"" << " file=\"" << ErrorLogger::toxml(macroUsage.macroLocation.file()) << "\"" << " line=\"" << macroUsage.macroLocation.line << "\"" << " column=\"" << macroUsage.macroLocation.col << "\"" << " usefile=\"" << ErrorLogger::toxml(macroUsage.useLocation.file()) << "\"" << " useline=\"" << macroUsage.useLocation.line << "\"" << " usecolumn=\"" << macroUsage.useLocation.col << "\"" << " is-known-value=\"" << bool_to_string(macroUsage.macroValueKnown) << "\"" << "/>" << std::endl; } out << " </macro-usage>" << std::endl; } if (!mIfCond.empty()) { out << " <simplecpp-if-cond>" << std::endl; for (const simplecpp::IfCond &ifCond: mIfCond) { out << " <if-cond" << " file=\"" << ErrorLogger::toxml(ifCond.location.file()) << "\"" << " line=\"" << ifCond.location.line << "\"" << " column=\"" << ifCond.location.col << "\"" << " E=\"" << ErrorLogger::toxml(ifCond.E) << "\"" << " result=\"" << ifCond.result << "\"" << "/>" << std::endl; } out << " </simplecpp-if-cond>" << std::endl; } } std::size_t Preprocessor::calculateHash(const simplecpp::TokenList &tokens1, const std::string &toolinfo) const { std::string hashData = toolinfo; for (const simplecpp::Token *tok = tokens1.cfront(); tok; tok = tok->next) { if (!tok->comment) { hashData += tok->str(); hashData += static_cast<char>(tok->location.line); hashData += static_cast<char>(tok->location.col); } } for (std::map<std::string, simplecpp::TokenList *>::const_iterator it = mTokenLists.cbegin(); it != mTokenLists.cend(); ++it) { for (const simplecpp::Token *tok = it->second->cfront(); tok; tok = tok->next) { if (!tok->comment) { hashData += tok->str(); hashData += static_cast<char>(tok->location.line); hashData += static_cast<char>(tok->location.col); } } } return (std::hash<std::string>{})(hashData); } void Preprocessor::simplifyPragmaAsm(simplecpp::TokenList &tokenList) const { Preprocessor::simplifyPragmaAsmPrivate(tokenList); for (const std::pair<const std::string, simplecpp::TokenList*>& list : mTokenLists) { Preprocessor::simplifyPragmaAsmPrivate(*list.second); } } void Preprocessor::simplifyPragmaAsmPrivate(simplecpp::TokenList &tokenList) { // assembler code.. for (simplecpp::Token *tok = tokenList.front(); tok; tok = tok->next) { if (tok->op != '#') continue; if (sameline(tok, tok->previousSkipComments())) continue; const simplecpp::Token * const tok2 = tok->nextSkipComments(); if (!tok2 || !sameline(tok, tok2) || tok2->str() != "pragma") continue; const simplecpp::Token * const tok3 = tok2->nextSkipComments(); if (!tok3 || !sameline(tok, tok3) || tok3->str() != "asm") continue; const simplecpp::Token *endasm = tok3; while ((endasm = endasm->next) != nullptr) { if (endasm->op != '#' || sameline(endasm,endasm->previousSkipComments())) continue; const simplecpp::Token * const endasm2 = endasm->nextSkipComments(); if (!endasm2 || !sameline(endasm, endasm2) || endasm2->str() != "pragma") continue; const simplecpp::Token * const endasm3 = endasm2->nextSkipComments(); if (!endasm3 || !sameline(endasm2, endasm3) || endasm3->str() != "endasm") continue; while (sameline(endasm,endasm3)) endasm = endasm->next; break; } const simplecpp::Token * const tok4 = tok3->next; tok->setstr("asm"); const_cast<simplecpp::Token *>(tok2)->setstr("("); const_cast<simplecpp::Token *>(tok3)->setstr(")"); const_cast<simplecpp::Token *>(tok4)->setstr(";"); while (tok4->next != endasm) tokenList.deleteToken(tok4->next); } } void Preprocessor::addRemarkComments(const simplecpp::TokenList &tokens, std::vector<RemarkComment> &remarkComments) const { for (const simplecpp::Token *tok = tokens.cfront(); tok; tok = tok->next) { if (!tok->comment) continue; const std::string& comment = tok->str(); // is it a remark comment? const std::string::size_type pos1 = comment.find_first_not_of("/* \t"); if (pos1 == std::string::npos) continue; const std::string::size_type pos2 = comment.find_first_of(": \t", pos1); if (pos2 != pos1 + 6 || comment.compare(pos1, 6, "REMARK") != 0) continue; const std::string::size_type pos3 = comment.find_first_not_of(": \t", pos2); if (pos3 == std::string::npos) continue; if (comment.compare(0,2,"/*") == 0 && pos3 + 2 >= tok->str().size()) continue; const std::string::size_type pos4 = (comment.compare(0,2,"/*") == 0) ? comment.size()-2 : comment.size(); const std::string remarkText = comment.substr(pos3, pos4-pos3); // Get remarked token const simplecpp::Token* remarkedToken = nullptr; for (const simplecpp::Token* after = tok->next; after; after = after->next) { if (after->comment) continue; remarkedToken = after; break; } for (const simplecpp::Token* prev = tok->previous; prev; prev = prev->previous) { if (prev->comment) continue; if (sameline(prev, tok)) remarkedToken = prev; break; } // Relative filename const std::string relativeFilename = getRelativeFilename(remarkedToken, mSettings); // Add the suppressions. remarkComments.emplace_back(relativeFilename, remarkedToken->location.line, remarkText); } }
42,924
C++
.cpp
958
34.822547
190
0.578388
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,120
checkfunctions.cpp
danmar_cppcheck/lib/checkfunctions.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- // Check functions //--------------------------------------------------------------------------- #include "checkfunctions.h" #include "astutils.h" #include "mathlib.h" #include "platform.h" #include "standards.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "valueflow.h" #include "vfvalue.h" #include <iomanip> #include <list> #include <sstream> #include <unordered_map> #include <vector> //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckFunctions instance; } static const CWE CWE252(252U); // Unchecked Return Value static const CWE CWE477(477U); // Use of Obsolete Functions static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments static const CWE CWE686(686U); // Function Call With Incorrect Argument Type static const CWE CWE687(687U); // Function Call With Incorrectly Specified Argument Value static const CWE CWE688(688U); // Function Call With Incorrect Variable or Reference as Argument void CheckFunctions::checkProhibitedFunctions() { const bool checkAlloca = mSettings->severity.isEnabled(Severity::warning) && ((mTokenizer->isC() && mSettings->standards.c >= Standards::C99) || mSettings->standards.cpp >= Standards::CPP11); logChecker("CheckFunctions::checkProhibitedFunctions"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "%name% (") && tok->varId() == 0) continue; // alloca() is special as it depends on the code being C or C++, so it is not in Library if (checkAlloca && Token::simpleMatch(tok, "alloca (") && (!tok->function() || tok->function()->nestedIn->type == Scope::eGlobal)) { if (tok->isC()) { if (mSettings->standards.c > Standards::C89) reportError(tok, Severity::warning, "allocaCalled", "$symbol:alloca\n" "Obsolete function 'alloca' called. In C99 and later it is recommended to use a variable length array instead.\n" "The obsolete function 'alloca' is called. In C99 and later it is recommended to use a variable length array or " "a dynamically allocated array instead. The function 'alloca' is dangerous for many reasons " "(http://stackoverflow.com/questions/1018853/why-is-alloca-not-considered-good-practice and http://linux.die.net/man/3/alloca)."); } else reportError(tok, Severity::warning, "allocaCalled", "$symbol:alloca\n" "Obsolete function 'alloca' called.\n" "The obsolete function 'alloca' is called. In C++11 and later it is recommended to use std::array<> or " "a dynamically allocated array instead. The function 'alloca' is dangerous for many reasons " "(http://stackoverflow.com/questions/1018853/why-is-alloca-not-considered-good-practice and http://linux.die.net/man/3/alloca)."); } else { if (tok->function() && tok->function()->hasBody()) continue; const Library::WarnInfo* wi = mSettings->library.getWarnInfo(tok); if (wi) { if (mSettings->severity.isEnabled(wi->severity) && ((tok->isC() && mSettings->standards.c >= wi->standards.c) || (tok->isCpp() && mSettings->standards.cpp >= wi->standards.cpp))) { const std::string daca = mSettings->daca ? "prohibited" : ""; reportError(tok, wi->severity, daca + tok->str() + "Called", wi->message, CWE477, Certainty::normal); } } } } } } //--------------------------------------------------------------------------- // Check <valid>, <strz> and <not-bool> //--------------------------------------------------------------------------- void CheckFunctions::invalidFunctionUsage() { logChecker("CheckFunctions::invalidFunctionUsage"); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "%name% ( !!)")) continue; const Token * const functionToken = tok; const std::vector<const Token *> arguments = getArguments(tok); for (int argnr = 1; argnr <= arguments.size(); ++argnr) { const Token * const argtok = arguments[argnr-1]; // check <valid>...</valid> const ValueFlow::Value *invalidValue = argtok->getInvalidValue(functionToken,argnr,*mSettings); if (invalidValue) { invalidFunctionArgError(argtok, functionToken->next()->astOperand1()->expressionString(), argnr, invalidValue, mSettings->library.validarg(functionToken, argnr)); } if (astIsBool(argtok)) { // check <not-bool> if (mSettings->library.isboolargbad(functionToken, argnr)) invalidFunctionArgBoolError(argtok, functionToken->str(), argnr); // Are the values 0 and 1 valid? else if (!mSettings->library.isIntArgValid(functionToken, argnr, 0)) invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, mSettings->library.validarg(functionToken, argnr)); else if (!mSettings->library.isIntArgValid(functionToken, argnr, 1)) invalidFunctionArgError(argtok, functionToken->str(), argnr, nullptr, mSettings->library.validarg(functionToken, argnr)); } // check <strz> if (mSettings->library.isargstrz(functionToken, argnr)) { if (Token::Match(argtok, "& %var% !![") && argtok->next() && argtok->next()->valueType()) { const ValueType * valueType = argtok->next()->valueType(); const Variable * variable = argtok->next()->variable(); if ((valueType->type == ValueType::Type::CHAR || valueType->type == ValueType::Type::WCHAR_T || (valueType->type == ValueType::Type::RECORD && Token::Match(argtok, "& %var% . %var% ,|)"))) && !variable->isArray() && (variable->isConst() || !variable->isGlobal()) && (!argtok->next()->hasKnownValue() || argtok->next()->getValue(0) == nullptr)) { invalidFunctionArgStrError(argtok, functionToken->str(), argnr); } } const ValueType* const valueType = argtok->valueType(); const Variable* const variable = argtok->variable(); // Is non-null terminated local variable of type char (e.g. char buf[] = {'x'};) ? if (variable && variable->isLocal() && valueType && (valueType->type == ValueType::Type::CHAR || valueType->type == ValueType::Type::WCHAR_T) && !isVariablesChanged(variable->declEndToken(), functionToken, 0 /*indirect*/, { variable }, *mSettings)) { const Token* varTok = variable->declEndToken(); auto count = -1; // Find out explicitly set count, e.g.: char buf[3] = {...}. Variable 'count' is set to 3 then. if (varTok && Token::simpleMatch(varTok->astOperand1(), "[")) { const Token* const countTok = varTok->astOperand1()->astOperand2(); if (countTok && countTok->hasKnownIntValue()) count = countTok->getKnownIntValue(); } if (Token::simpleMatch(varTok, "= {")) { varTok = varTok->tokAt(1); auto charsUntilFirstZero = 0; bool search = true; while (search && varTok && !Token::simpleMatch(varTok->next(), "}")) { varTok = varTok->next(); if (!Token::simpleMatch(varTok, ",")) { if (Token::Match(varTok, "%op%")) { varTok = varTok->next(); continue; } ++charsUntilFirstZero; if (varTok && varTok->hasKnownIntValue() && varTok->getKnownIntValue() == 0) search=false; // stop counting for cases like char buf[3] = {'x', '\0', 'y'}; } } if (varTok && varTok->hasKnownIntValue() && varTok->getKnownIntValue() != 0 && (count == -1 || (count > 0 && count <= charsUntilFirstZero))) { invalidFunctionArgStrError(argtok, functionToken->str(), argnr); } } else if (count > -1 && Token::Match(varTok, "= %str%")) { const Token* strTok = varTok->getValueTokenMinStrSize(*mSettings); if (strTok) { const int strSize = Token::getStrArraySize(strTok); if (strSize > count && strTok->str().find('\0') == std::string::npos) invalidFunctionArgStrError(argtok, functionToken->str(), argnr); } } } } } } } } void CheckFunctions::invalidFunctionArgError(const Token *tok, const std::string &functionName, int argnr, const ValueFlow::Value *invalidValue, const std::string &validstr) { std::ostringstream errmsg; errmsg << "$symbol:" << functionName << '\n'; if (invalidValue && invalidValue->condition) errmsg << ValueFlow::eitherTheConditionIsRedundant(invalidValue->condition) << " or $symbol() argument nr " << argnr << " can have invalid value."; else errmsg << "Invalid $symbol() argument nr " << argnr << '.'; if (invalidValue) errmsg << " The value is " << std::setprecision(10) << (invalidValue->isIntValue() ? invalidValue->intvalue : invalidValue->floatValue) << " but the valid values are '" << validstr << "'."; else errmsg << " The value is 0 or 1 (boolean) but the valid values are '" << validstr << "'."; if (invalidValue) reportError(getErrorPath(tok, invalidValue, "Invalid argument"), invalidValue->errorSeverity() && invalidValue->isKnown() ? Severity::error : Severity::warning, "invalidFunctionArg", errmsg.str(), CWE628, invalidValue->isInconclusive() ? Certainty::inconclusive : Certainty::normal); else reportError(tok, Severity::error, "invalidFunctionArg", errmsg.str(), CWE628, Certainty::normal); } void CheckFunctions::invalidFunctionArgBoolError(const Token *tok, const std::string &functionName, int argnr) { std::ostringstream errmsg; errmsg << "$symbol:" << functionName << '\n'; errmsg << "Invalid $symbol() argument nr " << argnr << ". A non-boolean value is required."; reportError(tok, Severity::error, "invalidFunctionArgBool", errmsg.str(), CWE628, Certainty::normal); } void CheckFunctions::invalidFunctionArgStrError(const Token *tok, const std::string &functionName, nonneg int argnr) { std::ostringstream errmsg; errmsg << "$symbol:" << functionName << '\n'; errmsg << "Invalid $symbol() argument nr " << argnr << ". A nul-terminated string is required."; reportError(tok, Severity::error, "invalidFunctionArgStr", errmsg.str(), CWE628, Certainty::normal); } //--------------------------------------------------------------------------- // Check for ignored return values. //--------------------------------------------------------------------------- void CheckFunctions::checkIgnoredReturnValue() { if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("ignoredReturnValue")) return; logChecker("CheckFunctions::checkIgnoredReturnValue"); // style,warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { // skip c++11 initialization, ({...}) if (Token::Match(tok, "%var%|(|,|return {")) tok = tok->linkAt(1); else if (Token::Match(tok, "[(<]") && tok->link()) tok = tok->link(); if (tok->varId() || tok->isKeyword() || tok->isStandardType() || !Token::Match(tok, "%name% (")) continue; const Token *parent = tok->next()->astParent(); while (Token::Match(parent, "%cop%")) { if (Token::Match(parent, "<<|>>|*") && !parent->astParent()) break; parent = parent->astParent(); } if (parent) continue; if (!tok->scope()->isExecutable()) { tok = tok->scope()->bodyEnd; continue; } if ((!tok->function() || !Token::Match(tok->function()->retDef, "void %name%")) && tok->next()->astOperand1()) { const Library::UseRetValType retvalTy = mSettings->library.getUseRetValType(tok); const bool warn = (tok->function() && (tok->function()->isAttributeNodiscard() || tok->function()->isAttributePure() || tok->function()->isAttributeConst())) || // avoid duplicate warnings for resource-allocating functions (retvalTy == Library::UseRetValType::DEFAULT && mSettings->library.getAllocFuncInfo(tok) == nullptr); if (mSettings->severity.isEnabled(Severity::warning) && warn) ignoredReturnValueError(tok, tok->next()->astOperand1()->expressionString()); else if (mSettings->severity.isEnabled(Severity::style) && retvalTy == Library::UseRetValType::ERROR_CODE) ignoredReturnErrorCode(tok, tok->next()->astOperand1()->expressionString()); } } } } void CheckFunctions::ignoredReturnValueError(const Token* tok, const std::string& function) { reportError(tok, Severity::warning, "ignoredReturnValue", "$symbol:" + function + "\nReturn value of function $symbol() is not used.", CWE252, Certainty::normal); } void CheckFunctions::ignoredReturnErrorCode(const Token* tok, const std::string& function) { reportError(tok, Severity::style, "ignoredReturnErrorCode", "$symbol:" + function + "\nError code from the return value of function $symbol() is not used.", CWE252, Certainty::normal); } //--------------------------------------------------------------------------- // Check for ignored return values. //--------------------------------------------------------------------------- static const Token *checkMissingReturnScope(const Token *tok, const Library &library); void CheckFunctions::checkMissingReturn() { logChecker("CheckFunctions::checkMissingReturn"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { const Function *function = scope->function; if (!function || !function->hasBody()) continue; if (function->name() == "main" && !(mTokenizer->isC() && mSettings->standards.c < Standards::C99)) continue; if (function->type != Function::Type::eFunction && function->type != Function::Type::eOperatorEqual) continue; if (Token::Match(function->retDef, "%name% (") && function->retDef->isUpperCaseName()) continue; if (Function::returnsVoid(function, true)) continue; const Token *errorToken = checkMissingReturnScope(scope->bodyEnd, mSettings->library); if (errorToken) missingReturnError(errorToken); } } static bool isForwardJump(const Token *gotoToken) { if (!Token::Match(gotoToken, "goto %name% ;")) return false; for (const Token *prev = gotoToken; gotoToken; gotoToken = gotoToken->previous()) { if (Token::Match(prev, "%name% :") && prev->str() == gotoToken->strAt(1)) return true; if (prev->str() == "{" && prev->scope()->type == Scope::eFunction) return false; } return false; } static const Token *checkMissingReturnScope(const Token *tok, const Library &library) { const Token *lastStatement = nullptr; while ((tok = tok->previous()) != nullptr) { if (tok->str() == ")") tok = tok->link(); if (tok->str() == "{") return lastStatement ? lastStatement : tok->next(); if (tok->str() == "}") { for (const Token *prev = tok->link()->previous(); prev && prev->scope() == tok->scope() && !Token::Match(prev, "[;{}]"); prev = prev->previous()) { if (prev->isKeyword() && Token::Match(prev, "return|throw")) return nullptr; if (prev->str() == "goto" && !isForwardJump(prev)) return nullptr; } if (tok->scope()->type == Scope::ScopeType::eSwitch) { bool reachable = false; for (const Token *switchToken = tok->link()->next(); switchToken != tok; switchToken = switchToken->next()) { if (reachable && Token::simpleMatch(switchToken, "break ;")) { if (Token::simpleMatch(switchToken->previous(), "}") && !checkMissingReturnScope(switchToken->previous(), library)) reachable = false; else return switchToken; } if (switchToken->isKeyword() && Token::Match(switchToken, "return|throw")) reachable = false; if (Token::Match(switchToken, "%name% (") && library.isnoreturn(switchToken)) reachable = false; if (Token::Match(switchToken, "case|default")) reachable = true; else if (switchToken->str() == "{" && (switchToken->scope()->isLoopScope() || switchToken->scope()->type == Scope::ScopeType::eSwitch)) switchToken = switchToken->link(); } if (!isExhaustiveSwitch(tok->link())) return tok->link(); } else if (tok->scope()->type == Scope::ScopeType::eIf) { const Token *condition = tok->scope()->classDef->next()->astOperand2(); if (condition && condition->hasKnownIntValue() && condition->getKnownIntValue() == 1) return checkMissingReturnScope(tok, library); return tok; } else if (tok->scope()->type == Scope::ScopeType::eElse) { const Token *errorToken = checkMissingReturnScope(tok, library); if (errorToken) return errorToken; tok = tok->link(); if (Token::simpleMatch(tok->tokAt(-2), "} else {")) return checkMissingReturnScope(tok->tokAt(-2), library); return tok; } // FIXME return nullptr; } if (tok->isKeyword() && Token::Match(tok, "return|throw")) return nullptr; if (tok->str() == "goto" && !isForwardJump(tok)) return nullptr; if (Token::Match(tok, "%name% (") && library.isnoreturn(tok)) { return nullptr; } if (Token::Match(tok->previous(), "[;{}] %name% (") && !library.isnotnoreturn(tok)) { return nullptr; } if (Token::Match(tok, "[;{}] %name% :")) return tok; if (Token::Match(tok, "; !!}") && !lastStatement) lastStatement = tok->next(); } return nullptr; } void CheckFunctions::missingReturnError(const Token* tok) { reportError(tok, Severity::error, "missingReturn", "Found an exit path from function with non-void return type that has missing return statement", CWE758, Certainty::normal); } //--------------------------------------------------------------------------- // Detect passing wrong values to <cmath> functions like atan(0, x); //--------------------------------------------------------------------------- void CheckFunctions::checkMathFunctions() { const bool styleC99 = mSettings->severity.isEnabled(Severity::style) && ((mTokenizer->isC() && mSettings->standards.c != Standards::C89) || (mTokenizer->isCPP() && mSettings->standards.cpp != Standards::CPP03)); const bool printWarnings = mSettings->severity.isEnabled(Severity::warning); if (!styleC99 && !printWarnings && !mSettings->isPremiumEnabled("wrongmathcall")) return; logChecker("CheckFunctions::checkMathFunctions"); // style,warning,c99,c++11 const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (tok->varId()) continue; if (printWarnings && Token::Match(tok, "%name% ( !!)")) { if (tok->strAt(-1) != "." && Token::Match(tok, "log|logf|logl|log10|log10f|log10l|log2|log2f|log2l ( %num% )")) { const std::string& number = tok->strAt(2); if ((MathLib::isInt(number) && MathLib::toBigNumber(number) <= 0) || (MathLib::isFloat(number) && MathLib::toDoubleNumber(number) <= 0.)) mathfunctionCallWarning(tok); } else if (Token::Match(tok, "log1p|log1pf|log1pl ( %num% )")) { const std::string& number = tok->strAt(2); if ((MathLib::isInt(number) && MathLib::toBigNumber(number) <= -1) || (MathLib::isFloat(number) && MathLib::toDoubleNumber(number) <= -1.)) mathfunctionCallWarning(tok); } // atan2 ( x , y): x and y can not be zero, because this is mathematically not defined else if (Token::Match(tok, "atan2|atan2f|atan2l ( %num% , %num% )")) { if (MathLib::isNullValue(tok->strAt(2)) && MathLib::isNullValue(tok->strAt(4))) mathfunctionCallWarning(tok, 2); } // fmod ( x , y) If y is zero, then either a range error will occur or the function will return zero (implementation-defined). else if (Token::Match(tok, "fmod|fmodf|fmodl (")) { const Token* nextArg = tok->tokAt(2)->nextArgument(); if (nextArg && MathLib::isNullValue(nextArg->str())) mathfunctionCallWarning(tok, 2); } // pow ( x , y) If x is zero, and y is negative --> division by zero else if (Token::Match(tok, "pow|powf|powl ( %num% , %num% )")) { if (MathLib::isNullValue(tok->strAt(2)) && MathLib::isNegative(tok->strAt(4))) mathfunctionCallWarning(tok, 2); } } if (styleC99) { if (Token::Match(tok, "%num% - erf (") && Tokenizer::isOneNumber(tok->str()) && tok->next()->astOperand2() == tok->tokAt(3)) { mathfunctionCallWarning(tok, "1 - erf(x)", "erfc(x)"); } else if (Token::simpleMatch(tok, "exp (") && Token::Match(tok->linkAt(1), ") - %num%") && Tokenizer::isOneNumber(tok->linkAt(1)->strAt(2)) && tok->linkAt(1)->next()->astOperand1() == tok->next()) { mathfunctionCallWarning(tok, "exp(x) - 1", "expm1(x)"); } else if (Token::simpleMatch(tok, "log (") && tok->next()->astOperand2()) { const Token* plus = tok->next()->astOperand2(); if (plus->str() == "+" && ((plus->astOperand1() && Tokenizer::isOneNumber(plus->astOperand1()->str())) || (plus->astOperand2() && Tokenizer::isOneNumber(plus->astOperand2()->str())))) mathfunctionCallWarning(tok, "log(1 + x)", "log1p(x)"); } } } } } void CheckFunctions::mathfunctionCallWarning(const Token *tok, const nonneg int numParam) { if (tok) { if (numParam == 1) reportError(tok, Severity::warning, "wrongmathcall", "$symbol:" + tok->str() + "\nPassing value " + tok->strAt(2) + " to $symbol() leads to implementation-defined result.", CWE758, Certainty::normal); else if (numParam == 2) reportError(tok, Severity::warning, "wrongmathcall", "$symbol:" + tok->str() + "\nPassing values " + tok->strAt(2) + " and " + tok->strAt(4) + " to $symbol() leads to implementation-defined result.", CWE758, Certainty::normal); } else reportError(tok, Severity::warning, "wrongmathcall", "Passing value '#' to #() leads to implementation-defined result.", CWE758, Certainty::normal); } void CheckFunctions::mathfunctionCallWarning(const Token *tok, const std::string& oldexp, const std::string& newexp) { reportError(tok, Severity::style, "unpreciseMathCall", "Expression '" + oldexp + "' can be replaced by '" + newexp + "' to avoid loss of precision.", CWE758, Certainty::normal); } //--------------------------------------------------------------------------- // memset(p, y, 0 /* bytes to fill */) <- 2nd and 3rd arguments inverted //--------------------------------------------------------------------------- void CheckFunctions::memsetZeroBytes() { // FIXME: // Replace this with library configuration. // For instance: // <arg nr="3"> // <warn knownIntValue="0" severity="warning" msg="..."/> // </arg> if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckFunctions::memsetZeroBytes"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "memset|wmemset (") && (numberOfArguments(tok)==3)) { const std::vector<const Token *> &arguments = getArguments(tok); if (WRONG_DATA(arguments.size() != 3U, tok)) continue; const Token* lastParamTok = arguments[2]; if (MathLib::isNullValue(lastParamTok->str())) memsetZeroBytesError(tok); } } } } void CheckFunctions::memsetZeroBytesError(const Token *tok) { const std::string summary("memset() called to fill 0 bytes."); const std::string verbose(summary + " The second and third arguments might be inverted." " The function memset ( void * ptr, int value, size_t num ) sets the" " first num bytes of the block of memory pointed by ptr to the specified value."); reportError(tok, Severity::warning, "memsetZeroBytes", summary + "\n" + verbose, CWE687, Certainty::normal); } void CheckFunctions::memsetInvalid2ndParam() { // FIXME: // Replace this with library configuration. // For instance: // <arg nr="2"> // <not-float/> // <warn possibleIntValue=":-129,256:" severity="warning" msg="..."/> // </arg> const bool printPortability = mSettings->severity.isEnabled(Severity::portability); const bool printWarning = mSettings->severity.isEnabled(Severity::warning); if (!printWarning && !printPortability) return; logChecker("CheckFunctions::memsetInvalid2ndParam"); // warning,portability const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok && (tok != scope->bodyEnd); tok = tok->next()) { if (!Token::simpleMatch(tok, "memset (")) continue; const std::vector<const Token *> args = getArguments(tok); if (args.size() != 3) continue; // Second parameter is zero literal, i.e. 0.0f const Token * const secondParamTok = args[1]; if (Token::Match(secondParamTok, "%num% ,") && MathLib::isNullValue(secondParamTok->str())) continue; // Check if second parameter is a float variable or a float literal != 0.0f if (printPortability && astIsFloat(secondParamTok,false)) { memsetFloatError(secondParamTok, secondParamTok->expressionString()); } if (printWarning && secondParamTok->isNumber()) { // Check if the second parameter is a literal and is out of range const long long int value = MathLib::toBigNumber(secondParamTok->str()); const long long sCharMin = mSettings->platform.signedCharMin(); const long long uCharMax = mSettings->platform.unsignedCharMax(); if (value < sCharMin || value > uCharMax) memsetValueOutOfRangeError(secondParamTok, secondParamTok->str()); } } } } void CheckFunctions::memsetFloatError(const Token *tok, const std::string &var_value) { const std::string message("The 2nd memset() argument '" + var_value + "' is a float, its representation is implementation defined."); const std::string verbose(message + " memset() is used to set each byte of a block of memory to a specific value and" " the actual representation of a floating-point value is implementation defined."); reportError(tok, Severity::portability, "memsetFloat", message + "\n" + verbose, CWE688, Certainty::normal); } void CheckFunctions::memsetValueOutOfRangeError(const Token *tok, const std::string &value) { const std::string message("The 2nd memset() argument '" + value + "' doesn't fit into an 'unsigned char'."); const std::string verbose(message + " The 2nd parameter is passed as an 'int', but the function fills the block of memory using the 'unsigned char' conversion of this value."); reportError(tok, Severity::warning, "memsetValueOutOfRange", message + "\n" + verbose, CWE686, Certainty::normal); } //--------------------------------------------------------------------------- // --check-library => warn for unconfigured functions //--------------------------------------------------------------------------- void CheckFunctions::checkLibraryMatchFunctions() { if (!mSettings->checkLibrary) return; bool insideNew = false; for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (!tok->scope() || !tok->scope()->isExecutable()) continue; if (tok->str() == "new") insideNew = true; else if (tok->str() == ";") insideNew = false; else if (insideNew) continue; if (tok->isKeyword() || !Token::Match(tok, "%name% (")) continue; if (tok->varId() != 0 || tok->type() || tok->isStandardType()) continue; if (tok->linkAt(1)->strAt(1) == "(") continue; if (tok->function()) continue; if (Token::simpleMatch(tok->astTop(), "throw")) continue; if (Token::simpleMatch(tok->astParent(), ".")) { const Token* contTok = tok->astParent()->astOperand1(); if (astContainerAction(contTok, nullptr, mSettings) != Library::Container::Action::NO_ACTION) continue; if (astContainerYield(contTok, nullptr, mSettings) != Library::Container::Yield::NO_YIELD) continue; } if (!mSettings->library.isNotLibraryFunction(tok)) continue; const std::string &functionName = mSettings->library.getFunctionName(tok); if (functionName.empty()) continue; if (mSettings->library.functions().find(functionName) != mSettings->library.functions().end()) continue; if (mSettings->library.podtype(tok->expressionString())) continue; if (mSettings->library.getTypeCheck("unusedvar", functionName) != Library::TypeCheck::def) continue; const Token* start = tok; while (Token::Match(start->tokAt(-2), "%name% ::") && !start->tokAt(-2)->isKeyword()) start = start->tokAt(-2); if (mSettings->library.detectContainerOrIterator(start)) continue; reportError(tok, Severity::information, "checkLibraryFunction", "--check-library: There is no matching configuration for function " + functionName + "()"); } } // Check for problems to compiler apply (Named) Return Value Optimization for local variable // Technically we have different guarantees between standard versions // details: https://en.cppreference.com/w/cpp/language/copy_elision void CheckFunctions::returnLocalStdMove() { if (!mTokenizer->isCPP() || mSettings->standards.cpp < Standards::CPP11) return; if (!mSettings->severity.isEnabled(Severity::performance)) return; logChecker("CheckFunctions::returnLocalStdMove"); // performance,c++11 const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { // Expect return by-value if (Function::returnsReference(scope->function, /*unknown*/ true, /*includeRValueRef*/ true)) continue; const auto rets = Function::findReturns(scope->function); for (const Token* ret : rets) { if (!Token::simpleMatch(ret->tokAt(-3), "std :: move (")) continue; const Token* retval = ret->astOperand2(); // NRVO if (retval->variable() && retval->variable()->isLocal() && !retval->variable()->isVolatile()) copyElisionError(retval); // RVO if (Token::Match(retval, "(|{") && !retval->isCast() && !(retval->valueType() && retval->valueType()->reference != Reference::None)) copyElisionError(retval); } } } void CheckFunctions::copyElisionError(const Token *tok) { reportError(tok, Severity::performance, "returnStdMoveLocal", "Using std::move for returning object by-value from function will affect copy elision optimization." " More: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-return-move-local"); } void CheckFunctions::useStandardLibrary() { if (!mSettings->severity.isEnabled(Severity::style)) return; logChecker("CheckFunctions::useStandardLibrary"); // style for (const Scope& scope: mTokenizer->getSymbolDatabase()->scopeList) { if (scope.type != Scope::ScopeType::eFor) continue; const Token *forToken = scope.classDef; // for ( initToken ; condToken ; stepToken ) const Token* initToken = getInitTok(forToken); if (!initToken) continue; const Token* condToken = getCondTok(forToken); if (!condToken) continue; const Token* stepToken = getStepTok(forToken); if (!stepToken) continue; // 1. we expect that idx variable will be initialized with 0 const Token* idxToken = initToken->astOperand1(); const Token* initVal = initToken->astOperand2(); if (!idxToken || !initVal || !initVal->hasKnownIntValue() || initVal->getKnownIntValue() != 0) continue; const auto idxVarId = idxToken->varId(); if (0 == idxVarId) continue; // 2. we expect that idx will be less of some variable if (!condToken->isComparisonOp()) continue; const auto& secondOp = condToken->str(); const bool isLess = "<" == secondOp && isConstExpression(condToken->astOperand2(), mSettings->library) && condToken->astOperand1()->varId() == idxVarId; const bool isMore = ">" == secondOp && isConstExpression(condToken->astOperand1(), mSettings->library) && condToken->astOperand2()->varId() == idxVarId; if (!(isLess || isMore)) continue; // 3. we expect idx incrementing by 1 const bool inc = stepToken->str() == "++" && stepToken->astOperand1() && stepToken->astOperand1()->varId() == idxVarId; const bool plusOne = stepToken->isBinaryOp() && stepToken->str() == "+=" && stepToken->astOperand1()->varId() == idxVarId && stepToken->astOperand2()->str() == "1"; if (!inc && !plusOne) continue; // technically using void* here is not correct but some compilers could allow it const Token *tok = scope.bodyStart; const std::string memcpyName = tok->isCpp() ? "std::memcpy" : "memcpy"; // (reinterpret_cast<uint8_t*>(dest))[i] = (reinterpret_cast<const uint8_t*>(src))[i]; if (Token::Match(tok, "{ (| reinterpret_cast < uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] = " "(| reinterpret_cast < const| uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] ; }", idxVarId)) { useStandardLibraryError(tok->next(), memcpyName); continue; } // ((char*)dst)[i] = ((const char*)src)[i]; if (Token::Match(tok, "{ ( ( uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] = " "( ( const| uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] ; }", idxVarId)) { useStandardLibraryError(tok->next(), memcpyName); continue; } const static std::string memsetName = tok->isCpp() ? "std::memset" : "memset"; // ((char*)dst)[i] = 0; if (Token::Match(tok, "{ ( ( uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] = %char%|%num% ; }", idxVarId)) { useStandardLibraryError(tok->next(), memsetName); continue; } // ((char*)dst)[i] = (const char*)0; if (Token::Match(tok, "{ ( ( uint8_t|int8_t|char|void * ) (| %var% ) )| [ %varid% ] = " "( const| uint8_t|int8_t|char ) (| %char%|%num% )| ; }", idxVarId)) { useStandardLibraryError(tok->next(), memsetName); continue; } // (reinterpret_cast<uint8_t*>(dest))[i] = static_cast<const uint8_t>(0); if (Token::Match(tok, "{ (| reinterpret_cast < uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] = " "(| static_cast < const| uint8_t|int8_t|char > ( %char%|%num% ) )| ; }", idxVarId)) { useStandardLibraryError(tok->next(), memsetName); continue; } // (reinterpret_cast<int8_t*>(dest))[i] = 0; if (Token::Match(tok, "{ (| reinterpret_cast < uint8_t|int8_t|char|void * > ( %var% ) )| [ %varid% ] = " "%char%|%num% ; }", idxVarId)) { useStandardLibraryError(tok->next(), memsetName); continue; } } } void CheckFunctions::useStandardLibraryError(const Token *tok, const std::string& expected) { reportError(tok, Severity::style, "useStandardLibrary", "Consider using " + expected + " instead of loop."); }
41,991
C++
.cpp
736
44.855978
239
0.558077
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,121
programmemory.cpp
danmar_cppcheck/lib/programmemory.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "programmemory.h" #include "astutils.h" #include "calculate.h" #include "infer.h" #include "library.h" #include "mathlib.h" #include "settings.h" #include "standards.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "utils.h" #include "valueflow.h" #include "valueptr.h" #include <algorithm> #include <cassert> #include <cmath> #include <functional> #include <iterator> #include <list> #include <memory> #include <stack> #include <sstream> #include <string> #include <utility> #include <vector> ExprIdToken::ExprIdToken(const Token* tok) : tok(tok), exprid(tok ? tok->exprId() : 0) {} nonneg int ExprIdToken::getExpressionId() const { return tok ? tok->exprId() : exprid; } std::size_t ExprIdToken::Hash::operator()(ExprIdToken etok) const { return std::hash<nonneg int>()(etok.getExpressionId()); } void ProgramMemory::setValue(const Token* expr, const ValueFlow::Value& value) { copyOnWrite(); (*mValues)[expr] = value; ValueFlow::Value subvalue = value; const Token* subexpr = solveExprValue( expr, [&](const Token* tok) -> std::vector<MathLib::bigint> { if (tok->hasKnownIntValue()) return {tok->values().front().intvalue}; MathLib::bigint result = 0; if (getIntValue(tok->exprId(), result)) return {result}; return {}; }, subvalue); if (subexpr) (*mValues)[subexpr] = std::move(subvalue); } const ValueFlow::Value* ProgramMemory::getValue(nonneg int exprid, bool impossible) const { const ProgramMemory::Map::const_iterator it = mValues->find(exprid); const bool found = it != mValues->cend() && (impossible || !it->second.isImpossible()); if (found) return &it->second; return nullptr; } // cppcheck-suppress unusedFunction bool ProgramMemory::getIntValue(nonneg int exprid, MathLib::bigint& result) const { const ValueFlow::Value* value = getValue(exprid); if (value && value->isIntValue()) { result = value->intvalue; return true; } return false; } void ProgramMemory::setIntValue(const Token* expr, MathLib::bigint value, bool impossible) { ValueFlow::Value v(value); if (impossible) v.setImpossible(); setValue(expr, v); } bool ProgramMemory::getTokValue(nonneg int exprid, const Token*& result) const { const ValueFlow::Value* value = getValue(exprid); if (value && value->isTokValue()) { result = value->tokvalue; return true; } return false; } // cppcheck-suppress unusedFunction bool ProgramMemory::getContainerSizeValue(nonneg int exprid, MathLib::bigint& result) const { const ValueFlow::Value* value = getValue(exprid); if (value && value->isContainerSizeValue()) { result = value->intvalue; return true; } return false; } bool ProgramMemory::getContainerEmptyValue(nonneg int exprid, MathLib::bigint& result) const { const ValueFlow::Value* value = getValue(exprid, true); if (value && value->isContainerSizeValue()) { if (value->isImpossible() && value->intvalue == 0) { result = false; return true; } if (!value->isImpossible()) { result = (value->intvalue == 0); return true; } } return false; } void ProgramMemory::setContainerSizeValue(const Token* expr, MathLib::bigint value, bool isEqual) { ValueFlow::Value v(value); v.valueType = ValueFlow::Value::ValueType::CONTAINER_SIZE; if (!isEqual) v.valueKind = ValueFlow::Value::ValueKind::Impossible; setValue(expr, v); } void ProgramMemory::setUnknown(const Token* expr) { copyOnWrite(); (*mValues)[expr].valueType = ValueFlow::Value::ValueType::UNINIT; } bool ProgramMemory::hasValue(nonneg int exprid) { return mValues->find(exprid) != mValues->end(); } const ValueFlow::Value& ProgramMemory::at(nonneg int exprid) const { return mValues->at(exprid); } ValueFlow::Value& ProgramMemory::at(nonneg int exprid) { copyOnWrite(); return mValues->at(exprid); } void ProgramMemory::erase_if(const std::function<bool(const ExprIdToken&)>& pred) { if (mValues->empty()) return; // TODO: how to delay until we actuallly modify? copyOnWrite(); for (auto it = mValues->begin(); it != mValues->end();) { if (pred(it->first)) it = mValues->erase(it); else ++it; } } void ProgramMemory::swap(ProgramMemory &pm) NOEXCEPT { mValues.swap(pm.mValues); } void ProgramMemory::clear() { if (mValues->empty()) return; copyOnWrite(); mValues->clear(); } bool ProgramMemory::empty() const { return mValues->empty(); } // NOLINTNEXTLINE(performance-unnecessary-value-param) - technically correct but we are moving the given values void ProgramMemory::replace(ProgramMemory pm) { if (pm.empty()) return; copyOnWrite(); for (auto&& p : (*pm.mValues)) { (*mValues)[p.first] = std::move(p.second); } } void ProgramMemory::copyOnWrite() { if (mValues.use_count() == 1) return; mValues = std::make_shared<Map>(*mValues); } static ValueFlow::Value execute(const Token* expr, ProgramMemory& pm, const Settings& settings); static bool evaluateCondition(MathLib::bigint r, const Token* condition, ProgramMemory& pm, const Settings& settings) { if (!condition) return false; MathLib::bigint result = 0; bool error = false; execute(condition, pm, &result, &error, settings); return !error && result == r; } bool conditionIsFalse(const Token* condition, ProgramMemory pm, const Settings& settings) { return evaluateCondition(0, condition, pm, settings); } bool conditionIsTrue(const Token* condition, ProgramMemory pm, const Settings& settings) { return evaluateCondition(1, condition, pm, settings); } static bool frontIs(const std::vector<MathLib::bigint>& v, bool i) { if (v.empty()) return false; if (v.front()) return i; return !i; } static bool isTrue(const ValueFlow::Value& v) { if (v.isUninitValue()) return false; if (v.isImpossible()) return v.intvalue == 0; return v.intvalue != 0; } static bool isFalse(const ValueFlow::Value& v) { if (v.isUninitValue()) return false; if (v.isImpossible()) return false; return v.intvalue == 0; } static bool isTrueOrFalse(const ValueFlow::Value& v, bool b) { if (b) return isTrue(v); return isFalse(v); } // If the scope is a non-range for loop static bool isBasicForLoop(const Token* tok) { if (!tok) return false; if (Token::simpleMatch(tok, "}")) return isBasicForLoop(tok->link()); if (!Token::simpleMatch(tok->previous(), ") {")) return false; const Token* start = tok->linkAt(-1); if (!start) return false; if (!Token::simpleMatch(start->previous(), "for (")) return false; if (!Token::simpleMatch(start->astOperand2(), ";")) return false; return true; } static void programMemoryParseCondition(ProgramMemory& pm, const Token* tok, const Token* endTok, const Settings& settings, bool then) { auto eval = [&](const Token* t) -> std::vector<MathLib::bigint> { if (!t) return std::vector<MathLib::bigint>{}; if (t->hasKnownIntValue()) return {t->values().front().intvalue}; MathLib::bigint result = 0; bool error = false; execute(t, pm, &result, &error, settings); if (!error) return {result}; return std::vector<MathLib::bigint>{}; }; if (Token::Match(tok, "==|>=|<=|<|>|!=")) { ValueFlow::Value truevalue; ValueFlow::Value falsevalue; const Token* vartok = parseCompareInt(tok, truevalue, falsevalue, eval); if (!vartok) return; if (vartok->exprId() == 0) return; if (!truevalue.isIntValue()) return; if (endTok && findExpressionChanged(vartok, tok->next(), endTok, settings)) return; const bool impossible = (tok->str() == "==" && !then) || (tok->str() == "!=" && then); const ValueFlow::Value& v = then ? truevalue : falsevalue; pm.setValue(vartok, impossible ? asImpossible(v) : v); const Token* containerTok = settings.library.getContainerFromYield(vartok, Library::Container::Yield::SIZE); if (containerTok) pm.setContainerSizeValue(containerTok, v.intvalue, !impossible); } else if (Token::simpleMatch(tok, "!")) { programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, !then); } else if (then && Token::simpleMatch(tok, "&&")) { programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then); programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then); } else if (!then && Token::simpleMatch(tok, "||")) { programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then); programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then); } else if (Token::Match(tok, "&&|%oror%")) { std::vector<MathLib::bigint> lhs = eval(tok->astOperand1()); std::vector<MathLib::bigint> rhs = eval(tok->astOperand2()); if (lhs.empty() || rhs.empty()) { if (frontIs(lhs, !then)) programMemoryParseCondition(pm, tok->astOperand2(), endTok, settings, then); else if (frontIs(rhs, !then)) programMemoryParseCondition(pm, tok->astOperand1(), endTok, settings, then); else pm.setIntValue(tok, 0, then); } } else if (tok && tok->exprId() > 0) { if (endTok && findExpressionChanged(tok, tok->next(), endTok, settings)) return; pm.setIntValue(tok, 0, then); const Token* containerTok = settings.library.getContainerFromYield(tok, Library::Container::Yield::EMPTY); if (containerTok) pm.setContainerSizeValue(containerTok, 0, then); } } static void fillProgramMemoryFromConditions(ProgramMemory& pm, const Scope* scope, const Token* endTok, const Settings& settings) { if (!scope) return; if (!scope->isLocal()) return; assert(scope != scope->nestedIn); fillProgramMemoryFromConditions(pm, scope->nestedIn, endTok, settings); if (scope->type == Scope::eIf || scope->type == Scope::eWhile || scope->type == Scope::eElse || scope->type == Scope::eFor) { const Token* condTok = getCondTokFromEnd(scope->bodyEnd); if (!condTok) return; MathLib::bigint result = 0; bool error = false; execute(condTok, pm, &result, &error, settings); if (error) programMemoryParseCondition(pm, condTok, endTok, settings, scope->type != Scope::eElse); } } static void fillProgramMemoryFromConditions(ProgramMemory& pm, const Token* tok, const Settings& settings) { fillProgramMemoryFromConditions(pm, tok->scope(), tok, settings); } static void fillProgramMemoryFromAssignments(ProgramMemory& pm, const Token* tok, const Settings& settings, const ProgramMemory& state, const ProgramMemory::Map& vars) { int indentlevel = 0; for (const Token *tok2 = tok; tok2; tok2 = tok2->previous()) { if ((Token::simpleMatch(tok2, "=") || Token::Match(tok2->previous(), "%var% (|{")) && tok2->astOperand1() && tok2->astOperand2()) { bool setvar = false; const Token* vartok = tok2->astOperand1(); for (const auto& p:vars) { if (p.first != vartok->exprId()) continue; if (vartok == tok) continue; pm.setValue(vartok, p.second); setvar = true; } if (!setvar) { if (!pm.hasValue(vartok->exprId())) { const Token* valuetok = tok2->astOperand2(); pm.setValue(vartok, execute(valuetok, pm, settings)); } } } else if (tok2->exprId() > 0 && Token::Match(tok2, ".|(|[|*|%var%") && !pm.hasValue(tok2->exprId()) && isVariableChanged(tok2, 0, settings)) { pm.setUnknown(tok2); } if (tok2->str() == "{") { if (indentlevel <= 0) { const Token* cond = getCondTokFromEnd(tok2->link()); // Keep progressing with anonymous/do scopes and always true branches if (!Token::Match(tok2->previous(), "do|; {") && !conditionIsTrue(cond, state, settings) && (cond || !isBasicForLoop(tok2))) break; } else --indentlevel; if (Token::simpleMatch(tok2->previous(), "else {")) tok2 = tok2->linkAt(-2)->previous(); } if (tok2->str() == "}" && !Token::Match(tok2->link()->previous(), "%var% {")) { const Token *cond = getCondTokFromEnd(tok2); const bool inElse = Token::simpleMatch(tok2->link()->previous(), "else {"); if (cond) { if (conditionIsFalse(cond, state, settings)) { if (inElse) { ++indentlevel; continue; } } else if (conditionIsTrue(cond, state, settings)) { if (inElse) tok2 = tok2->link()->tokAt(-2); ++indentlevel; continue; } } break; } } } static void removeModifiedVars(ProgramMemory& pm, const Token* tok, const Token* origin, const Settings& settings) { pm.erase_if([&](const ExprIdToken& e) { return isVariableChanged(origin, tok, e.getExpressionId(), false, settings); }); } static ProgramMemory getInitialProgramState(const Token* tok, const Token* origin, const Settings& settings, const ProgramMemory::Map& vars = ProgramMemory::Map {}) { ProgramMemory pm; if (origin) { fillProgramMemoryFromConditions(pm, origin, settings); const ProgramMemory state = pm; fillProgramMemoryFromAssignments(pm, tok, settings, state, vars); removeModifiedVars(pm, tok, origin, settings); } return pm; } ProgramMemoryState::ProgramMemoryState(const Settings& s) : settings(s) {} void ProgramMemoryState::replace(ProgramMemory pm, const Token* origin) { if (origin) for (const auto& p : pm) origins[p.first.getExpressionId()] = origin; state.replace(std::move(pm)); } static void addVars(ProgramMemory& pm, const ProgramMemory::Map& vars) { for (const auto& p:vars) { const ValueFlow::Value &value = p.second; pm.setValue(p.first.tok, value); } } void ProgramMemoryState::addState(const Token* tok, const ProgramMemory::Map& vars) { ProgramMemory pm = state; addVars(pm, vars); fillProgramMemoryFromConditions(pm, tok, settings); ProgramMemory local = pm; fillProgramMemoryFromAssignments(pm, tok, settings, local, vars); addVars(pm, vars); replace(std::move(pm), tok); } void ProgramMemoryState::assume(const Token* tok, bool b, bool isEmpty) { ProgramMemory pm = state; if (isEmpty) pm.setContainerSizeValue(tok, 0, b); else programMemoryParseCondition(pm, tok, nullptr, settings, b); const Token* origin = tok; const Token* top = tok->astTop(); if (Token::Match(top->previous(), "for|while|if (") && !Token::simpleMatch(tok->astParent(), "?")) { origin = top->link()->next(); if (!b && origin->link()) { origin = origin->link(); } } replace(std::move(pm), origin); } void ProgramMemoryState::removeModifiedVars(const Token* tok) { const ProgramMemory& pm = state; auto eval = [&](const Token* cond) -> std::vector<MathLib::bigint> { ProgramMemory pm2 = pm; auto result = execute(cond, pm2, settings); if (isTrue(result)) return {1}; if (isFalse(result)) return {0}; return {}; }; state.erase_if([&](const ExprIdToken& e) { const Token* start = origins[e.getExpressionId()]; const Token* expr = e.tok; if (!expr || findExpressionChangedSkipDeadCode(expr, start, tok, settings, eval)) { origins.erase(e.getExpressionId()); return true; } return false; }); } ProgramMemory ProgramMemoryState::get(const Token* tok, const Token* ctx, const ProgramMemory::Map& vars) const { ProgramMemoryState local = *this; if (ctx) local.addState(ctx, vars); const Token* start = previousBeforeAstLeftmostLeaf(tok); if (!start) start = tok; if (!ctx || precedes(start, ctx)) { local.removeModifiedVars(start); local.addState(start, vars); } else { local.removeModifiedVars(ctx); } return local.state; } ProgramMemory getProgramMemory(const Token* tok, const Token* expr, const ValueFlow::Value& value, const Settings& settings) { ProgramMemory programMemory; programMemory.replace(getInitialProgramState(tok, value.tokvalue, settings)); programMemory.replace(getInitialProgramState(tok, value.condition, settings)); fillProgramMemoryFromConditions(programMemory, tok, settings); programMemory.setValue(expr, value); const ProgramMemory state = programMemory; fillProgramMemoryFromAssignments(programMemory, tok, settings, state, {{expr, value}}); return programMemory; } static bool isNumericValue(const ValueFlow::Value& value) { return value.isIntValue() || value.isFloatValue(); } static double asFloat(const ValueFlow::Value& value) { return value.isFloatValue() ? value.floatValue : value.intvalue; } static std::string removeAssign(const std::string& assign) { return std::string{assign.cbegin(), assign.cend() - 1}; } namespace { struct assign { template<class T, class U> void operator()(T& x, const U& y) const { x = y; } }; } static bool isIntegralValue(const ValueFlow::Value& value) { return value.isIntValue() || value.isIteratorValue() || value.isSymbolicValue(); } static ValueFlow::Value evaluate(const std::string& op, const ValueFlow::Value& lhs, const ValueFlow::Value& rhs) { ValueFlow::Value result; if (lhs.isImpossible() && rhs.isImpossible()) return ValueFlow::Value::unknown(); if (lhs.isImpossible() || rhs.isImpossible()) { // noninvertible if (contains({"%", "/", "&", "|"}, op)) return ValueFlow::Value::unknown(); result.setImpossible(); } if (isNumericValue(lhs) && isNumericValue(rhs)) { if (lhs.isFloatValue() || rhs.isFloatValue()) { result.valueType = ValueFlow::Value::ValueType::FLOAT; bool error = false; result.floatValue = calculate(op, asFloat(lhs), asFloat(rhs), &error); if (error) return ValueFlow::Value::unknown(); return result; } } // Must be integral types if (!isIntegralValue(lhs) && !isIntegralValue(rhs)) return ValueFlow::Value::unknown(); // If not the same type then one must be int if (lhs.valueType != rhs.valueType && !lhs.isIntValue() && !rhs.isIntValue()) return ValueFlow::Value::unknown(); const bool compareOp = contains({"==", "!=", "<", ">", ">=", "<="}, op); // Comparison must be the same type if (compareOp && lhs.valueType != rhs.valueType) return ValueFlow::Value::unknown(); // Only add, subtract, and compare for non-integers if (!compareOp && !contains({"+", "-"}, op) && !lhs.isIntValue() && !rhs.isIntValue()) return ValueFlow::Value::unknown(); // Both can't be iterators for non-compare if (!compareOp && lhs.isIteratorValue() && rhs.isIteratorValue()) return ValueFlow::Value::unknown(); // Symbolic values must be in the same ring if (lhs.isSymbolicValue() && rhs.isSymbolicValue() && lhs.tokvalue != rhs.tokvalue) return ValueFlow::Value::unknown(); if (!lhs.isIntValue() && !compareOp) { result.valueType = lhs.valueType; result.tokvalue = lhs.tokvalue; } else if (!rhs.isIntValue() && !compareOp) { result.valueType = rhs.valueType; result.tokvalue = rhs.tokvalue; } else { result.valueType = ValueFlow::Value::ValueType::INT; } bool error = false; result.intvalue = calculate(op, lhs.intvalue, rhs.intvalue, &error); if (error) return ValueFlow::Value::unknown(); if (result.isImpossible() && op == "!=") { if (isTrue(result)) { result.intvalue = 1; } else if (isFalse(result)) { result.intvalue = 0; } else { return ValueFlow::Value::unknown(); } result.setPossible(); result.bound = ValueFlow::Value::Bound::Point; } return result; } using BuiltinLibraryFunction = std::function<ValueFlow::Value(const std::vector<ValueFlow::Value>&)>; static std::unordered_map<std::string, BuiltinLibraryFunction> createBuiltinLibraryFunctions() { std::unordered_map<std::string, BuiltinLibraryFunction> functions; functions["strlen"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!(v.isTokValue() && v.tokvalue->tokType() == Token::eString)) return ValueFlow::Value::unknown(); v.valueType = ValueFlow::Value::ValueType::INT; v.intvalue = Token::getStrLength(v.tokvalue); v.tokvalue = nullptr; return v; }; functions["strcmp"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2) return ValueFlow::Value::unknown(); const ValueFlow::Value& lhs = args[0]; if (!(lhs.isTokValue() && lhs.tokvalue->tokType() == Token::eString)) return ValueFlow::Value::unknown(); const ValueFlow::Value& rhs = args[1]; if (!(rhs.isTokValue() && rhs.tokvalue->tokType() == Token::eString)) return ValueFlow::Value::unknown(); ValueFlow::Value v(getStringLiteral(lhs.tokvalue->str()).compare(getStringLiteral(rhs.tokvalue->str()))); ValueFlow::combineValueProperties(lhs, rhs, v); return v; }; functions["strncmp"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 3) return ValueFlow::Value::unknown(); const ValueFlow::Value& lhs = args[0]; if (!(lhs.isTokValue() && lhs.tokvalue->tokType() == Token::eString)) return ValueFlow::Value::unknown(); const ValueFlow::Value& rhs = args[1]; if (!(rhs.isTokValue() && rhs.tokvalue->tokType() == Token::eString)) return ValueFlow::Value::unknown(); const ValueFlow::Value& len = args[2]; if (!len.isIntValue()) return ValueFlow::Value::unknown(); ValueFlow::Value v(getStringLiteral(lhs.tokvalue->str()) .compare(0, len.intvalue, getStringLiteral(rhs.tokvalue->str()), 0, len.intvalue)); ValueFlow::combineValueProperties(lhs, rhs, v); return v; }; functions["sin"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::sin(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["lgamma"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::lgamma(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["cos"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::cos(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["tan"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::tan(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["asin"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::asin(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["acos"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::acos(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["atan"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::atan(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["atan2"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::atan2(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["remainder"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::remainder(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["nextafter"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::nextafter(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["nexttoward"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::nexttoward(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["hypot"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::hypot(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["fdim"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::fdim(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["fmax"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::fmax(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["fmin"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::fmin(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["fmod"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::fmod(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["pow"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::pow(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["scalbln"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::scalbln(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["ldexp"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 2 || !std::all_of(args.cbegin(), args.cend(), [](const ValueFlow::Value& v) { return v.isFloatValue() || v.isIntValue(); })) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; ValueFlow::Value v; combineValueProperties(args[0], args[1], v); v.floatValue = std::ldexp(value, args[1].isFloatValue() ? args[1].floatValue : args[1].intvalue); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["ilogb"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.intvalue = std::ilogb(value); v.valueType = ValueFlow::Value::ValueType::INT; return v; }; functions["erf"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::erf(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["erfc"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::erfc(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["floor"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::floor(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["sqrt"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::sqrt(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["cbrt"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::cbrt(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["ceil"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::ceil(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["exp"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::exp(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["exp2"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::exp2(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["expm1"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::expm1(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["fabs"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::fabs(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["log"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::log(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["log10"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::log10(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["log1p"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::log1p(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["log2"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::log2(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["logb"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::logb(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["nearbyint"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::nearbyint(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["sinh"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::sinh(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["cosh"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::cosh(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["tanh"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::tanh(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["asinh"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::asinh(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["acosh"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::acosh(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["atanh"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::atanh(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["round"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::round(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["tgamma"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::tgamma(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; functions["trunc"] = [](const std::vector<ValueFlow::Value>& args) { if (args.size() != 1) return ValueFlow::Value::unknown(); ValueFlow::Value v = args[0]; if (!v.isFloatValue() && !v.isIntValue()) return ValueFlow::Value::unknown(); const double value = args[0].isFloatValue() ? args[0].floatValue : args[0].intvalue; v.floatValue = std::trunc(value); v.valueType = ValueFlow::Value::ValueType::FLOAT; return v; }; return functions; } static BuiltinLibraryFunction getBuiltinLibraryFunction(const std::string& name) { static const std::unordered_map<std::string, BuiltinLibraryFunction> functions = createBuiltinLibraryFunctions(); auto it = functions.find(name); if (it == functions.end()) return nullptr; return it->second; } static bool TokenExprIdCompare(const Token* tok1, const Token* tok2) { return tok1->exprId() < tok2->exprId(); } static bool TokenExprIdEqual(const Token* tok1, const Token* tok2) { return tok1->exprId() == tok2->exprId(); } static std::vector<const Token*> setDifference(const std::vector<const Token*>& v1, const std::vector<const Token*>& v2) { std::vector<const Token*> result; std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), std::back_inserter(result), &TokenExprIdCompare); return result; } static bool evalSameCondition(const ProgramMemory& state, const Token* storedValue, const Token* cond, const Settings& settings) { assert(!conditionIsTrue(cond, state, settings)); ProgramMemory pm = state; programMemoryParseCondition(pm, storedValue, nullptr, settings, true); if (pm == state) return false; return conditionIsTrue(cond, std::move(pm), settings); } static void pruneConditions(std::vector<const Token*>& conds, bool b, const std::unordered_map<nonneg int, ValueFlow::Value>& state) { conds.erase(std::remove_if(conds.begin(), conds.end(), [&](const Token* cond) { if (cond->exprId() == 0) return false; auto it = state.find(cond->exprId()); if (it == state.end()) return false; const ValueFlow::Value& v = it->second; return isTrueOrFalse(v, !b); }), conds.end()); } namespace { struct Executor { ProgramMemory* pm; const Settings& settings; int fdepth = 4; int depth = 10; Executor(ProgramMemory* pm, const Settings& settings) : pm(pm), settings(settings) { assert(pm != nullptr); } static ValueFlow::Value unknown() { return ValueFlow::Value::unknown(); } std::unordered_map<nonneg int, ValueFlow::Value> executeAll(const std::vector<const Token*>& toks, const bool* b = nullptr) const { std::unordered_map<nonneg int, ValueFlow::Value> result; auto state = *this; for (const Token* tok : toks) { ValueFlow::Value r = state.execute(tok); if (r.isUninitValue()) continue; const bool brk = b && isTrueOrFalse(r, *b); result.emplace(tok->exprId(), std::move(r)); // Short-circuit evaluation if (brk) break; } return result; } static std::vector<const Token*> flattenConditions(const Token* tok) { return astFlatten(tok, tok->str().c_str()); } static bool sortConditions(std::vector<const Token*>& conditions) { if (std::any_of(conditions.begin(), conditions.end(), [](const Token* child) { return Token::Match(child, "&&|%oror%"); })) return false; std::sort(conditions.begin(), conditions.end(), &TokenExprIdCompare); conditions.erase(std::unique(conditions.begin(), conditions.end(), &TokenExprIdCompare), conditions.end()); return !conditions.empty() && conditions.front()->exprId() != 0; } ValueFlow::Value executeMultiCondition(bool b, const Token* expr) { if (pm->hasValue(expr->exprId())) { const ValueFlow::Value& v = utils::as_const(*pm).at(expr->exprId()); if (v.isIntValue()) return v; } // Evaluate recursively if there are no exprids if ((expr->astOperand1() && expr->astOperand1()->exprId() == 0) || (expr->astOperand2() && expr->astOperand2()->exprId() == 0)) { ValueFlow::Value lhs = execute(expr->astOperand1()); if (isTrueOrFalse(lhs, b)) return lhs; ValueFlow::Value rhs = execute(expr->astOperand2()); if (isTrueOrFalse(rhs, b)) return rhs; if (isTrueOrFalse(lhs, !b) && isTrueOrFalse(rhs, !b)) return lhs; return unknown(); } nonneg int n = astCount(expr, expr->str().c_str()); if (n > 50) return unknown(); std::vector<const Token*> conditions1 = flattenConditions(expr); if (conditions1.empty()) return unknown(); std::unordered_map<nonneg int, ValueFlow::Value> condValues = executeAll(conditions1, &b); bool allNegated = true; ValueFlow::Value negatedValue = unknown(); for (const auto& p : condValues) { const ValueFlow::Value& v = p.second; if (isTrueOrFalse(v, b)) return v; allNegated &= isTrueOrFalse(v, !b); if (allNegated && negatedValue.isUninitValue()) negatedValue = v; } if (condValues.size() == conditions1.size() && allNegated) return negatedValue; if (n > 4) return unknown(); if (!sortConditions(conditions1)) return unknown(); for (const auto& p : *pm) { const Token* tok = p.first.tok; if (!tok) continue; const ValueFlow::Value& value = p.second; if (tok->str() == expr->str() && !astHasExpr(tok, expr->exprId())) { // TODO: Handle when it is greater if (n != astCount(tok, expr->str().c_str())) continue; std::vector<const Token*> conditions2 = flattenConditions(tok); if (!sortConditions(conditions2)) return unknown(); if (conditions1.size() == conditions2.size() && std::equal(conditions1.begin(), conditions1.end(), conditions2.begin(), &TokenExprIdEqual)) return value; std::vector<const Token*> diffConditions1 = setDifference(conditions1, conditions2); std::vector<const Token*> diffConditions2 = setDifference(conditions2, conditions1); pruneConditions(diffConditions1, !b, condValues); pruneConditions(diffConditions2, !b, executeAll(diffConditions2)); if (diffConditions1.size() != diffConditions2.size()) continue; if (diffConditions1.size() == conditions1.size()) continue; for (const Token* cond1 : diffConditions1) { auto it = std::find_if(diffConditions2.begin(), diffConditions2.end(), [&](const Token* cond2) { return evalSameCondition(*pm, cond2, cond1, settings); }); if (it == diffConditions2.end()) break; diffConditions2.erase(it); } if (diffConditions2.empty()) return value; } } return unknown(); } ValueFlow::Value executeImpl(const Token* expr) { const ValueFlow::Value* value = nullptr; if (!expr) return unknown(); if (expr->hasKnownIntValue() && !expr->isAssignmentOp() && expr->str() != ",") return expr->values().front(); if ((value = expr->getKnownValue(ValueFlow::Value::ValueType::FLOAT)) || (value = expr->getKnownValue(ValueFlow::Value::ValueType::TOK)) || (value = expr->getKnownValue(ValueFlow::Value::ValueType::ITERATOR_START)) || (value = expr->getKnownValue(ValueFlow::Value::ValueType::ITERATOR_END)) || (value = expr->getKnownValue(ValueFlow::Value::ValueType::CONTAINER_SIZE))) { return *value; } if (expr->isNumber()) { if (MathLib::isFloat(expr->str())) return unknown(); MathLib::bigint i = MathLib::toBigNumber(expr->str()); if (i < 0 && astIsUnsigned(expr)) return unknown(); return ValueFlow::Value{i}; } if (expr->isBoolean()) return ValueFlow::Value{expr->str() == "true"}; if (Token::Match(expr->tokAt(-2), ". %name% (") && astIsContainer(expr->tokAt(-2)->astOperand1())) { const Token* containerTok = expr->tokAt(-2)->astOperand1(); const Library::Container::Yield yield = containerTok->valueType()->container->getYield(expr->strAt(-1)); if (yield == Library::Container::Yield::SIZE) { ValueFlow::Value v = execute(containerTok); if (!v.isContainerSizeValue()) return unknown(); v.valueType = ValueFlow::Value::ValueType::INT; return v; } if (yield == Library::Container::Yield::EMPTY) { ValueFlow::Value v = execute(containerTok); if (!v.isContainerSizeValue()) return unknown(); if (v.isImpossible() && v.intvalue == 0) return ValueFlow::Value{0}; if (!v.isImpossible()) return ValueFlow::Value{v.intvalue == 0}; } } else if (expr->isAssignmentOp() && expr->astOperand1() && expr->astOperand2() && expr->astOperand1()->exprId() > 0) { ValueFlow::Value rhs = execute(expr->astOperand2()); if (rhs.isUninitValue()) return unknown(); if (expr->str() != "=") { if (!pm->hasValue(expr->astOperand1()->exprId())) return unknown(); ValueFlow::Value& lhs = pm->at(expr->astOperand1()->exprId()); rhs = evaluate(removeAssign(expr->str()), lhs, rhs); if (lhs.isIntValue()) ValueFlow::Value::visitValue(rhs, std::bind(assign{}, std::ref(lhs.intvalue), std::placeholders::_1)); else if (lhs.isFloatValue()) ValueFlow::Value::visitValue(rhs, std::bind(assign{}, std::ref(lhs.floatValue), std::placeholders::_1)); else return unknown(); return lhs; } pm->setValue(expr->astOperand1(), rhs); return rhs; } else if (expr->str() == "&&" && expr->astOperand1() && expr->astOperand2()) { return executeMultiCondition(false, expr); } else if (expr->str() == "||" && expr->astOperand1() && expr->astOperand2()) { return executeMultiCondition(true, expr); } else if (expr->str() == "," && expr->astOperand1() && expr->astOperand2()) { execute(expr->astOperand1()); return execute(expr->astOperand2()); } else if (expr->tokType() == Token::eIncDecOp && expr->astOperand1() && expr->astOperand1()->exprId() != 0) { if (!pm->hasValue(expr->astOperand1()->exprId())) return ValueFlow::Value::unknown(); ValueFlow::Value& lhs = pm->at(expr->astOperand1()->exprId()); if (!lhs.isIntValue()) return unknown(); // overflow if (!lhs.isImpossible() && lhs.intvalue == 0 && expr->str() == "--" && astIsUnsigned(expr->astOperand1())) return unknown(); if (expr->str() == "++") lhs.intvalue++; else lhs.intvalue--; return lhs; } else if (expr->str() == "[" && expr->astOperand1() && expr->astOperand2()) { const Token* tokvalue = nullptr; if (!pm->getTokValue(expr->astOperand1()->exprId(), tokvalue)) { auto tokvalue_it = std::find_if(expr->astOperand1()->values().cbegin(), expr->astOperand1()->values().cend(), std::mem_fn(&ValueFlow::Value::isTokValue)); if (tokvalue_it == expr->astOperand1()->values().cend() || !tokvalue_it->isKnown()) { return unknown(); } tokvalue = tokvalue_it->tokvalue; } if (!tokvalue || !tokvalue->isLiteral()) { return unknown(); } const std::string strValue = tokvalue->strValue(); ValueFlow::Value rhs = execute(expr->astOperand2()); if (!rhs.isIntValue()) return unknown(); const MathLib::bigint index = rhs.intvalue; if (index >= 0 && index < strValue.size()) return ValueFlow::Value{strValue[index]}; if (index == strValue.size()) return ValueFlow::Value{}; } else if (Token::Match(expr, "%cop%") && expr->astOperand1() && expr->astOperand2()) { ValueFlow::Value lhs = execute(expr->astOperand1()); ValueFlow::Value rhs = execute(expr->astOperand2()); ValueFlow::Value r = unknown(); if (!lhs.isUninitValue() && !rhs.isUninitValue()) r = evaluate(expr->str(), lhs, rhs); if (expr->isComparisonOp() && (r.isUninitValue() || r.isImpossible())) { if (rhs.isIntValue() && !expr->astOperand1()->values().empty()) { std::vector<ValueFlow::Value> result = infer(makeIntegralInferModel(), expr->str(), expr->astOperand1()->values(), {std::move(rhs)}); if (!result.empty() && result.front().isKnown()) return std::move(result.front()); } if (lhs.isIntValue() && !expr->astOperand2()->values().empty()) { std::vector<ValueFlow::Value> result = infer(makeIntegralInferModel(), expr->str(), {std::move(lhs)}, expr->astOperand2()->values()); if (!result.empty() && result.front().isKnown()) return std::move(result.front()); } return unknown(); } return r; } // Unary ops else if (Token::Match(expr, "!|+|-") && expr->astOperand1() && !expr->astOperand2()) { ValueFlow::Value lhs = execute(expr->astOperand1()); if (!lhs.isIntValue()) return unknown(); if (expr->str() == "!") { if (isTrue(lhs)) { lhs.intvalue = 0; } else if (isFalse(lhs)) { lhs.intvalue = 1; } else { return unknown(); } lhs.setPossible(); lhs.bound = ValueFlow::Value::Bound::Point; } if (expr->str() == "-") lhs.intvalue = -lhs.intvalue; return lhs; } else if (expr->str() == "?" && expr->astOperand1() && expr->astOperand2()) { ValueFlow::Value cond = execute(expr->astOperand1()); if (!cond.isIntValue()) return unknown(); const Token* child = expr->astOperand2(); if (isFalse(cond)) return execute(child->astOperand2()); if (isTrue(cond)) return execute(child->astOperand1()); return unknown(); } else if (expr->str() == "(" && expr->isCast()) { if (expr->astOperand2()) { if (expr->astOperand1()->str() != "dynamic_cast") return execute(expr->astOperand2()); return unknown(); } return execute(expr->astOperand1()); } if (expr->exprId() > 0 && pm->hasValue(expr->exprId())) { ValueFlow::Value result = utils::as_const(*pm).at(expr->exprId()); if (result.isImpossible() && result.isIntValue() && result.intvalue == 0 && isUsedAsBool(expr, settings)) { result.intvalue = !result.intvalue; result.setKnown(); } return result; } if (Token::Match(expr->previous(), ">|%name% {|(")) { const Token* ftok = expr->previous(); const Function* f = ftok->function(); ValueFlow::Value result = unknown(); if (expr->str() == "(") { std::vector<const Token*> tokArgs = getArguments(expr); std::vector<ValueFlow::Value> args(tokArgs.size()); std::transform( tokArgs.cbegin(), tokArgs.cend(), args.begin(), [&](const Token* tok) { return execute(tok); }); if (f) { if (fdepth >= 0 && !f->isImplicitlyVirtual()) { ProgramMemory functionState; for (std::size_t i = 0; i < args.size(); ++i) { const Variable* const arg = f->getArgumentVar(i); if (!arg) return unknown(); functionState.setValue(arg->nameToken(), args[i]); } Executor ex = *this; ex.pm = &functionState; ex.fdepth--; auto r = ex.execute(f->functionScope); if (!r.empty()) result = std::move(r.front()); // TODO: Track values changed by reference } } else { BuiltinLibraryFunction lf = getBuiltinLibraryFunction(ftok->str()); if (lf) return lf(args); const std::string& returnValue = settings.library.returnValue(ftok); if (!returnValue.empty()) { std::unordered_map<nonneg int, ValueFlow::Value> arg_map; int argn = 0; for (const ValueFlow::Value& v : args) { if (!v.isUninitValue()) arg_map[argn] = v; argn++; } return evaluateLibraryFunction(arg_map, returnValue, settings, ftok->isCpp()); } } } // Check if function modifies argument visitAstNodes(expr->astOperand2(), [&](const Token* child) { if (child->exprId() > 0 && pm->hasValue(child->exprId())) { ValueFlow::Value& v = pm->at(child->exprId()); if (v.valueType == ValueFlow::Value::ValueType::CONTAINER_SIZE) { if (ValueFlow::isContainerSizeChanged(child, v.indirect, settings)) v = unknown(); } else if (v.valueType != ValueFlow::Value::ValueType::UNINIT) { if (isVariableChanged(child, v.indirect, settings)) v = unknown(); } } return ChildrenToVisit::op1_and_op2; }); return result; } return unknown(); } static const ValueFlow::Value* getImpossibleValue(const Token* tok) { if (!tok) return nullptr; std::vector<const ValueFlow::Value*> values; for (const ValueFlow::Value& v : tok->values()) { if (!v.isImpossible()) continue; if (v.isContainerSizeValue() || v.isIntValue()) { values.push_back(std::addressof(v)); } } auto it = std::max_element(values.begin(), values.end(), [](const ValueFlow::Value* x, const ValueFlow::Value* y) { return x->intvalue < y->intvalue; }); if (it == values.end()) return nullptr; return *it; } static bool updateValue(ValueFlow::Value& v, ValueFlow::Value x) { const bool returnValue = !x.isUninitValue() && !x.isImpossible(); if (v.isUninitValue() || returnValue) v = std::move(x); return returnValue; } ValueFlow::Value execute(const Token* expr) { depth--; OnExit onExit{[&] { depth++; }}; if (depth < 0) return unknown(); ValueFlow::Value v = unknown(); if (updateValue(v, executeImpl(expr))) return v; if (!expr) return v; if (expr->exprId() > 0 && pm->hasValue(expr->exprId())) { if (updateValue(v, utils::as_const(*pm).at(expr->exprId()))) return v; } // Find symbolic values for (const ValueFlow::Value& value : expr->values()) { if (!value.isSymbolicValue()) continue; if (!value.isKnown()) continue; if (value.tokvalue->exprId() > 0 && !pm->hasValue(value.tokvalue->exprId())) continue; ValueFlow::Value v2 = utils::as_const(*pm).at(value.tokvalue->exprId()); if (!v2.isIntValue() && value.intvalue != 0) continue; v2.intvalue += value.intvalue; return v2; } if (v.isImpossible() && v.isIntValue()) return v; if (const ValueFlow::Value* value = getImpossibleValue(expr)) return *value; return v; } std::vector<ValueFlow::Value> execute(const Scope* scope) { if (!scope) return {unknown()}; if (!scope->bodyStart) return {unknown()}; for (const Token* tok = scope->bodyStart->next(); precedes(tok, scope->bodyEnd); tok = tok->next()) { const Token* top = tok->astTop(); if (Token::simpleMatch(top, "return") && top->astOperand1()) return {execute(top->astOperand1())}; if (Token::Match(top, "%op%")) { if (execute(top).isUninitValue()) return {unknown()}; const Token* next = nextAfterAstRightmostLeaf(top); if (!next) return {unknown()}; tok = next; } else if (Token::simpleMatch(top->previous(), "if (")) { const Token* condTok = top->astOperand2(); ValueFlow::Value v = execute(condTok); if (!v.isIntValue()) return {unknown()}; const Token* thenStart = top->link()->next(); const Token* next = thenStart->link(); const Token* elseStart = nullptr; if (Token::simpleMatch(thenStart->link(), "} else {")) { elseStart = thenStart->link()->tokAt(2); next = elseStart->link(); } std::vector<ValueFlow::Value> result; if (isTrue(v)) { result = execute(thenStart->scope()); } else if (isFalse(v)) { if (elseStart) result = execute(elseStart->scope()); } else { return {unknown()}; } if (!result.empty()) return result; tok = next; } else { return {unknown()}; } } return {}; } }; } // namespace static ValueFlow::Value execute(const Token* expr, ProgramMemory& pm, const Settings& settings) { Executor ex{&pm, settings}; return ex.execute(expr); } std::vector<ValueFlow::Value> execute(const Scope* scope, ProgramMemory& pm, const Settings& settings) { Executor ex{&pm, settings}; return ex.execute(scope); } static std::shared_ptr<Token> createTokenFromExpression(const std::string& returnValue, const Settings& settings, bool cpp, std::unordered_map<nonneg int, const Token*>& lookupVarId) { std::shared_ptr<TokenList> tokenList = std::make_shared<TokenList>(&settings); { const std::string code = "return " + returnValue + ";"; std::istringstream istr(code); if (!tokenList->createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C)) return nullptr; } // TODO: put in a helper? // combine operators, set links, etc.. std::stack<Token*> lpar; for (Token* tok2 = tokenList->front(); tok2; tok2 = tok2->next()) { if (Token::Match(tok2, "[!<>=] =")) { tok2->str(tok2->str() + "="); tok2->deleteNext(); } else if (tok2->str() == "(") lpar.push(tok2); else if (tok2->str() == ")") { if (lpar.empty()) return nullptr; Token::createMutualLinks(lpar.top(), tok2); lpar.pop(); } } if (!lpar.empty()) return nullptr; // set varids for (Token* tok2 = tokenList->front(); tok2; tok2 = tok2->next()) { if (!startsWith(tok2->str(), "arg")) continue; nonneg int const id = strToInt<nonneg int>(tok2->str().c_str() + 3); tok2->varId(id); lookupVarId[id] = tok2; } // Evaluate expression tokenList->createAst(); Token* expr = tokenList->front()->astOperand1(); ValueFlow::valueFlowConstantFoldAST(expr, settings); return {tokenList, expr}; } ValueFlow::Value evaluateLibraryFunction(const std::unordered_map<nonneg int, ValueFlow::Value>& args, const std::string& returnValue, const Settings& settings, bool cpp) { thread_local static std::unordered_map<std::string, std::function<ValueFlow::Value(const std::unordered_map<nonneg int, ValueFlow::Value>&, const Settings&)>> functions = {}; if (functions.count(returnValue) == 0) { std::unordered_map<nonneg int, const Token*> lookupVarId; std::shared_ptr<Token> expr = createTokenFromExpression(returnValue, settings, cpp, lookupVarId); functions[returnValue] = [lookupVarId, expr](const std::unordered_map<nonneg int, ValueFlow::Value>& xargs, const Settings& settings) { if (!expr) return ValueFlow::Value::unknown(); ProgramMemory pm{}; for (const auto& p : xargs) { auto it = lookupVarId.find(p.first); if (it != lookupVarId.end()) pm.setValue(it->second, p.second); } return execute(expr.get(), pm, settings); }; } return functions.at(returnValue)(args, settings); } void execute(const Token* expr, ProgramMemory& programMemory, MathLib::bigint* result, bool* error, const Settings& settings) { ValueFlow::Value v = execute(expr, programMemory, settings); if (!v.isIntValue() || v.isImpossible()) { if (error) *error = true; } else if (result) *result = v.intvalue; }
78,440
C++
.cpp
1,775
33.338592
167
0.556995
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,122
forwardanalyzer.cpp
danmar_cppcheck/lib/forwardanalyzer.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "forwardanalyzer.h" #include "analyzer.h" #include "astutils.h" #include "config.h" #include "errorlogger.h" #include "errortypes.h" #include "mathlib.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "utils.h" #include "valueptr.h" #include "vfvalue.h" #include <algorithm> #include <cassert> #include <cstdio> #include <cstdint> #include <functional> #include <list> #include <string> #include <tuple> #include <type_traits> #include <utility> #include <vector> namespace { struct ForwardTraversal { enum class Progress : std::uint8_t { Continue, Break, Skip }; enum class Terminate : std::uint8_t { None, Bail, Inconclusive }; ForwardTraversal(const ValuePtr<Analyzer>& analyzer, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) : analyzer(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings) {} ValuePtr<Analyzer> analyzer; const TokenList& tokenList; ErrorLogger& errorLogger; const Settings& settings; Analyzer::Action actions; bool analyzeOnly{}; bool analyzeTerminate{}; Analyzer::Terminate terminate = Analyzer::Terminate::None; std::vector<Token*> loopEnds; int branchCount = 0; Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) { if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None) terminate = t; return Progress::Break; } struct Branch { explicit Branch(Token* tok = nullptr) : endBlock(tok) {} Token* endBlock = nullptr; Analyzer::Action action = Analyzer::Action::None; bool check = false; bool escape = false; bool escapeUnknown = false; bool active = false; bool isEscape() const { return escape || escapeUnknown; } bool isConclusiveEscape() const { return escape && !escapeUnknown; } bool isModified() const { return action.isModified() && !isConclusiveEscape(); } bool isInconclusive() const { return action.isInconclusive() && !isConclusiveEscape(); } bool isDead() const { return action.isModified() || action.isInconclusive() || isEscape(); } }; bool stopUpdates() { analyzeOnly = true; return actions.isModified(); } bool stopOnCondition(const Token* condTok) const { if (analyzer->isConditional() && findAstNode(condTok, [](const Token* tok) { return tok->isIncompleteVar(); })) return true; return analyzer->stopOnCondition(condTok); } std::pair<bool, bool> evalCond(const Token* tok, const Token* ctx = nullptr) const { if (!tok) return std::make_pair(false, false); std::vector<MathLib::bigint> result = analyzer->evaluate(tok, ctx); // TODO: We should convert to bool const bool checkThen = std::any_of(result.cbegin(), result.cend(), [](int x) { return x != 0; }); const bool checkElse = std::any_of(result.cbegin(), result.cend(), [](int x) { return x == 0; }); return std::make_pair(checkThen, checkElse); } bool isConditionTrue(const Token* tok, const Token* ctx = nullptr) const { return evalCond(tok, ctx).first; } template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> Progress traverseTok(T* tok, const F &f, bool traverseUnknown, T** out = nullptr) { if (Token::Match(tok, "asm|goto")) return Break(Analyzer::Terminate::Bail); if (Token::Match(tok, "setjmp|longjmp (")) { // Traverse the parameters of the function before escaping traverseRecursive(tok->next()->astOperand2(), f, traverseUnknown); return Break(Analyzer::Terminate::Bail); } if (Token::simpleMatch(tok, "continue")) { if (loopEnds.empty()) return Break(Analyzer::Terminate::Escape); // If we are in a loop then jump to the end if (out) *out = loopEnds.back(); } else if (Token::Match(tok, "return|throw")) { traverseRecursive(tok->astOperand2(), f, traverseUnknown); traverseRecursive(tok->astOperand1(), f, traverseUnknown); return Break(Analyzer::Terminate::Escape); } else if (Token::Match(tok, "%name% (") && isEscapeFunction(tok, &settings.library)) { // Traverse the parameters of the function before escaping traverseRecursive(tok->next()->astOperand2(), f, traverseUnknown); return Break(Analyzer::Terminate::Escape); } else if (isUnevaluated(tok->previous())) { if (out) *out = tok->link(); return Progress::Skip; } else if (tok->astOperand1() && tok->astOperand2() && Token::Match(tok, "?|&&|%oror%")) { if (traverseConditional(tok, f, traverseUnknown) == Progress::Break) return Break(); if (out) *out = nextAfterAstRightmostLeaf(tok); return Progress::Skip; // Skip lambdas } else if (T* lambdaEndToken = findLambdaEndToken(tok)) { if (checkScope(lambdaEndToken).isModified()) return Break(Analyzer::Terminate::Bail); if (out) *out = lambdaEndToken->next(); // Skip class scope } else if (tok->str() == "{" && tok->scope() && tok->scope()->isClassOrStruct()) { if (out) *out = tok->link(); } else { if (f(tok) == Progress::Break) return Break(); } return Progress::Continue; } template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> Progress traverseRecursive(T* tok, const F &f, bool traverseUnknown, unsigned int recursion=0) { if (!tok) return Progress::Continue; if (recursion > 10000) return Progress::Skip; T* firstOp = tok->astOperand1(); T* secondOp = tok->astOperand2(); // Evaluate: // 1. RHS of assignment before LHS // 2. Unary op before operand // 3. Function arguments before function call if (tok->isAssignmentOp() || !secondOp || isFunctionCall(tok)) std::swap(firstOp, secondOp); if (firstOp && traverseRecursive(firstOp, f, traverseUnknown, recursion+1) == Progress::Break) return Break(); const Progress p = tok->isAssignmentOp() ? Progress::Continue : traverseTok(tok, f, traverseUnknown); if (p == Progress::Break) return Break(); if (p == Progress::Continue && secondOp && traverseRecursive(secondOp, f, traverseUnknown, recursion+1) == Progress::Break) return Break(); if (tok->isAssignmentOp() && traverseTok(tok, f, traverseUnknown) == Progress::Break) return Break(); return Progress::Continue; } template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> Progress traverseConditional(T* tok, F f, bool traverseUnknown) { if (Token::Match(tok, "?|&&|%oror%") && tok->astOperand1() && tok->astOperand2()) { const T* condTok = tok->astOperand1(); T* childTok = tok->astOperand2(); bool checkThen, checkElse; std::tie(checkThen, checkElse) = evalCond(condTok); if (!checkThen && !checkElse) { if (!traverseUnknown && stopOnCondition(condTok) && stopUpdates()) { return Progress::Continue; } checkThen = true; checkElse = true; } if (childTok->str() == ":") { if (checkThen && traverseRecursive(childTok->astOperand1(), f, traverseUnknown) == Progress::Break) return Break(); if (checkElse && traverseRecursive(childTok->astOperand2(), f, traverseUnknown) == Progress::Break) return Break(); } else { if (!checkThen && tok->str() == "&&") return Progress::Continue; if (!checkElse && tok->str() == "||") return Progress::Continue; if (traverseRecursive(childTok, f, traverseUnknown) == Progress::Break) return Break(); } } return Progress::Continue; } Progress update(Token* tok) { Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward); actions |= action; if (!action.isNone() && !analyzeOnly) analyzer->update(tok, action, Analyzer::Direction::Forward); if (action.isInconclusive() && !analyzer->lowerToInconclusive()) return Break(Analyzer::Terminate::Inconclusive); if (action.isInvalid()) return Break(Analyzer::Terminate::Modified); if (action.isWrite() && !action.isRead()) // Analysis of this write will continue separately return Break(Analyzer::Terminate::Modified); return Progress::Continue; } Progress updateTok(Token* tok, Token** out = nullptr) { auto f = [this](Token* tok2) { return update(tok2); }; return traverseTok(tok, f, false, out); } Progress updateRecursive(Token* tok) { auto f = [this](Token* tok2) { return update(tok2); }; return traverseRecursive(tok, f, false); } Analyzer::Action analyzeRecursive(const Token* start) { Analyzer::Action result = Analyzer::Action::None; auto f = [&](const Token* tok) { result = analyzer->analyze(tok, Analyzer::Direction::Forward); if (result.isModified() || result.isInconclusive()) return Break(); return Progress::Continue; }; traverseRecursive(start, f, true); return result; } Analyzer::Action analyzeRange(const Token* start, const Token* end) const { Analyzer::Action result = Analyzer::Action::None; for (const Token* tok = start; tok && tok != end; tok = tok->next()) { Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward); if (action.isModified() || action.isInconclusive()) return action; result |= action; } return result; } ForwardTraversal fork(bool analyze = false) const { ForwardTraversal ft = *this; if (analyze) { ft.analyzeOnly = true; ft.analyzeTerminate = true; } ft.actions = Analyzer::Action::None; return ft; } std::vector<ForwardTraversal> tryForkScope(Token* endBlock, bool isModified = false) const { if (analyzer->updateScope(endBlock, isModified)) { ForwardTraversal ft = fork(); return {std::move(ft)}; } return std::vector<ForwardTraversal> {}; } std::vector<ForwardTraversal> tryForkUpdateScope(Token* endBlock, bool isModified = false) const { std::vector<ForwardTraversal> result = tryForkScope(endBlock, isModified); for (ForwardTraversal& ft : result) ft.updateScope(endBlock); return result; } static bool hasGoto(const Token* endBlock) { return Token::findsimplematch(endBlock->link(), "goto", endBlock); } static bool hasJump(const Token* endBlock) { return Token::findmatch(endBlock->link(), "goto|break", endBlock); } bool hasInnerReturnScope(const Token* start, const Token* end) const { for (const Token* tok=start; tok != end; tok = tok->previous()) { if (Token::simpleMatch(tok, "}")) { const Token* ftok = nullptr; const bool r = isReturnScope(tok, settings.library, &ftok); if (r) return true; } } return false; } bool isEscapeScope(const Token* endBlock, bool& unknown) const { const Token* ftok = nullptr; const bool r = isReturnScope(endBlock, settings.library, &ftok); if (!r && ftok) unknown = true; return r; } enum class Status : std::uint8_t { None, Inconclusive, }; Analyzer::Action analyzeScope(const Token* endBlock) const { return analyzeRange(endBlock->link(), endBlock); } Analyzer::Action checkScope(Token* endBlock) const { Analyzer::Action a = analyzeScope(endBlock); tryForkUpdateScope(endBlock, a.isModified()); return a; } Analyzer::Action checkScope(const Token* endBlock) const { Analyzer::Action a = analyzeScope(endBlock); return a; } bool checkBranch(Branch& branch) const { Analyzer::Action a = analyzeScope(branch.endBlock); branch.action = a; std::vector<ForwardTraversal> ft1 = tryForkUpdateScope(branch.endBlock, a.isModified()); const bool bail = hasGoto(branch.endBlock); if (!a.isModified() && !bail) { if (ft1.empty()) { // Traverse into the branch to see if there is a conditional escape if (!branch.escape && hasInnerReturnScope(branch.endBlock->previous(), branch.endBlock->link())) { ForwardTraversal ft2 = fork(true); ft2.updateScope(branch.endBlock); if (ft2.terminate == Analyzer::Terminate::Escape) { branch.escape = true; branch.escapeUnknown = false; } } } else { if (ft1.front().terminate == Analyzer::Terminate::Escape) { branch.escape = true; branch.escapeUnknown = false; } } } return bail; } bool reentersLoop(Token* endBlock, const Token* condTok, const Token* stepTok) const { if (!condTok) return true; if (Token::simpleMatch(condTok, ":")) return true; bool stepChangesCond = false; if (stepTok) { std::pair<const Token*, const Token*> exprToks = stepTok->findExpressionStartEndTokens(); if (exprToks.first != nullptr && exprToks.second != nullptr) stepChangesCond |= findExpressionChanged(condTok, exprToks.first, exprToks.second->next(), settings) != nullptr; } const bool bodyChangesCond = findExpressionChanged(condTok, endBlock->link(), endBlock, settings); // Check for mutation in the condition const bool condChanged = nullptr != findAstNode(condTok, [&](const Token* tok) { return isVariableChanged(tok, 0, settings); }); const bool changed = stepChangesCond || bodyChangesCond || condChanged; if (!changed) return true; ForwardTraversal ft = fork(true); ft.updateScope(endBlock); return ft.isConditionTrue(condTok) && bodyChangesCond; } Progress updateInnerLoop(Token* endBlock, Token* stepTok, Token* condTok) { loopEnds.push_back(endBlock); OnExit oe{[&] { loopEnds.pop_back(); }}; if (endBlock && updateScope(endBlock) == Progress::Break) return Break(); if (stepTok && updateRecursive(stepTok) == Progress::Break) return Break(); if (condTok && !Token::simpleMatch(condTok, ":") && updateRecursive(condTok) == Progress::Break) return Break(); return Progress::Continue; } Progress updateLoop(const Token* endToken, Token* endBlock, Token* condTok, Token* initTok = nullptr, Token* stepTok = nullptr, bool exit = false) { if (initTok && updateRecursive(initTok) == Progress::Break) return Break(); const bool isDoWhile = precedes(endBlock, condTok); bool checkThen = true; bool checkElse = false; if (condTok && !Token::simpleMatch(condTok, ":")) std::tie(checkThen, checkElse) = evalCond(condTok, isDoWhile ? endBlock->previous() : nullptr); // exiting a do while(false) if (checkElse && exit) { if (hasJump(endBlock)) { if (!analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); if (analyzer->isConditional() && stopUpdates()) return Break(Analyzer::Terminate::Conditional); } return Progress::Continue; } Analyzer::Action bodyAnalysis = analyzeScope(endBlock); Analyzer::Action allAnalysis = bodyAnalysis; Analyzer::Action condAnalysis; if (condTok) { condAnalysis = analyzeRecursive(condTok); allAnalysis |= condAnalysis; } if (stepTok) allAnalysis |= analyzeRecursive(stepTok); actions |= allAnalysis; // do while(false) is not really a loop if (checkElse && isDoWhile && (condTok->hasKnownIntValue() || (!bodyAnalysis.isModified() && !condAnalysis.isModified() && condAnalysis.isRead()))) { if (updateScope(endBlock) == Progress::Break) return Break(); return updateRecursive(condTok); } if (allAnalysis.isInconclusive()) { if (!analyzer->lowerToInconclusive()) return Break(Analyzer::Terminate::Bail); } else if (allAnalysis.isModified() || (exit && allAnalysis.isIdempotent())) { if (!analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); } if (condTok && !Token::simpleMatch(condTok, ":")) { if (!isDoWhile || (!bodyAnalysis.isModified() && !bodyAnalysis.isIdempotent())) if (updateRecursive(condTok) == Progress::Break) return Break(); } if (!checkThen && !checkElse && !isDoWhile && stopOnCondition(condTok) && stopUpdates()) return Break(Analyzer::Terminate::Conditional); // condition is false, we don't enter the loop if (checkElse && !isDoWhile) return Progress::Continue; if (checkThen || isDoWhile) { // Since we are re-entering the loop then assume the condition is true to update the state if (exit) analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); if (updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break) return Break(); // If loop re-enters then it could be modified again if (allAnalysis.isModified() && reentersLoop(endBlock, condTok, stepTok)) return Break(Analyzer::Terminate::Bail); if (allAnalysis.isIncremental()) return Break(Analyzer::Terminate::Bail); } else if (allAnalysis.isModified()) { std::vector<ForwardTraversal> ftv = tryForkScope(endBlock, allAnalysis.isModified()); bool forkContinue = true; for (ForwardTraversal& ft : ftv) { if (condTok) ft.analyzer->assume(condTok, false, Analyzer::Assume::Quiet); if (ft.updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break) forkContinue = false; } if (allAnalysis.isModified() || !forkContinue) { // TODO: Don't bail on missing condition if (!condTok) return Break(Analyzer::Terminate::Bail); if (analyzer->isConditional() && stopUpdates()) return Break(Analyzer::Terminate::Conditional); analyzer->assume(condTok, false); } if (forkContinue) { for (ForwardTraversal& ft : ftv) { if (!ft.actions.isIncremental()) ft.updateRange(endBlock, endToken); } } if (allAnalysis.isIncremental()) return Break(Analyzer::Terminate::Bail); } else { if (updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break) return Progress::Break; if (allAnalysis.isIncremental()) return Break(Analyzer::Terminate::Bail); } return Progress::Continue; } Progress updateLoopExit(const Token* endToken, Token* endBlock, Token* condTok, Token* initTok = nullptr, Token* stepTok = nullptr) { return updateLoop(endToken, endBlock, condTok, initTok, stepTok, true); } Progress updateScope(Token* endBlock, int depth = 20) { if (!endBlock) return Break(); assert(endBlock->link()); Token* ctx = endBlock->link()->previous(); if (Token::simpleMatch(ctx, ")")) ctx = ctx->link()->previous(); if (ctx) analyzer->updateState(ctx); return updateRange(endBlock->link(), endBlock, depth); } Progress updateRange(Token* start, const Token* end, int depth = 20) { if (depth < 0) return Break(Analyzer::Terminate::Bail); std::size_t i = 0; for (Token* tok = start; precedes(tok, end); tok = tok->next()) { Token* next = nullptr; if (tok->index() <= i) throw InternalError(tok, "Cyclic forward analysis."); i = tok->index(); if (tok->link()) { // Skip casts.. if (tok->str() == "(" && !tok->astOperand2() && tok->isCast()) { tok = tok->link(); continue; } // Skip template arguments.. if (tok->str() == "<") { tok = tok->link(); continue; } } // Evaluate RHS of assignment before LHS if (Token* assignTok = assignExpr(tok)) { if (updateRecursive(assignTok) == Progress::Break) return Break(); tok = nextAfterAstRightmostLeaf(assignTok); if (!tok) return Break(); } else if (Token::simpleMatch(tok, ") {") && Token::Match(tok->link()->previous(), "for|while (") && !Token::simpleMatch(tok->link()->astOperand2(), ":")) { // In the middle of a loop structure so bail return Break(Analyzer::Terminate::Bail); } else if (tok->str() == ";" && tok->astParent()) { Token* top = tok->astTop(); if (Token::Match(top->previous(), "for|while (") && Token::simpleMatch(top->link(), ") {")) { Token* endCond = top->link(); Token* endBlock = endCond->linkAt(1); Token* condTok = getCondTok(top); Token* stepTok = getStepTok(top); // The semicolon should belong to the initTok otherwise something went wrong, so just bail if (tok->astOperand2() != condTok && !Token::simpleMatch(tok->astOperand2(), ";")) return Break(Analyzer::Terminate::Bail); if (updateLoop(end, endBlock, condTok, nullptr, stepTok) == Progress::Break) return Break(); } } else if (tok->str() == "break") { const Token *scopeEndToken = findNextTokenFromBreak(tok); if (!scopeEndToken) return Break(); tok = skipTo(tok, scopeEndToken, end); if (!precedes(tok, end)) return Break(Analyzer::Terminate::Escape); if (!analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); // TODO: Don't break, instead move to the outer scope if (!tok) return Break(); } else if (!tok->variable() && (Token::Match(tok, "%name% :") || tok->str() == "case")) { if (!analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); } else if (tok->link() && tok->str() == "}" && tok == tok->scope()->bodyEnd) { // might be an init list const Scope* scope = tok->scope(); if (contains({Scope::eDo, Scope::eFor, Scope::eWhile, Scope::eIf, Scope::eElse, Scope::eSwitch}, scope->type)) { const bool inElse = scope->type == Scope::eElse; const bool inDoWhile = scope->type == Scope::eDo; const bool inLoop = contains({Scope::eDo, Scope::eFor, Scope::eWhile}, scope->type); Token* condTok = getCondTokFromEnd(tok); if (!condTok) return Break(); if (!condTok->hasKnownIntValue() || inLoop) { if (!analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); } else if (condTok->values().front().intvalue == inElse) { return Break(); } // Handle loop if (inLoop) { Token* stepTok = getStepTokFromEnd(tok); bool checkThen, checkElse; std::tie(checkThen, checkElse) = evalCond(condTok); if (stepTok && !checkElse) { if (updateRecursive(stepTok) == Progress::Break) return Break(); if (updateRecursive(condTok) == Progress::Break) return Break(); // Reevaluate condition std::tie(checkThen, checkElse) = evalCond(condTok); } if (!checkElse) { if (updateLoopExit(end, tok, condTok, nullptr, stepTok) == Progress::Break) return Break(); } } analyzer->assume(condTok, !inElse, Analyzer::Assume::Quiet); assert(!inDoWhile || Token::simpleMatch(tok, "} while (")); if (Token::simpleMatch(tok, "} else {") || inDoWhile) tok = tok->linkAt(2); } else if (contains({Scope::eTry, Scope::eCatch}, scope->type)) { if (!analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); } else if (scope->type == Scope::eLambda) { return Break(); } } else if (tok->isControlFlowKeyword() && Token::Match(tok, "if|while|for (") && Token::simpleMatch(tok->linkAt(1), ") {")) { if ((settings.vfOptions.maxForwardBranches > 0) && (++branchCount > settings.vfOptions.maxForwardBranches)) { // TODO: should be logged on function-level instead of file-level reportError(Severity::information, "normalCheckLevelMaxBranches", "Limiting analysis of branches. Use --check-level=exhaustive to analyze all branches."); return Break(Analyzer::Terminate::Bail); } Token* endCond = tok->linkAt(1); Token* endBlock = endCond->linkAt(1); Token* condTok = getCondTok(tok); Token* initTok = getInitTok(tok); if (initTok && updateRecursive(initTok) == Progress::Break) return Break(); if (Token::Match(tok, "for|while (")) { // For-range loop if (Token::simpleMatch(condTok, ":")) { Token* conTok = condTok->astOperand2(); if (conTok && updateRecursive(conTok) == Progress::Break) return Break(); bool isEmpty = false; std::vector<MathLib::bigint> result = analyzer->evaluate(Analyzer::Evaluate::ContainerEmpty, conTok); if (result.empty()) analyzer->assume(conTok, false, Analyzer::Assume::ContainerEmpty); else isEmpty = result.front() != 0; if (!isEmpty && updateLoop(end, endBlock, condTok) == Progress::Break) return Break(); } else { Token* stepTok = getStepTok(tok); // Dont pass initTok since it was already evaluated if (updateLoop(end, endBlock, condTok, nullptr, stepTok) == Progress::Break) return Break(); } tok = endBlock; } else { // Traverse condition if (updateRecursive(condTok) == Progress::Break) return Break(); Branch thenBranch{endBlock}; Branch elseBranch{endBlock->tokAt(2) ? endBlock->linkAt(2) : nullptr}; // Check if condition is true or false std::tie(thenBranch.check, elseBranch.check) = evalCond(condTok); if (!thenBranch.check && !elseBranch.check && stopOnCondition(condTok) && stopUpdates()) return Break(Analyzer::Terminate::Conditional); const bool hasElse = Token::simpleMatch(endBlock, "} else {"); bool bail = false; // Traverse then block thenBranch.escape = isEscapeScope(endBlock, thenBranch.escapeUnknown); if (thenBranch.check) { thenBranch.active = true; if (updateScope(endBlock, depth - 1) == Progress::Break) return Break(); } else if (!elseBranch.check) { thenBranch.active = true; if (checkBranch(thenBranch)) bail = true; } // Traverse else block if (hasElse) { elseBranch.escape = isEscapeScope(endBlock->linkAt(2), elseBranch.escapeUnknown); if (elseBranch.check) { elseBranch.active = true; const Progress result = updateScope(endBlock->linkAt(2), depth - 1); if (result == Progress::Break) return Break(); } else if (!thenBranch.check) { elseBranch.active = true; if (checkBranch(elseBranch)) bail = true; } tok = endBlock->linkAt(2); } else { tok = endBlock; } if (thenBranch.active) actions |= thenBranch.action; if (elseBranch.active) actions |= elseBranch.action; if (bail) return Break(Analyzer::Terminate::Bail); if (thenBranch.isDead() && elseBranch.isDead()) { if (thenBranch.isModified() && elseBranch.isModified()) return Break(Analyzer::Terminate::Modified); if (thenBranch.isConclusiveEscape() && elseBranch.isConclusiveEscape()) return Break(Analyzer::Terminate::Escape); return Break(Analyzer::Terminate::Bail); } // Conditional return if (thenBranch.active && thenBranch.isEscape() && !hasElse) { if (!thenBranch.isConclusiveEscape()) { if (!analyzer->lowerToInconclusive()) return Break(Analyzer::Terminate::Bail); } else if (thenBranch.check) { return Break(); } else { if (analyzer->isConditional() && stopUpdates()) return Break(Analyzer::Terminate::Conditional); analyzer->assume(condTok, false); } } if (thenBranch.isInconclusive() || elseBranch.isInconclusive()) { if (!analyzer->lowerToInconclusive()) return Break(Analyzer::Terminate::Bail); } else if (thenBranch.isModified() || elseBranch.isModified()) { if (!hasElse && analyzer->isConditional() && stopUpdates()) return Break(Analyzer::Terminate::Conditional); if (!analyzer->lowerToPossible()) return Break(Analyzer::Terminate::Bail); analyzer->assume(condTok, elseBranch.isModified()); } } } else if (Token::simpleMatch(tok, "try {")) { Token* endBlock = tok->linkAt(1); ForwardTraversal tryTraversal = fork(); tryTraversal.updateScope(endBlock, depth - 1); bool bail = tryTraversal.actions.isModified(); if (bail) { actions = tryTraversal.actions; terminate = tryTraversal.terminate; return Break(); } while (Token::simpleMatch(endBlock, "} catch (")) { Token* endCatch = endBlock->linkAt(2); if (!Token::simpleMatch(endCatch, ") {")) return Break(); endBlock = endCatch->linkAt(1); ForwardTraversal ft = fork(); ft.updateScope(endBlock, depth - 1); bail |= ft.terminate != Analyzer::Terminate::None || ft.actions.isModified(); } if (bail) return Break(); tok = endBlock; } else if (Token::simpleMatch(tok, "do {")) { Token* endBlock = tok->linkAt(1); Token* condTok = Token::simpleMatch(endBlock, "} while (") ? endBlock->tokAt(2)->astOperand2() : nullptr; if (updateLoop(end, endBlock, condTok) == Progress::Break) return Break(); if (condTok) tok = endBlock->linkAt(2)->next(); else tok = endBlock; } else if (Token::Match(tok, "assert|ASSERT (")) { const Token* condTok = tok->next()->astOperand2(); bool checkThen, checkElse; std::tie(checkThen, checkElse) = evalCond(condTok); if (checkElse) return Break(); if (!checkThen) analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute); } else if (Token::simpleMatch(tok, "switch (")) { if (updateRecursive(tok->next()->astOperand2()) == Progress::Break) return Break(); actions |= Analyzer::Action::Write; // bailout for switch scope return Break(); } else if (Token* callTok = callExpr(tok)) { // TODO: Dont traverse tokens a second time if (start != callTok && tok != callTok && updateRecursive(callTok->astOperand1()) == Progress::Break) return Break(); // Since the call could be an unknown macro, traverse the tokens as a range instead of recursively if (!Token::simpleMatch(callTok, "( )") && updateRange(callTok->next(), callTok->link(), depth - 1) == Progress::Break) return Break(); if (updateTok(callTok) == Progress::Break) return Break(); tok = callTok->link(); if (!tok) return Break(); } else { if (updateTok(tok, &next) == Progress::Break) return Break(); if (next) { if (precedes(next, end)) tok = next->previous(); else return Progress::Continue; } } // Prevent infinite recursion if (tok->next() == start) break; } return Progress::Continue; } void reportError(Severity severity, const std::string& id, const std::string& msg) { ErrorMessage::FileLocation loc(tokenList.getSourceFilePath(), 0, 0); const ErrorMessage errmsg({std::move(loc)}, tokenList.getSourceFilePath(), severity, msg, id, Certainty::normal); errorLogger.reportErr(errmsg); } static bool isFunctionCall(const Token* tok) { if (!Token::simpleMatch(tok, "(")) return false; if (tok->isCast()) return false; if (!tok->isBinaryOp()) return false; if (Token::simpleMatch(tok->link(), ") {")) return false; if (isUnevaluated(tok->previous())) return false; return Token::Match(tok->previous(), "%name%|)|]|>"); } static Token* assignExpr(Token* tok) { while (tok->astParent() && astIsLHS(tok)) { if (tok->astParent()->isAssignmentOp()) return tok->astParent(); tok = tok->astParent(); } return nullptr; } static Token* callExpr(Token* tok) { while (tok->astParent() && astIsLHS(tok)) { if (!Token::Match(tok, "%name%|::|<|.")) break; if (Token::simpleMatch(tok, "<") && !tok->link()) break; tok = tok->astParent(); } if (isFunctionCall(tok)) return tok; return nullptr; } static Token* skipTo(Token* tok, const Token* dest, const Token* end = nullptr) { if (end && dest->index() > end->index()) return nullptr; const int i = dest->index() - tok->index(); if (i > 0) return tok->tokAt(dest->index() - tok->index()); return nullptr; } static Token* getStepTokFromEnd(Token* tok) { if (!Token::simpleMatch(tok, "}")) return nullptr; Token* end = tok->link()->previous(); if (!Token::simpleMatch(end, ")")) return nullptr; return getStepTok(end->link()); } }; } Analyzer::Result valueFlowGenericForward(Token* start, const Token* end, const ValuePtr<Analyzer>& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) { if (a->invalid()) return Analyzer::Result{Analyzer::Action::None, Analyzer::Terminate::Bail}; ForwardTraversal ft{a, tokenList, errorLogger, settings}; if (start) ft.analyzer->updateState(start); ft.updateRange(start, end); return Analyzer::Result{ ft.actions, ft.terminate }; } Analyzer::Result valueFlowGenericForward(Token* start, const ValuePtr<Analyzer>& a, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings) { if (Settings::terminated()) throw TerminateException(); if (a->invalid()) return Analyzer::Result{Analyzer::Action::None, Analyzer::Terminate::Bail}; ForwardTraversal ft{a, tokenList, errorLogger, settings}; (void)ft.updateRecursive(start); return Analyzer::Result{ ft.actions, ft.terminate }; }
44,641
C++
.cpp
879
33.407281
181
0.498238
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,123
vf_iteratorinfer.cpp
danmar_cppcheck/lib/vf_iteratorinfer.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_iteratorinfer.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_common.h" #include "vf_settokenvalue.h" #include <list> #include <utility> namespace ValueFlow { void analyzeIteratorInfer(TokenList &tokenlist, const Settings &settings) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (!tok->scope()) continue; if (!tok->scope()->isExecutable()) continue; std::list<Value> values = getIteratorValues(tok->values()); values.remove_if([&](const Value& v) { if (!v.isImpossible()) return true; if (!v.condition) return true; if (v.bound != Value::Bound::Point) return true; if (v.isIteratorEndValue() && v.intvalue <= 0) return true; if (v.isIteratorStartValue() && v.intvalue >= 0) return true; return false; }); for (Value& v:values) { v.setPossible(); if (v.isIteratorStartValue()) v.intvalue++; if (v.isIteratorEndValue()) v.intvalue--; setTokenValue(tok, std::move(v), settings); } } } }
2,177
C++
.cpp
60
27.533333
77
0.586174
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,124
vf_number.cpp
danmar_cppcheck/lib/vf_number.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_number.h" #include "settings.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_common.h" #include "vf_settokenvalue.h" #include <string> #include <utility> namespace ValueFlow { void analyzeNumber(TokenList &tokenlist, const Settings& settings) { for (Token *tok = tokenlist.front(); tok;) { tok = valueFlowSetConstantValue(tok, settings); } if (tokenlist.isCPP() || settings.standards.c >= Standards::C23) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (tok->isName() && !tok->varId() && Token::Match(tok, "false|true")) { ValueFlow::Value value(tok->str() == "true"); if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok, std::move(value), settings); } else if (Token::Match(tok, "[(,] NULL [,)]")) { // NULL function parameters are not simplified in the // normal tokenlist ValueFlow::Value value(0); if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); } } } } }
2,080
C++
.cpp
52
32.115385
88
0.607814
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,125
analyzerinfo.cpp
danmar_cppcheck/lib/analyzerinfo.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "analyzerinfo.h" #include "errorlogger.h" #include "filesettings.h" #include "path.h" #include "utils.h" #include <cstring> #include <map> #include "xml.h" AnalyzerInformation::~AnalyzerInformation() { close(); } static std::string getFilename(const std::string &fullpath) { std::string::size_type pos1 = fullpath.find_last_of("/\\"); pos1 = (pos1 == std::string::npos) ? 0U : (pos1 + 1U); std::string::size_type pos2 = fullpath.rfind('.'); if (pos2 < pos1) pos2 = std::string::npos; if (pos2 != std::string::npos) pos2 = pos2 - pos1; return fullpath.substr(pos1,pos2); } void AnalyzerInformation::writeFilesTxt(const std::string &buildDir, const std::list<std::string> &sourcefiles, const std::string &userDefines, const std::list<FileSettings> &fileSettings) { std::map<std::string, unsigned int> fileCount; const std::string filesTxt(buildDir + "/files.txt"); std::ofstream fout(filesTxt); for (const std::string &f : sourcefiles) { const std::string afile = getFilename(f); fout << afile << ".a" << (++fileCount[afile]) << "::" << Path::simplifyPath(f) << '\n'; if (!userDefines.empty()) fout << afile << ".a" << (++fileCount[afile]) << ":" << userDefines << ":" << Path::simplifyPath(f) << '\n'; } for (const FileSettings &fs : fileSettings) { const std::string afile = getFilename(fs.filename()); fout << afile << ".a" << (++fileCount[afile]) << ":" << fs.cfg << ":" << Path::simplifyPath(fs.filename()) << std::endl; } } void AnalyzerInformation::close() { mAnalyzerInfoFile.clear(); if (mOutputStream.is_open()) { mOutputStream << "</analyzerinfo>\n"; mOutputStream.close(); } } static bool skipAnalysis(const std::string &analyzerInfoFile, std::size_t hash, std::list<ErrorMessage> &errors) { tinyxml2::XMLDocument doc; const tinyxml2::XMLError error = doc.LoadFile(analyzerInfoFile.c_str()); if (error != tinyxml2::XML_SUCCESS) return false; const tinyxml2::XMLElement * const rootNode = doc.FirstChildElement(); if (rootNode == nullptr) return false; const char *attr = rootNode->Attribute("hash"); if (!attr || attr != std::to_string(hash)) return false; for (const tinyxml2::XMLElement *e = rootNode->FirstChildElement(); e; e = e->NextSiblingElement()) { if (std::strcmp(e->Name(), "error") == 0) errors.emplace_back(e); } return true; } std::string AnalyzerInformation::getAnalyzerInfoFileFromFilesTxt(std::istream& filesTxt, const std::string &sourcefile, const std::string &cfg) { std::string line; const std::string end(':' + cfg + ':' + Path::simplifyPath(sourcefile)); while (std::getline(filesTxt,line)) { if (line.size() <= end.size() + 2U) continue; if (!endsWith(line, end.c_str(), end.size())) continue; return line.substr(0,line.find(':')); } return ""; } std::string AnalyzerInformation::getAnalyzerInfoFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg) { std::ifstream fin(Path::join(buildDir, "files.txt")); if (fin.is_open()) { const std::string& ret = getAnalyzerInfoFileFromFilesTxt(fin, sourcefile, cfg); if (!ret.empty()) return Path::join(buildDir, ret); } const std::string::size_type pos = sourcefile.rfind('/'); std::string filename; if (pos == std::string::npos) filename = sourcefile; else filename = sourcefile.substr(pos + 1); return Path::join(buildDir, filename) + ".analyzerinfo"; } bool AnalyzerInformation::analyzeFile(const std::string &buildDir, const std::string &sourcefile, const std::string &cfg, std::size_t hash, std::list<ErrorMessage> &errors) { if (buildDir.empty() || sourcefile.empty()) return true; close(); mAnalyzerInfoFile = AnalyzerInformation::getAnalyzerInfoFile(buildDir,sourcefile,cfg); if (skipAnalysis(mAnalyzerInfoFile, hash, errors)) return false; mOutputStream.open(mAnalyzerInfoFile); if (mOutputStream.is_open()) { mOutputStream << "<?xml version=\"1.0\"?>\n"; mOutputStream << "<analyzerinfo hash=\"" << hash << "\">\n"; } else { mAnalyzerInfoFile.clear(); } return true; } void AnalyzerInformation::reportErr(const ErrorMessage &msg) { if (mOutputStream.is_open()) mOutputStream << msg.toXML() << '\n'; } void AnalyzerInformation::setFileInfo(const std::string &check, const std::string &fileInfo) { if (mOutputStream.is_open() && !fileInfo.empty()) mOutputStream << " <FileInfo check=\"" << check << "\">\n" << fileInfo << " </FileInfo>\n"; }
5,526
C++
.cpp
138
35.268116
188
0.659332
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,126
clangimport.cpp
danmar_cppcheck/lib/clangimport.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "clangimport.h" #include "errortypes.h" #include "mathlib.h" #include "settings.h" #include "standards.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include "utils.h" #include "vfvalue.h" #include <algorithm> #include <cctype> #include <cstring> #include <iostream> #include <iterator> #include <list> #include <map> #include <memory> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> #include <numeric> static const std::string AccessSpecDecl = "AccessSpecDecl"; static const std::string ArraySubscriptExpr = "ArraySubscriptExpr"; static const std::string BinaryOperator = "BinaryOperator"; static const std::string BreakStmt = "BreakStmt"; static const std::string CallExpr = "CallExpr"; static const std::string CaseStmt = "CaseStmt"; static const std::string CharacterLiteral = "CharacterLiteral"; static const std::string ClassTemplateDecl = "ClassTemplateDecl"; static const std::string ClassTemplateSpecializationDecl = "ClassTemplateSpecializationDecl"; static const std::string ConditionalOperator = "ConditionalOperator"; static const std::string ConstantExpr = "ConstantExpr"; static const std::string CompoundAssignOperator = "CompoundAssignOperator"; static const std::string CompoundStmt = "CompoundStmt"; static const std::string ContinueStmt = "ContinueStmt"; static const std::string CStyleCastExpr = "CStyleCastExpr"; static const std::string CXXBindTemporaryExpr = "CXXBindTemporaryExpr"; static const std::string CXXBoolLiteralExpr = "CXXBoolLiteralExpr"; static const std::string CXXConstructorDecl = "CXXConstructorDecl"; static const std::string CXXConstructExpr = "CXXConstructExpr"; static const std::string CXXDefaultArgExpr = "CXXDefaultArgExpr"; static const std::string CXXDeleteExpr = "CXXDeleteExpr"; static const std::string CXXDestructorDecl = "CXXDestructorDecl"; static const std::string CXXForRangeStmt = "CXXForRangeStmt"; static const std::string CXXFunctionalCastExpr = "CXXFunctionalCastExpr"; static const std::string CXXMemberCallExpr = "CXXMemberCallExpr"; static const std::string CXXMethodDecl = "CXXMethodDecl"; static const std::string CXXNewExpr = "CXXNewExpr"; static const std::string CXXNullPtrLiteralExpr = "CXXNullPtrLiteralExpr"; static const std::string CXXOperatorCallExpr = "CXXOperatorCallExpr"; static const std::string CXXRecordDecl = "CXXRecordDecl"; static const std::string CXXStaticCastExpr = "CXXStaticCastExpr"; static const std::string CXXStdInitializerListExpr = "CXXStdInitializerListExpr"; static const std::string CXXTemporaryObjectExpr = "CXXTemporaryObjectExpr"; static const std::string CXXThisExpr = "CXXThisExpr"; static const std::string CXXThrowExpr = "CXXThrowExpr"; static const std::string DeclRefExpr = "DeclRefExpr"; static const std::string DeclStmt = "DeclStmt"; static const std::string DefaultStmt = "DefaultStmt"; static const std::string DoStmt = "DoStmt"; static const std::string EnumConstantDecl = "EnumConstantDecl"; static const std::string EnumDecl = "EnumDecl"; static const std::string ExprWithCleanups = "ExprWithCleanups"; static const std::string FieldDecl = "FieldDecl"; static const std::string FloatingLiteral = "FloatingLiteral"; static const std::string ForStmt = "ForStmt"; static const std::string FunctionDecl = "FunctionDecl"; static const std::string FunctionTemplateDecl = "FunctionTemplateDecl"; static const std::string GotoStmt = "GotoStmt"; static const std::string IfStmt = "IfStmt"; static const std::string ImplicitCastExpr = "ImplicitCastExpr"; static const std::string InitListExpr = "InitListExpr"; static const std::string IntegerLiteral = "IntegerLiteral"; static const std::string LabelStmt = "LabelStmt"; static const std::string LinkageSpecDecl = "LinkageSpecDecl"; static const std::string MaterializeTemporaryExpr = "MaterializeTemporaryExpr"; static const std::string MemberExpr = "MemberExpr"; static const std::string NamespaceDecl = "NamespaceDecl"; static const std::string NullStmt = "NullStmt"; static const std::string ParenExpr = "ParenExpr"; static const std::string ParmVarDecl = "ParmVarDecl"; static const std::string RecordDecl = "RecordDecl"; static const std::string ReturnStmt = "ReturnStmt"; static const std::string StringLiteral = "StringLiteral"; static const std::string SwitchStmt = "SwitchStmt"; static const std::string TemplateArgument = "TemplateArgument"; static const std::string TypedefDecl = "TypedefDecl"; static const std::string UnaryOperator = "UnaryOperator"; static const std::string UnaryExprOrTypeTraitExpr = "UnaryExprOrTypeTraitExpr"; static const std::string VarDecl = "VarDecl"; static const std::string WhileStmt = "WhileStmt"; static std::string unquote(const std::string &s) { return (s[0] == '\'') ? s.substr(1, s.size() - 2) : s; } static std::vector<std::string> splitString(const std::string &line) { std::vector<std::string> ret; std::string::size_type pos1 = line.find_first_not_of(' '); while (pos1 < line.size()) { std::string::size_type pos2; if (std::strchr("*()", line[pos1])) { ret.push_back(line.substr(pos1,1)); pos1 = line.find_first_not_of(' ', pos1 + 1); continue; } if (line[pos1] == '<') pos2 = line.find('>', pos1); else if (line[pos1] == '\"') pos2 = line.find('\"', pos1+1); else if (line[pos1] == '\'') { pos2 = line.find('\'', pos1+1); if (pos2 < (int)line.size() - 3 && line.compare(pos2, 3, "\':\'", 0, 3) == 0) pos2 = line.find('\'', pos2 + 3); } else { pos2 = pos1; while (pos2 < line.size() && (line[pos2] == '_' || line[pos2] == ':' || std::isalnum((unsigned char)line[pos2]))) ++pos2; if (pos2 > pos1 && pos2 < line.size() && line[pos2] == '<' && std::isalpha(line[pos1])) { int tlevel = 1; while (++pos2 < line.size() && tlevel > 0) { if (line[pos2] == '<') ++tlevel; else if (line[pos2] == '>') --tlevel; } if (tlevel == 0 && pos2 < line.size() && line[pos2] == ' ') { ret.push_back(line.substr(pos1, pos2-pos1)); pos1 = pos2 + 1; continue; } } pos2 = line.find(' ', pos1) - 1; if ((std::isalpha(line[pos1]) || line[pos1] == '_') && line.find("::", pos1) < pos2 && line.find("::", pos1) < line.find('<', pos1)) { pos2 = line.find("::", pos1); ret.push_back(line.substr(pos1, pos2-pos1)); ret.emplace_back("::"); pos1 = pos2 + 2; continue; } if ((std::isalpha(line[pos1]) || line[pos1] == '_') && line.find('<', pos1) < pos2 && line.find("<<",pos1) != line.find('<',pos1) && line.find('>', pos1) != std::string::npos && line.find('>', pos1) > pos2) { int level = 0; for (pos2 = pos1; pos2 < line.size(); ++pos2) { if (line[pos2] == '<') ++level; else if (line[pos2] == '>') { if (level <= 1) break; --level; } } if (level > 1 && pos2 + 1 >= line.size()) return std::vector<std::string> {}; pos2 = line.find(' ', pos2); if (pos2 != std::string::npos) --pos2; } } if (pos2 == std::string::npos) { ret.push_back(line.substr(pos1)); break; } ret.push_back(line.substr(pos1, pos2+1-pos1)); pos1 = line.find_first_not_of(' ', pos2 + 1); } return ret; } namespace clangimport { struct Data { struct Decl { explicit Decl(Scope *scope) : scope(scope) {} Decl(Token *def, Variable *var) : def(def), var(var) {} Decl(Token *def, Function *function) : def(def), function(function) {} Decl(Token *def, Enumerator *enumerator) : def(def), enumerator(enumerator) {} void ref(Token *tok) const { if (enumerator) tok->enumerator(enumerator); if (function) tok->function(function); if (var) { tok->variable(var); tok->varId(var->declarationId()); } } Token* def{}; Enumerator* enumerator{}; Function* function{}; Scope* scope{}; Variable* var{}; }; const Settings *mSettings = nullptr; SymbolDatabase *mSymbolDatabase = nullptr; int enumValue = 0; void enumDecl(const std::string &addr, Token *nameToken, Enumerator *enumerator) { Decl decl(nameToken, enumerator); mDeclMap.insert(std::pair<std::string, Decl>(addr, decl)); nameToken->enumerator(enumerator); notFound(addr); } void funcDecl(const std::string &addr, Token *nameToken, Function *function) { Decl decl(nameToken, function); mDeclMap.insert(std::pair<std::string, Decl>(addr, decl)); nameToken->function(function); notFound(addr); } void scopeDecl(const std::string &addr, Scope *scope) { Decl decl(scope); mDeclMap.insert(std::pair<std::string, Decl>(addr, decl)); } void varDecl(const std::string &addr, Token *def, Variable *var) { Decl decl(def, var); mDeclMap.insert(std::pair<std::string, Decl>(addr, decl)); def->varId(++mVarId); def->variable(var); if (def->valueType()) var->setValueType(*def->valueType()); notFound(addr); } void replaceVarDecl(const Variable *from, Variable *to) { for (auto &it: mDeclMap) { Decl &decl = it.second; if (decl.var == from) decl.var = to; } } void ref(const std::string &addr, Token *tok) { auto it = mDeclMap.find(addr); if (it != mDeclMap.end()) it->second.ref(tok); else mNotFound[addr].push_back(tok); } std::vector<const Variable *> getVariableList() const { std::vector<const Variable *> ret; ret.resize(mVarId + 1, nullptr); for (const auto& it: mDeclMap) { if (it.second.var) ret[it.second.var->declarationId()] = it.second.var; } return ret; } bool hasDecl(const std::string &addr) const { return mDeclMap.find(addr) != mDeclMap.end(); } const Scope *getScope(const std::string &addr) { auto it = mDeclMap.find(addr); return (it == mDeclMap.end() ? nullptr : it->second.scope); } // "}" tokens that are not end-of-scope std::set<Token *> mNotScope; std::map<const Scope *, AccessControl> scopeAccessControl; private: void notFound(const std::string &addr) { auto it = mNotFound.find(addr); if (it != mNotFound.end()) { for (Token *reftok: it->second) ref(addr, reftok); mNotFound.erase(it); } } std::map<std::string, Decl> mDeclMap; std::map<std::string, std::vector<Token *>> mNotFound; int mVarId = 0; }; class AstNode; using AstNodePtr = std::shared_ptr<AstNode>; class AstNode { public: AstNode(std::string nodeType, const std::string &ext, Data *data) : nodeType(std::move(nodeType)), mExtTokens(splitString(ext)), mData(data) {} std::string nodeType; std::vector<AstNodePtr> children; void setLocations(TokenList &tokenList, int file, int line, int col); void dumpAst(int num = 0, int indent = 0) const; void createTokens1(TokenList &tokenList) { //dumpAst(); // TODO: reactivate or remove if (!tokenList.back()) { setLocations(tokenList, 0, 1, 1); // FIXME: treat as C++ if no filename (i.e. no lang) is specified for now if (tokenList.getSourceFilePath().empty()) tokenList.setLang(Standards::Language::CPP); } else setLocations(tokenList, tokenList.back()->fileIndex(), tokenList.back()->linenr(), 1); createTokens(tokenList); if (nodeType == VarDecl || nodeType == RecordDecl || nodeType == TypedefDecl) addtoken(tokenList, ";"); mData->mNotScope.clear(); } AstNodePtr getChild(int c) { if (c >= children.size()) { std::ostringstream err; err << "ClangImport: AstNodePtr::getChild(" << c << ") out of bounds. children.size=" << children.size() << " " << nodeType; for (const std::string &s: mExtTokens) err << " " << s; throw InternalError(nullptr, err.str()); } return children[c]; } private: Token *createTokens(TokenList &tokenList); Token *addtoken(TokenList &tokenList, const std::string &str, bool valueType=true); const ::Type *addTypeTokens(TokenList &tokenList, const std::string &str, const Scope *scope = nullptr); void addFullScopeNameTokens(TokenList &tokenList, const Scope *recordScope); Scope *createScope(TokenList &tokenList, Scope::ScopeType scopeType, AstNodePtr astNode, const Token *def); Scope *createScope(TokenList &tokenList, Scope::ScopeType scopeType, const std::vector<AstNodePtr> &children2, const Token *def); Token *createTokensCall(TokenList &tokenList); void createTokensFunctionDecl(TokenList &tokenList); void createTokensForCXXRecord(TokenList &tokenList); Token *createTokensVarDecl(TokenList &tokenList); std::string getSpelling() const; std::string getType(int index = 0) const; std::string getFullType(int index = 0) const; bool isDefinition() const; std::string getTemplateParameters() const; const Scope *getNestedInScope(TokenList &tokenList); void setValueType(Token *tok); int mFile = 0; int mLine = 1; int mCol = 1; std::vector<std::string> mExtTokens; Data *mData; }; } std::string clangimport::AstNode::getSpelling() const { if (nodeType == CompoundAssignOperator) { std::size_t typeIndex = 1; while (typeIndex < mExtTokens.size() && mExtTokens[typeIndex][0] != '\'') typeIndex++; // name is next quoted token std::size_t nameIndex = typeIndex + 1; while (nameIndex < mExtTokens.size() && mExtTokens[nameIndex][0] != '\'') nameIndex++; return (nameIndex < mExtTokens.size()) ? unquote(mExtTokens[nameIndex]) : ""; } if (nodeType == UnaryExprOrTypeTraitExpr) { std::size_t typeIndex = 1; while (typeIndex < mExtTokens.size() && mExtTokens[typeIndex][0] != '\'') typeIndex++; const std::size_t nameIndex = typeIndex + 1; return (nameIndex < mExtTokens.size()) ? unquote(mExtTokens[nameIndex]) : ""; } int typeIndex = mExtTokens.size() - 1; if (nodeType == FunctionDecl || nodeType == CXXConstructorDecl || nodeType == CXXMethodDecl) { while (typeIndex >= 0 && mExtTokens[typeIndex][0] != '\'') typeIndex--; if (typeIndex <= 0) return ""; } if (nodeType == DeclRefExpr) { while (typeIndex > 0 && std::isalpha(mExtTokens[typeIndex][0])) typeIndex--; if (typeIndex <= 0) return ""; } const std::string &str = mExtTokens[typeIndex - 1]; if (startsWith(str,"col:")) return ""; if (startsWith(str,"<invalid")) return ""; if (nodeType == RecordDecl && str == "struct") return ""; return str; } std::string clangimport::AstNode::getType(int index) const { std::string type = getFullType(index); if (type.find(" (") != std::string::npos) { const std::string::size_type pos = type.find(" ("); type[pos] = '\''; type.erase(pos+1); } if (type.find(" *(") != std::string::npos) { const std::string::size_type pos = type.find(" *(") + 2; type[pos] = '\''; type.erase(pos+1); } if (type.find(" &(") != std::string::npos) { const std::string::size_type pos = type.find(" &(") + 2; type[pos] = '\''; type.erase(pos+1); } return unquote(type); } std::string clangimport::AstNode::getFullType(int index) const { std::size_t typeIndex = 1; while (typeIndex < mExtTokens.size() && mExtTokens[typeIndex][0] != '\'') typeIndex++; if (typeIndex >= mExtTokens.size()) return ""; std::string type = mExtTokens[typeIndex]; if (type.find("\':\'") != std::string::npos) { if (index == 0) type.erase(type.find("\':\'") + 1); else type.erase(0, type.find("\':\'") + 2); } return type; } bool clangimport::AstNode::isDefinition() const { return contains(mExtTokens, "definition"); } std::string clangimport::AstNode::getTemplateParameters() const { if (children.empty() || children[0]->nodeType != TemplateArgument) return ""; std::string templateParameters; for (const AstNodePtr& child: children) { if (child->nodeType == TemplateArgument) { if (templateParameters.empty()) templateParameters = "<"; else templateParameters += ","; templateParameters += unquote(child->mExtTokens.back()); } } return templateParameters + ">"; } // cppcheck-suppress unusedFunction // only used in comment void clangimport::AstNode::dumpAst(int num, int indent) const { (void)num; std::cout << std::string(indent, ' ') << nodeType; for (const auto& tok: mExtTokens) std::cout << " " << tok; std::cout << std::endl; for (int c = 0; c < children.size(); ++c) { if (children[c]) children[c]->dumpAst(c, indent + 2); else std::cout << std::string(indent + 2, ' ') << "<<<<NULL>>>>>" << std::endl; } } void clangimport::AstNode::setLocations(TokenList &tokenList, int file, int line, int col) { for (const std::string &ext: mExtTokens) { if (startsWith(ext, "<col:")) col = strToInt<int>(ext.substr(5, ext.find_first_of(",>", 5) - 5)); else if (startsWith(ext, "<line:")) { line = strToInt<int>(ext.substr(6, ext.find_first_of(":,>", 6) - 6)); const auto pos = ext.find(", col:"); if (pos != std::string::npos) col = strToInt<int>(ext.substr(pos+6, ext.find_first_of(":,>", pos+6) - (pos+6))); } else if (ext[0] == '<') { const std::string::size_type colon = ext.find(':'); if (colon != std::string::npos) { const bool windowsPath = colon == 2 && ext.size() > 3 && ext[2] == ':'; const std::string::size_type sep1 = windowsPath ? ext.find(':', 4) : colon; const std::string::size_type sep2 = ext.find(':', sep1 + 1); file = tokenList.appendFileIfNew(ext.substr(1, sep1 - 1)); line = strToInt<int>(ext.substr(sep1 + 1, sep2 - sep1 - 1)); } } } mFile = file; mLine = line; mCol = col; for (const auto& child: children) { if (child) child->setLocations(tokenList, file, line, col); } } Token *clangimport::AstNode::addtoken(TokenList &tokenList, const std::string &str, bool valueType) { const Scope *scope = getNestedInScope(tokenList); tokenList.addtoken(str, mLine, mCol, mFile); tokenList.back()->scope(scope); if (valueType) setValueType(tokenList.back()); return tokenList.back(); } const ::Type * clangimport::AstNode::addTypeTokens(TokenList &tokenList, const std::string &str, const Scope *scope) { if (str.find("\':\'") != std::string::npos) { return addTypeTokens(tokenList, str.substr(0, str.find("\':\'") + 1), scope); } if (startsWith(str, "'enum (anonymous")) return nullptr; std::string type; if (str.find(" (") != std::string::npos) { if (str.find('<') != std::string::npos) type = str.substr(1, str.find('<')) + "...>"; else type = str.substr(1,str.find(" (")-1); } else type = unquote(str); if (type.find("(*)(") != std::string::npos) { type.erase(type.find("(*)(")); type += "*"; } if (type.find('(') != std::string::npos) type.erase(type.find('(')); // TODO: put in a helper? std::stack<Token *> lpar; for (const std::string &s: splitString(type)) { Token *tok = addtoken(tokenList, s, false); if (tok->str() == "(") lpar.push(tok); else if (tok->str() == ")") { Token::createMutualLinks(tok, lpar.top()); lpar.pop(); } } // Set Type if (!scope) { scope = tokenList.back() ? tokenList.back()->scope() : nullptr; if (!scope) return nullptr; } for (const Token *typeToken = tokenList.back(); Token::Match(typeToken, "&|*|%name%"); typeToken = typeToken->previous()) { if (!typeToken->isName()) continue; const ::Type *recordType = scope->check->findVariableType(scope, typeToken); if (recordType) { const_cast<Token*>(typeToken)->type(recordType); return recordType; } } return nullptr; } void clangimport::AstNode::addFullScopeNameTokens(TokenList &tokenList, const Scope *recordScope) { if (!recordScope) return; std::list<const Scope *> scopes; while (recordScope && recordScope != tokenList.back()->scope() && !recordScope->isExecutable()) { scopes.push_front(recordScope); recordScope = recordScope->nestedIn; } for (const Scope *s: scopes) { if (!s->className.empty()) { addtoken(tokenList, s->className); addtoken(tokenList, "::"); } } } const Scope *clangimport::AstNode::getNestedInScope(TokenList &tokenList) { if (!tokenList.back()) return &mData->mSymbolDatabase->scopeList.front(); if (tokenList.back()->str() == "}" && mData->mNotScope.find(tokenList.back()) == mData->mNotScope.end()) return tokenList.back()->scope()->nestedIn; return tokenList.back()->scope(); } void clangimport::AstNode::setValueType(Token *tok) { for (int i = 0; i < 2; i++) { const std::string &type = getType(i); if (type.find('<') != std::string::npos) // TODO continue; TokenList decl(nullptr); decl.setLang(tok->isCpp() ? Standards::Language::CPP : Standards::Language::C); addTypeTokens(decl, type, tok->scope()); if (!decl.front()) break; const ValueType valueType = ValueType::parseDecl(decl.front(), *mData->mSettings); if (valueType.type != ValueType::Type::UNKNOWN_TYPE) { tok->setValueType(new ValueType(valueType)); break; } } } Scope *clangimport::AstNode::createScope(TokenList &tokenList, Scope::ScopeType scopeType, AstNodePtr astNode, const Token *def) { std::vector<AstNodePtr> children2{std::move(astNode)}; return createScope(tokenList, scopeType, children2, def); } Scope *clangimport::AstNode::createScope(TokenList &tokenList, Scope::ScopeType scopeType, const std::vector<AstNodePtr> & children2, const Token *def) { SymbolDatabase *symbolDatabase = mData->mSymbolDatabase; auto *nestedIn = const_cast<Scope *>(getNestedInScope(tokenList)); symbolDatabase->scopeList.emplace_back(nullptr, nullptr, nestedIn); Scope *scope = &symbolDatabase->scopeList.back(); if (scopeType == Scope::ScopeType::eEnum) scope->enumeratorList.reserve(children2.size()); nestedIn->nestedList.push_back(scope); scope->type = scopeType; scope->classDef = def; scope->check = nestedIn->check; if (Token::Match(def, "if|for|while (")) { std::map<const Variable *, const Variable *> replaceVar; for (const Token *vartok = def->tokAt(2); vartok; vartok = vartok->next()) { if (!vartok->variable()) continue; if (vartok->variable()->nameToken() == vartok) { const Variable *from = vartok->variable(); scope->varlist.emplace_back(*from, scope); Variable *to = &scope->varlist.back(); replaceVar[from] = to; mData->replaceVarDecl(from, to); } if (replaceVar.find(vartok->variable()) != replaceVar.end()) const_cast<Token *>(vartok)->variable(replaceVar[vartok->variable()]); } std::list<Variable> &varlist = const_cast<Scope *>(def->scope())->varlist; for (std::list<Variable>::const_iterator var = varlist.cbegin(); var != varlist.cend();) { if (replaceVar.find(&(*var)) != replaceVar.end()) var = varlist.erase(var); else ++var; } } scope->bodyStart = addtoken(tokenList, "{"); tokenList.back()->scope(scope); mData->scopeAccessControl[scope] = scope->defaultAccess(); if (!children2.empty()) { for (const AstNodePtr &astNode: children2) { if (astNode->nodeType == "VisibilityAttr") continue; if (astNode->nodeType == AccessSpecDecl) { if (contains(astNode->mExtTokens, "private")) mData->scopeAccessControl[scope] = AccessControl::Private; else if (contains(astNode->mExtTokens, "protected")) mData->scopeAccessControl[scope] = AccessControl::Protected; else if (contains(astNode->mExtTokens, "public")) mData->scopeAccessControl[scope] = AccessControl::Public; continue; } astNode->createTokens(tokenList); if (scopeType == Scope::ScopeType::eEnum) astNode->addtoken(tokenList, ","); else if (!Token::Match(tokenList.back(), "[;{}]")) astNode->addtoken(tokenList, ";"); } } scope->bodyEnd = addtoken(tokenList, "}"); Token::createMutualLinks(const_cast<Token*>(scope->bodyStart), const_cast<Token*>(scope->bodyEnd)); mData->scopeAccessControl.erase(scope); return scope; } Token *clangimport::AstNode::createTokens(TokenList &tokenList) { if (nodeType == ArraySubscriptExpr) { Token *array = getChild(0)->createTokens(tokenList); Token *bracket1 = addtoken(tokenList, "["); Token *index = children[1]->createTokens(tokenList); Token *bracket2 = addtoken(tokenList, "]"); bracket1->astOperand1(array); bracket1->astOperand2(index); bracket1->link(bracket2); bracket2->link(bracket1); return bracket1; } if (nodeType == BinaryOperator) { Token *tok1 = getChild(0)->createTokens(tokenList); Token *binop = addtoken(tokenList, unquote(mExtTokens.back())); Token *tok2 = children[1]->createTokens(tokenList); binop->astOperand1(tok1); binop->astOperand2(tok2); return binop; } if (nodeType == BreakStmt) return addtoken(tokenList, "break"); if (nodeType == CharacterLiteral) { const int c = MathLib::toBigNumber(mExtTokens.back()); if (c == 0) return addtoken(tokenList, "\'\\0\'"); if (c == '\r') return addtoken(tokenList, "\'\\r\'"); if (c == '\n') return addtoken(tokenList, "\'\\n\'"); if (c == '\t') return addtoken(tokenList, "\'\\t\'"); if (c == '\\') return addtoken(tokenList, "\'\\\\\'"); if (c < ' ' || c >= 0x80) { std::ostringstream hex; hex << std::hex << ((c>>4) & 0xf) << (c&0xf); return addtoken(tokenList, "\'\\x" + hex.str() + "\'"); } return addtoken(tokenList, std::string("\'") + char(c) + std::string("\'")); } if (nodeType == CallExpr) return createTokensCall(tokenList); if (nodeType == CaseStmt) { Token *caseToken = addtoken(tokenList, "case"); Token *exprToken = getChild(0)->createTokens(tokenList); caseToken->astOperand1(exprToken); addtoken(tokenList, ":"); children.back()->createTokens(tokenList); return nullptr; } if (nodeType == ClassTemplateDecl) { for (const AstNodePtr& child: children) { if (child->nodeType == ClassTemplateSpecializationDecl) child->createTokens(tokenList); } return nullptr; } if (nodeType == ClassTemplateSpecializationDecl) { createTokensForCXXRecord(tokenList); return nullptr; } if (nodeType == ConditionalOperator) { Token *expr1 = getChild(0)->createTokens(tokenList); Token *tok1 = addtoken(tokenList, "?"); Token *expr2 = children[1]->createTokens(tokenList); Token *tok2 = addtoken(tokenList, ":"); Token *expr3 = children[2]->createTokens(tokenList); tok2->astOperand1(expr2); tok2->astOperand2(expr3); tok1->astOperand1(expr1); tok1->astOperand2(tok2); return tok1; } if (nodeType == CompoundAssignOperator) { Token *lhs = getChild(0)->createTokens(tokenList); Token *assign = addtoken(tokenList, getSpelling()); Token *rhs = children[1]->createTokens(tokenList); assign->astOperand1(lhs); assign->astOperand2(rhs); return assign; } if (nodeType == CompoundStmt) { for (const AstNodePtr& child: children) { child->createTokens(tokenList); if (!Token::Match(tokenList.back(), "[;{}]")) child->addtoken(tokenList, ";"); } return nullptr; } if (nodeType == ConstantExpr) return children.back()->createTokens(tokenList); if (nodeType == ContinueStmt) return addtoken(tokenList, "continue"); if (nodeType == CStyleCastExpr) { Token *par1 = addtoken(tokenList, "("); addTypeTokens(tokenList, '\'' + getType() + '\''); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); par1->astOperand1(getChild(0)->createTokens(tokenList)); return par1; } if (nodeType == CXXBindTemporaryExpr) return getChild(0)->createTokens(tokenList); if (nodeType == CXXBoolLiteralExpr) { addtoken(tokenList, mExtTokens.back()); tokenList.back()->setValueType(new ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::BOOL, 0)); return tokenList.back(); } if (nodeType == CXXConstructExpr) { if (!children.empty()) return getChild(0)->createTokens(tokenList); addTypeTokens(tokenList, '\'' + getType() + '\''); Token *type = tokenList.back(); Token *par1 = addtoken(tokenList, "("); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); par1->astOperand1(type); return par1; } if (nodeType == CXXConstructorDecl) { createTokensFunctionDecl(tokenList); return nullptr; } if (nodeType == CXXDeleteExpr) { addtoken(tokenList, "delete"); getChild(0)->createTokens(tokenList); return nullptr; } if (nodeType == CXXDestructorDecl) { createTokensFunctionDecl(tokenList); return nullptr; } if (nodeType == CXXForRangeStmt) { Token *forToken = addtoken(tokenList, "for"); Token *par1 = addtoken(tokenList, "("); AstNodePtr varDecl; if (children[6]->nodeType == DeclStmt) varDecl = getChild(6)->getChild(0); else varDecl = getChild(5)->getChild(0); varDecl->mExtTokens.pop_back(); varDecl->children.clear(); Token *expr1 = varDecl->createTokens(tokenList); Token *colon = addtoken(tokenList, ":"); AstNodePtr range; for (std::size_t i = 0; i < 2; i++) { if (children[i] && children[i]->nodeType == DeclStmt && children[i]->getChild(0)->nodeType == VarDecl) { range = children[i]->getChild(0)->getChild(0); break; } } if (!range) throw InternalError(tokenList.back(), "Failed to import CXXForRangeStmt. Range?"); Token *expr2 = range->createTokens(tokenList); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); colon->astOperand1(expr1); colon->astOperand2(expr2); par1->astOperand1(forToken); par1->astOperand2(colon); createScope(tokenList, Scope::ScopeType::eFor, children.back(), forToken); return nullptr; } if (nodeType == CXXMethodDecl) { for (std::size_t i = 0; i+1 < mExtTokens.size(); ++i) { if (mExtTokens[i] == "prev" && !mData->hasDecl(mExtTokens[i+1])) return nullptr; } createTokensFunctionDecl(tokenList); return nullptr; } if (nodeType == CXXMemberCallExpr) return createTokensCall(tokenList); if (nodeType == CXXNewExpr) { Token *newtok = addtoken(tokenList, "new"); if (children.size() == 1 && getChild(0)->nodeType == CXXConstructExpr) { newtok->astOperand1(getChild(0)->createTokens(tokenList)); return newtok; } std::string type = getType(); if (type.find('*') != std::string::npos) type = type.erase(type.rfind('*')); addTypeTokens(tokenList, type); if (!children.empty()) { Token *bracket1 = addtoken(tokenList, "["); getChild(0)->createTokens(tokenList); Token *bracket2 = addtoken(tokenList, "]"); bracket1->link(bracket2); bracket2->link(bracket1); } return newtok; } if (nodeType == CXXNullPtrLiteralExpr) return addtoken(tokenList, "nullptr"); if (nodeType == CXXOperatorCallExpr) return createTokensCall(tokenList); if (nodeType == CXXRecordDecl) { createTokensForCXXRecord(tokenList); return nullptr; } if (nodeType == CXXStaticCastExpr || nodeType == CXXFunctionalCastExpr) { Token *cast = addtoken(tokenList, getSpelling()); Token *par1 = addtoken(tokenList, "("); Token *expr = getChild(0)->createTokens(tokenList); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); par1->astOperand1(cast); par1->astOperand2(expr); setValueType(par1); return par1; } if (nodeType == CXXStdInitializerListExpr) return getChild(0)->createTokens(tokenList); if (nodeType == CXXTemporaryObjectExpr && !children.empty()) return getChild(0)->createTokens(tokenList); if (nodeType == CXXThisExpr) return addtoken(tokenList, "this"); if (nodeType == CXXThrowExpr) { Token *t = addtoken(tokenList, "throw"); t->astOperand1(getChild(0)->createTokens(tokenList)); return t; } if (nodeType == DeclRefExpr) { int addrIndex = mExtTokens.size() - 1; while (addrIndex > 1 && !startsWith(mExtTokens[addrIndex],"0x")) --addrIndex; const std::string addr = mExtTokens[addrIndex]; std::string name = unquote(getSpelling()); Token *reftok = addtoken(tokenList, name.empty() ? "<NoName>" : std::move(name)); mData->ref(addr, reftok); return reftok; } if (nodeType == DeclStmt) return getChild(0)->createTokens(tokenList); if (nodeType == DefaultStmt) { addtoken(tokenList, "default"); addtoken(tokenList, ":"); children.back()->createTokens(tokenList); return nullptr; } if (nodeType == DoStmt) { addtoken(tokenList, "do"); createScope(tokenList, Scope::ScopeType::eDo, getChild(0), tokenList.back()); Token *tok1 = addtoken(tokenList, "while"); Token *par1 = addtoken(tokenList, "("); Token *expr = children[1]->createTokens(tokenList); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); par1->astOperand1(tok1); par1->astOperand2(expr); return nullptr; } if (nodeType == EnumConstantDecl) { Token *nameToken = addtoken(tokenList, getSpelling()); auto *scope = const_cast<Scope *>(nameToken->scope()); scope->enumeratorList.emplace_back(nameToken->scope()); Enumerator *e = &scope->enumeratorList.back(); e->name = nameToken; e->value = mData->enumValue++; e->value_known = true; mData->enumDecl(mExtTokens.front(), nameToken, e); return nameToken; } if (nodeType == EnumDecl) { int colIndex = mExtTokens.size() - 1; while (colIndex > 0 && !startsWith(mExtTokens[colIndex],"col:") && !startsWith(mExtTokens[colIndex],"line:")) --colIndex; if (colIndex == 0) return nullptr; mData->enumValue = 0; Token *enumtok = addtoken(tokenList, "enum"); const Token *nametok = nullptr; { int nameIndex = mExtTokens.size() - 1; while (nameIndex > colIndex && mExtTokens[nameIndex][0] == '\'') --nameIndex; if (nameIndex > colIndex) nametok = addtoken(tokenList, mExtTokens[nameIndex]); if (mExtTokens.back()[0] == '\'') { addtoken(tokenList, ":"); addTypeTokens(tokenList, mExtTokens.back()); } } Scope *enumscope = createScope(tokenList, Scope::ScopeType::eEnum, children, enumtok); if (nametok) enumscope->className = nametok->str(); if (enumscope->bodyEnd && Token::simpleMatch(enumscope->bodyEnd->previous(), ", }")) const_cast<Token *>(enumscope->bodyEnd)->deletePrevious(); // Create enum type mData->mSymbolDatabase->typeList.emplace_back(enumtok, enumscope, enumtok->scope()); enumscope->definedType = &mData->mSymbolDatabase->typeList.back(); if (nametok) const_cast<Scope *>(enumtok->scope())->definedTypesMap[nametok->str()] = enumscope->definedType; return nullptr; } if (nodeType == ExprWithCleanups) return getChild(0)->createTokens(tokenList); if (nodeType == FieldDecl) return createTokensVarDecl(tokenList); if (nodeType == FloatingLiteral) return addtoken(tokenList, mExtTokens.back()); if (nodeType == ForStmt) { Token *forToken = addtoken(tokenList, "for"); Token *par1 = addtoken(tokenList, "("); Token *expr1 = getChild(0) ? children[0]->createTokens(tokenList) : nullptr; Token *sep1 = addtoken(tokenList, ";"); Token *expr2 = children[2] ? children[2]->createTokens(tokenList) : nullptr; Token *sep2 = addtoken(tokenList, ";"); Token *expr3 = children[3] ? children[3]->createTokens(tokenList) : nullptr; Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); par1->astOperand1(forToken); par1->astOperand2(sep1); sep1->astOperand1(expr1); sep1->astOperand2(sep2); sep2->astOperand1(expr2); sep2->astOperand2(expr3); createScope(tokenList, Scope::ScopeType::eFor, children[4], forToken); return nullptr; } if (nodeType == FunctionDecl) { createTokensFunctionDecl(tokenList); return nullptr; } if (nodeType == FunctionTemplateDecl) { bool first = true; for (const AstNodePtr& child: children) { if (child->nodeType == FunctionDecl) { if (!first) child->createTokens(tokenList); first = false; } } return nullptr; } if (nodeType == GotoStmt) { addtoken(tokenList, "goto"); addtoken(tokenList, unquote(mExtTokens[mExtTokens.size() - 2])); addtoken(tokenList, ";"); return nullptr; } if (nodeType == IfStmt) { AstNodePtr cond; AstNodePtr thenCode; AstNodePtr elseCode; if (children.size() == 2) { cond = children[children.size() - 2]; thenCode = children[children.size() - 1]; } else { cond = children[children.size() - 3]; thenCode = children[children.size() - 2]; elseCode = children[children.size() - 1]; } Token *iftok = addtoken(tokenList, "if"); Token *par1 = addtoken(tokenList, "("); par1->astOperand1(iftok); par1->astOperand2(cond->createTokens(tokenList)); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); createScope(tokenList, Scope::ScopeType::eIf, std::move(thenCode), iftok); if (elseCode) { elseCode->addtoken(tokenList, "else"); createScope(tokenList, Scope::ScopeType::eElse, std::move(elseCode), tokenList.back()); } return nullptr; } if (nodeType == ImplicitCastExpr) { Token *expr = getChild(0)->createTokens(tokenList); if (!expr->valueType() || contains(mExtTokens, "<ArrayToPointerDecay>")) setValueType(expr); return expr; } if (nodeType == InitListExpr) { const Scope *scope = tokenList.back()->scope(); Token *start = addtoken(tokenList, "{"); start->scope(scope); for (const AstNodePtr& child: children) { if (tokenList.back()->str() != "{") addtoken(tokenList, ","); child->createTokens(tokenList); } Token *end = addtoken(tokenList, "}"); end->scope(scope); start->link(end); end->link(start); mData->mNotScope.insert(end); return start; } if (nodeType == IntegerLiteral) return addtoken(tokenList, mExtTokens.back()); if (nodeType == LabelStmt) { addtoken(tokenList, unquote(mExtTokens.back())); addtoken(tokenList, ":"); for (const auto& child: children) child->createTokens(tokenList); return nullptr; } if (nodeType == LinkageSpecDecl) return nullptr; if (nodeType == MaterializeTemporaryExpr) return getChild(0)->createTokens(tokenList); if (nodeType == MemberExpr) { Token *s = getChild(0)->createTokens(tokenList); Token *dot = addtoken(tokenList, "."); std::string memberName = getSpelling(); if (startsWith(memberName, "->")) { dot->originalName("->"); memberName = memberName.substr(2); } else if (startsWith(memberName, ".")) { memberName = memberName.substr(1); } if (memberName.empty()) memberName = "<unknown>"; Token *member = addtoken(tokenList, memberName); mData->ref(mExtTokens.back(), member); dot->astOperand1(s); dot->astOperand2(member); return dot; } if (nodeType == NamespaceDecl) { if (children.empty()) return nullptr; const Token *defToken = addtoken(tokenList, "namespace"); const std::string &s = mExtTokens[mExtTokens.size() - 2]; const Token* nameToken = (startsWith(s, "col:") || startsWith(s, "line:")) ? addtoken(tokenList, mExtTokens.back()) : nullptr; Scope *scope = createScope(tokenList, Scope::ScopeType::eNamespace, children, defToken); if (nameToken) scope->className = nameToken->str(); return nullptr; } if (nodeType == NullStmt) return addtoken(tokenList, ";"); if (nodeType == ParenExpr) { Token *par1 = addtoken(tokenList, "("); Token *expr = getChild(0)->createTokens(tokenList); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); return expr; } if (nodeType == RecordDecl) { const Token *classDef = addtoken(tokenList, "struct"); const std::string &recordName = getSpelling(); if (!recordName.empty()) addtoken(tokenList, getSpelling()); if (!isDefinition()) { addtoken(tokenList, ";"); return nullptr; } Scope *recordScope = createScope(tokenList, Scope::ScopeType::eStruct, children, classDef); mData->mSymbolDatabase->typeList.emplace_back(classDef, recordScope, classDef->scope()); recordScope->definedType = &mData->mSymbolDatabase->typeList.back(); if (!recordName.empty()) { recordScope->className = recordName; const_cast<Scope *>(classDef->scope())->definedTypesMap[recordName] = recordScope->definedType; } return nullptr; } if (nodeType == ReturnStmt) { Token *tok1 = addtoken(tokenList, "return"); if (!children.empty()) { getChild(0)->setValueType(tok1); tok1->astOperand1(getChild(0)->createTokens(tokenList)); } return tok1; } if (nodeType == StringLiteral) return addtoken(tokenList, mExtTokens.back()); if (nodeType == SwitchStmt) { Token *tok1 = addtoken(tokenList, "switch"); Token *par1 = addtoken(tokenList, "("); Token *expr = children[children.size() - 2]->createTokens(tokenList); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); par1->astOperand1(tok1); par1->astOperand2(expr); createScope(tokenList, Scope::ScopeType::eSwitch, children.back(), tok1); return nullptr; } if (nodeType == TypedefDecl) { addtoken(tokenList, "typedef"); addTypeTokens(tokenList, getType()); return addtoken(tokenList, getSpelling()); } if (nodeType == UnaryOperator) { int index = (int)mExtTokens.size() - 1; while (index > 0 && mExtTokens[index][0] != '\'') --index; Token *unop = addtoken(tokenList, unquote(mExtTokens[index])); unop->astOperand1(getChild(0)->createTokens(tokenList)); return unop; } if (nodeType == UnaryExprOrTypeTraitExpr) { Token *tok1 = addtoken(tokenList, getSpelling()); Token *par1 = addtoken(tokenList, "("); if (children.empty()) addTypeTokens(tokenList, mExtTokens.back()); else { AstNodePtr child = getChild(0); if (child && child->nodeType == ParenExpr) child = child->getChild(0); Token *expr = child->createTokens(tokenList); child->setValueType(expr); par1->astOperand2(expr); } Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); par1->astOperand1(tok1); par1->astOperand2(par1->next()); setValueType(par1); return par1; } if (nodeType == VarDecl) return createTokensVarDecl(tokenList); if (nodeType == WhileStmt) { AstNodePtr cond = children[children.size() - 2]; AstNodePtr body = children.back(); Token *whiletok = addtoken(tokenList, "while"); Token *par1 = addtoken(tokenList, "("); par1->astOperand1(whiletok); par1->astOperand2(cond->createTokens(tokenList)); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); createScope(tokenList, Scope::ScopeType::eWhile, std::move(body), whiletok); return nullptr; } return addtoken(tokenList, "?" + nodeType + "?"); } Token * clangimport::AstNode::createTokensCall(TokenList &tokenList) { int firstParam; Token *f; if (nodeType == CXXOperatorCallExpr) { firstParam = 2; Token *obj = getChild(1)->createTokens(tokenList); Token *dot = addtoken(tokenList, "."); Token *op = getChild(0)->createTokens(tokenList); dot->astOperand1(obj); dot->astOperand2(op); f = dot; } else { firstParam = 1; f = getChild(0)->createTokens(tokenList); } f->setValueType(nullptr); Token *par1 = addtoken(tokenList, "("); par1->astOperand1(f); std::size_t args = 0; while (args < children.size() && children[args]->nodeType != CXXDefaultArgExpr) args++; Token *child = nullptr; for (std::size_t c = firstParam; c < args; ++c) { if (child) { Token *comma = addtoken(tokenList, ","); comma->setValueType(nullptr); comma->astOperand1(child); comma->astOperand2(children[c]->createTokens(tokenList)); child = comma; } else { child = children[c]->createTokens(tokenList); } } par1->astOperand2(child); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); return par1; } void clangimport::AstNode::createTokensFunctionDecl(TokenList &tokenList) { const bool prev = contains(mExtTokens, "prev"); const bool hasBody = !children.empty() && children.back()->nodeType == CompoundStmt; const bool isStatic = contains(mExtTokens, "static"); const bool isInline = contains(mExtTokens, "inline"); const Token *startToken = nullptr; SymbolDatabase *symbolDatabase = mData->mSymbolDatabase; if (nodeType != CXXConstructorDecl && nodeType != CXXDestructorDecl) { if (isStatic) addtoken(tokenList, "static"); if (isInline) addtoken(tokenList, "inline"); const Token * const before = tokenList.back(); addTypeTokens(tokenList, '\'' + getType() + '\''); startToken = before ? before->next() : tokenList.front(); } if (mExtTokens.size() > 4 && mExtTokens[1] == "parent") addFullScopeNameTokens(tokenList, mData->getScope(mExtTokens[2])); Token *nameToken = addtoken(tokenList, getSpelling() + getTemplateParameters()); auto *nestedIn = const_cast<Scope *>(nameToken->scope()); if (prev) { const std::string addr = *(std::find(mExtTokens.cbegin(), mExtTokens.cend(), "prev") + 1); mData->ref(addr, nameToken); } if (!nameToken->function()) { nestedIn->functionList.emplace_back(nameToken, unquote(getFullType())); mData->funcDecl(mExtTokens.front(), nameToken, &nestedIn->functionList.back()); if (nodeType == CXXConstructorDecl) nestedIn->functionList.back().type = Function::Type::eConstructor; else if (nodeType == CXXDestructorDecl) nestedIn->functionList.back().type = Function::Type::eDestructor; else nestedIn->functionList.back().retDef = startToken; } auto * const function = const_cast<Function*>(nameToken->function()); if (!prev) { auto accessControl = mData->scopeAccessControl.find(tokenList.back()->scope()); if (accessControl != mData->scopeAccessControl.end()) function->access = accessControl->second; } Scope *scope = nullptr; if (hasBody) { symbolDatabase->scopeList.emplace_back(nullptr, nullptr, nestedIn); scope = &symbolDatabase->scopeList.back(); scope->check = symbolDatabase; scope->function = function; scope->classDef = nameToken; scope->type = Scope::ScopeType::eFunction; scope->className = nameToken->str(); nestedIn->nestedList.push_back(scope); function->hasBody(true); function->functionScope = scope; } Token *par1 = addtoken(tokenList, "("); if (!function->arg) function->arg = par1; function->token = nameToken; if (!function->nestedIn) function->nestedIn = nestedIn; function->argDef = par1; // Function arguments for (int i = 0; i < children.size(); ++i) { AstNodePtr child = children[i]; if (child->nodeType != ParmVarDecl) continue; if (tokenList.back() != par1) addtoken(tokenList, ","); const Type *recordType = addTypeTokens(tokenList, child->mExtTokens.back(), nestedIn); const Token *typeEndToken = tokenList.back(); const std::string spelling = child->getSpelling(); Token *vartok = nullptr; if (!spelling.empty()) vartok = child->addtoken(tokenList, spelling); if (!prev) { function->argumentList.emplace_back(vartok, child->getType(), nullptr, typeEndToken, i, AccessControl::Argument, recordType, scope); if (vartok) { const std::string addr = child->mExtTokens[0]; mData->varDecl(addr, vartok, &function->argumentList.back()); } } else if (vartok) { const std::string addr = child->mExtTokens[0]; mData->ref(addr, vartok); } } Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); if (function->isConst()) addtoken(tokenList, "const"); // Function body if (hasBody) { symbolDatabase->functionScopes.push_back(scope); Token *bodyStart = addtoken(tokenList, "{"); bodyStart->scope(scope); children.back()->createTokens(tokenList); Token *bodyEnd = addtoken(tokenList, "}"); scope->bodyStart = bodyStart; scope->bodyEnd = bodyEnd; bodyStart->link(bodyEnd); bodyEnd->link(bodyStart); } else { if (nodeType == CXXConstructorDecl && contains(mExtTokens, "default")) { addtoken(tokenList, "="); addtoken(tokenList, "default"); } addtoken(tokenList, ";"); } } void clangimport::AstNode::createTokensForCXXRecord(TokenList &tokenList) { const bool isStruct = contains(mExtTokens, "struct"); Token * const classToken = addtoken(tokenList, isStruct ? "struct" : "class"); std::string className; if (mExtTokens[mExtTokens.size() - 2] == (isStruct?"struct":"class")) className = mExtTokens.back(); else className = mExtTokens[mExtTokens.size() - 2]; className += getTemplateParameters(); /*Token *nameToken =*/ addtoken(tokenList, className); // base classes bool firstBase = true; for (const AstNodePtr &child: children) { if (child->nodeType == "public" || child->nodeType == "protected" || child->nodeType == "private") { addtoken(tokenList, firstBase ? ":" : ","); addtoken(tokenList, child->nodeType); addtoken(tokenList, unquote(child->mExtTokens.back())); firstBase = false; } } // definition if (isDefinition()) { std::vector<AstNodePtr> children2; std::copy_if(children.cbegin(), children.cend(), std::back_inserter(children2), [](const AstNodePtr& child) { return child->nodeType == CXXConstructorDecl || child->nodeType == CXXDestructorDecl || child->nodeType == CXXMethodDecl || child->nodeType == FieldDecl || child->nodeType == VarDecl || child->nodeType == AccessSpecDecl || child->nodeType == TypedefDecl; }); Scope *scope = createScope(tokenList, isStruct ? Scope::ScopeType::eStruct : Scope::ScopeType::eClass, children2, classToken); const std::string addr = mExtTokens[0]; mData->scopeDecl(addr, scope); scope->className = className; mData->mSymbolDatabase->typeList.emplace_back(classToken, scope, classToken->scope()); scope->definedType = &mData->mSymbolDatabase->typeList.back(); const_cast<Scope *>(classToken->scope())->definedTypesMap[className] = scope->definedType; } addtoken(tokenList, ";"); tokenList.back()->scope(classToken->scope()); } Token * clangimport::AstNode::createTokensVarDecl(TokenList &tokenList) { const std::string addr = mExtTokens.front(); if (contains(mExtTokens, "static")) addtoken(tokenList, "static"); int typeIndex = mExtTokens.size() - 1; while (typeIndex > 1 && std::isalpha(mExtTokens[typeIndex][0])) typeIndex--; const std::string type = mExtTokens[typeIndex]; const std::string name = mExtTokens[typeIndex - 1]; const Token *startToken = tokenList.back(); const ::Type *recordType = addTypeTokens(tokenList, type); if (!startToken) startToken = tokenList.front(); else if (startToken->str() != "static") startToken = startToken->next(); Token *vartok1 = addtoken(tokenList, name); auto *scope = const_cast<Scope *>(tokenList.back()->scope()); scope->varlist.emplace_back(vartok1, unquote(type), startToken, vartok1->previous(), 0, scope->defaultAccess(), recordType, scope); mData->varDecl(addr, vartok1, &scope->varlist.back()); if (mExtTokens.back() == "cinit" && !children.empty()) { Token *eq = addtoken(tokenList, "="); eq->astOperand1(vartok1); eq->astOperand2(children.back()->createTokens(tokenList)); return eq; } if (mExtTokens.back() == "callinit") { Token *par1 = addtoken(tokenList, "("); par1->astOperand1(vartok1); par1->astOperand2(getChild(0)->createTokens(tokenList)); Token *par2 = addtoken(tokenList, ")"); par1->link(par2); par2->link(par1); return par1; } if (mExtTokens.back() == "listinit") { return getChild(0)->createTokens(tokenList); } return vartok1; } static void setTypes(TokenList &tokenList) { for (Token *tok = tokenList.front(); tok; tok = tok->next()) { if (Token::simpleMatch(tok, "sizeof (")) { for (Token *typeToken = tok->tokAt(2); typeToken->str() != ")"; typeToken = typeToken->next()) { if (typeToken->type()) continue; typeToken->type(typeToken->scope()->findType(typeToken->str())); } } } } static void setValues(const Tokenizer &tokenizer, const SymbolDatabase *symbolDatabase) { const Settings & settings = tokenizer.getSettings(); for (const Scope& scope : symbolDatabase->scopeList) { if (!scope.definedType) continue; int typeSize = 0; for (const Variable &var: scope.varlist) { const int mul = std::accumulate(var.dimensions().cbegin(), var.dimensions().cend(), 1, [](int v, const Dimension& dim) { return v * dim.num; }); if (var.valueType()) typeSize += mul * var.valueType()->typeSize(settings.platform, true); } scope.definedType->sizeOf = typeSize; } for (auto *tok = const_cast<Token*>(tokenizer.tokens()); tok; tok = tok->next()) { if (Token::simpleMatch(tok, "sizeof (")) { ValueType vt = ValueType::parseDecl(tok->tokAt(2), settings); const int sz = vt.typeSize(settings.platform, true); if (sz <= 0) continue; long long mul = 1; for (const Token *arrtok = tok->linkAt(1)->previous(); arrtok; arrtok = arrtok->previous()) { const std::string &a = arrtok->str(); if (a.size() > 2 && a[0] == '[' && a.back() == ']') mul *= strToInt<long long>(a.substr(1)); else break; } ValueFlow::Value v(mul * sz); v.setKnown(); tok->next()->addValue(v); } } } void clangimport::parseClangAstDump(Tokenizer &tokenizer, std::istream &f) { TokenList &tokenList = tokenizer.list; tokenizer.createSymbolDatabase(); auto *symbolDatabase = const_cast<SymbolDatabase *>(tokenizer.getSymbolDatabase()); symbolDatabase->scopeList.emplace_back(nullptr, nullptr, nullptr); symbolDatabase->scopeList.back().type = Scope::ScopeType::eGlobal; symbolDatabase->scopeList.back().check = symbolDatabase; clangimport::Data data; data.mSettings = &tokenizer.getSettings(); data.mSymbolDatabase = symbolDatabase; std::string line; std::vector<AstNodePtr> tree; while (std::getline(f,line)) { const std::string::size_type pos1 = line.find('-'); if (pos1 == std::string::npos) continue; if (!tree.empty() && line.substr(pos1) == "-<<<NULL>>>") { const int level = (pos1 - 1) / 2; tree[level - 1]->children.push_back(nullptr); continue; } const std::string::size_type pos2 = line.find(' ', pos1); if (pos2 < pos1 + 4 || pos2 == std::string::npos) continue; const std::string nodeType = line.substr(pos1+1, pos2 - pos1 - 1); const std::string ext = line.substr(pos2); if (pos1 == 1 && endsWith(nodeType, "Decl")) { if (!tree.empty()) tree[0]->createTokens1(tokenList); tree.clear(); tree.push_back(std::make_shared<AstNode>(nodeType, ext, &data)); continue; } const int level = (pos1 - 1) / 2; if (level == 0 || level > tree.size()) continue; AstNodePtr newNode = std::make_shared<AstNode>(nodeType, ext, &data); tree[level - 1]->children.push_back(newNode); if (level >= tree.size()) tree.push_back(std::move(newNode)); else tree[level] = std::move(newNode); } if (!tree.empty()) tree[0]->createTokens1(tokenList); // Validation for (const Token *tok = tokenList.front(); tok; tok = tok->next()) { if (Token::Match(tok, "(|)|[|]|{|}") && !tok->link()) throw InternalError(tok, "Token::link() is not set properly"); } if (tokenList.front()) tokenList.front()->assignIndexes(); symbolDatabase->clangSetVariables(data.getVariableList()); symbolDatabase->createSymbolDatabaseExprIds(); tokenList.clangSetOrigFiles(); setTypes(tokenList); setValues(tokenizer, symbolDatabase); }
63,871
C++
.cpp
1,544
32.759715
151
0.595292
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,127
color.cpp
danmar_cppcheck/lib/color.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "color.h" #include <cstdlib> #include <sstream> #include <iostream> #ifndef _WIN32 #include <unistd.h> #endif bool gDisableColors = false; #ifndef _WIN32 static bool isStreamATty(const std::ostream & os) { static const bool stdout_tty = isatty(STDOUT_FILENO); static const bool stderr_tty = isatty(STDERR_FILENO); if (&os == &std::cout) return stdout_tty; if (&os == &std::cerr) return stderr_tty; return (stdout_tty && stderr_tty); } #endif static bool isColorEnabled(const std::ostream & os) { // See https://bixense.com/clicolors/ static const bool color_forced_off = (nullptr != std::getenv("NO_COLOR")); if (color_forced_off) { return false; } static const bool color_forced_on = (nullptr != std::getenv("CLICOLOR_FORCE")); if (color_forced_on) { return true; } #ifdef _WIN32 (void)os; return false; #else return isStreamATty(os); #endif } std::ostream& operator<<(std::ostream & os, Color c) { if (!gDisableColors && isColorEnabled(os)) return os << "\033[" << static_cast<std::size_t>(c) << "m"; return os; } std::string toString(Color c) { std::ostringstream ss; ss << c; return ss.str(); }
1,996
C++
.cpp
69
25.695652
83
0.690141
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,128
checkassert.cpp
danmar_cppcheck/lib/checkassert.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- // You should not write statements with side effects in assert() //--------------------------------------------------------------------------- #include "checkassert.h" #include "astutils.h" #include "errortypes.h" #include "library.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include <algorithm> #include <utility> //--------------------------------------------------------------------------- // CWE ids used static const CWE CWE398(398U); // Indicator of Poor Code Quality // Register this check class (by creating a static instance of it) namespace { CheckAssert instance; } void CheckAssert::assertWithSideEffects() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckAssert::assertWithSideEffects"); // warning for (const Token* tok = mTokenizer->list.front(); tok; tok = tok->next()) { if (!Token::simpleMatch(tok, "assert (")) continue; const Token *endTok = tok->linkAt(1); for (const Token* tmp = tok->next(); tmp != endTok; tmp = tmp->next()) { if (Token::simpleMatch(tmp, "sizeof (")) tmp = tmp->linkAt(1); checkVariableAssignment(tmp, tok->scope()); if (tmp->tokType() != Token::eFunction) { if (const Library::Function* f = mSettings->library.getFunction(tmp)) { if (f->isconst || f->ispure) continue; if (Library::getContainerYield(tmp->next()) != Library::Container::Yield::NO_YIELD) // bailout, assume read access continue; if (std::any_of(f->argumentChecks.begin(), f->argumentChecks.end(), [](const std::pair<int, Library::ArgumentChecks>& ac) { return ac.second.iteratorInfo.container > 0; // bailout, takes iterators -> assume read access })) continue; if (tmp->str() == "get" && Token::simpleMatch(tmp->astParent(), ".") && astIsSmartPointer(tmp->astParent()->astOperand1())) continue; if (f->containerYield == Library::Container::Yield::START_ITERATOR || // bailout for std::begin/end/prev/next f->containerYield == Library::Container::Yield::END_ITERATOR || f->containerYield == Library::Container::Yield::ITERATOR) continue; sideEffectInAssertError(tmp, mSettings->library.getFunctionName(tmp)); } continue; } const Function* f = tmp->function(); const Scope* scope = f->functionScope; if (!scope) { // guess that const method doesn't have side effects if (f->nestedIn->isClassOrStruct() && !f->isConst() && !f->isStatic()) sideEffectInAssertError(tmp, f->name()); // Non-const member function called, assume it has side effects continue; } for (const Token *tok2 = scope->bodyStart; tok2 != scope->bodyEnd; tok2 = tok2->next()) { if (!tok2->isAssignmentOp() && tok2->tokType() != Token::eIncDecOp) continue; const Variable* var = tok2->previous()->variable(); if (!var || var->isLocal() || (var->isArgument() && !var->isReference() && !var->isPointer())) continue; // See ticket #4937. Assigning function arguments not passed by reference is ok. if (var->isArgument() && var->isPointer() && tok2->strAt(-2) != "*") continue; // Pointers need to be dereferenced, otherwise there is no error bool noReturnInScope = true; for (const Token *rt = scope->bodyStart; rt != scope->bodyEnd; rt = rt->next()) { if (rt->str() != "return") continue; // find all return statements if (inSameScope(rt, tok2)) { noReturnInScope = false; break; } } if (noReturnInScope) continue; sideEffectInAssertError(tmp, f->name()); break; } } tok = endTok; } } //--------------------------------------------------------------------------- void CheckAssert::sideEffectInAssertError(const Token *tok, const std::string& functionName) { reportError(tok, Severity::warning, "assertWithSideEffect", "$symbol:" + functionName + "\n" "Assert statement calls a function which may have desired side effects: '$symbol'.\n" "Non-pure function: '$symbol' is called inside assert statement. " "Assert statements are removed from release builds so the code inside " "assert statement is not executed. If the code is needed also in release " "builds, this is a bug.", CWE398, Certainty::normal); } void CheckAssert::assignmentInAssertError(const Token *tok, const std::string& varname) { reportError(tok, Severity::warning, "assignmentInAssert", "$symbol:" + varname + "\n" "Assert statement modifies '$symbol'.\n" "Variable '$symbol' is modified inside assert statement. " "Assert statements are removed from release builds so the code inside " "assert statement is not executed. If the code is needed also in release " "builds, this is a bug.", CWE398, Certainty::normal); } // checks if side effects happen on the variable prior to tmp void CheckAssert::checkVariableAssignment(const Token* assignTok, const Scope *assertionScope) { if (!assignTok->isAssignmentOp() && assignTok->tokType() != Token::eIncDecOp) return; const Variable* var = assignTok->astOperand1()->variable(); if (!var) return; // Variable declared in inner scope in assert => don't warn if (assertionScope != var->scope()) { const Scope *s = var->scope(); while (s && s != assertionScope) s = s->nestedIn; if (s == assertionScope) return; } // assignment if (assignTok->isAssignmentOp() || assignTok->tokType() == Token::eIncDecOp) { if (var->isConst()) { return; } assignmentInAssertError(assignTok, var->name()); } // TODO: function calls on var } bool CheckAssert::inSameScope(const Token* returnTok, const Token* assignTok) { // TODO: even if a return is in the same scope, the assignment might not affect it. return returnTok->scope() == assignTok->scope(); }
7,652
C++
.cpp
156
38.987179
143
0.572825
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,129
vf_unknownfunctionreturn.cpp
danmar_cppcheck/lib/vf_unknownfunctionreturn.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_unknownfunctionreturn.h" #include "library.h" #include "mathlib.h" #include "settings.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_common.h" #include "vf_settokenvalue.h" #include <set> #include <string> #include <vector> namespace ValueFlow { void analyzeUnknownFunctionReturn(TokenList &tokenlist, const Settings &settings) { if (settings.checkUnknownFunctionReturn.empty()) return; for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (!tok->astParent() || tok->str() != "(" || !tok->previous()->isName()) continue; if (settings.checkUnknownFunctionReturn.find(tok->strAt(-1)) == settings.checkUnknownFunctionReturn.end()) continue; std::vector<MathLib::bigint> unknownValues = settings.library.unknownReturnValues(tok->astOperand1()); if (unknownValues.empty()) continue; // Get min/max values for return type const std::string &typestr = settings.library.returnValueType(tok->previous()); MathLib::bigint minvalue, maxvalue; if (!getMinMaxValues(typestr, settings, tok->isCpp(), minvalue, maxvalue)) continue; for (MathLib::bigint value : unknownValues) { if (value < minvalue) value = minvalue; else if (value > maxvalue) value = maxvalue; setTokenValue(tok, Value(value), settings); } } } }
2,335
C++
.cpp
58
33.344828
118
0.653744
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,130
infer.cpp
danmar_cppcheck/lib/infer.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "infer.h" #include "calculate.h" #include "errortypes.h" #include "token.h" #include "valueptr.h" #include <cassert> #include <algorithm> #include <functional> #include <iterator> #include <unordered_set> #include <utility> template<class Predicate, class Compare> static const ValueFlow::Value* getCompareValue(const std::list<ValueFlow::Value>& values, Predicate pred, Compare compare) { const ValueFlow::Value* result = nullptr; for (const ValueFlow::Value& value : values) { if (!pred(value)) continue; if (result) result = &std::min(value, *result, [compare](const ValueFlow::Value& x, const ValueFlow::Value& y) { return compare(x.intvalue, y.intvalue); }); else result = &value; } return result; } namespace { struct Interval { std::vector<MathLib::bigint> minvalue, maxvalue; std::vector<const ValueFlow::Value*> minRef, maxRef; void setMinValue(MathLib::bigint x, const ValueFlow::Value* ref = nullptr) { minvalue = {x}; if (ref) minRef = {ref}; } void setMaxValue(MathLib::bigint x, const ValueFlow::Value* ref = nullptr) { maxvalue = {x}; if (ref) maxRef = {ref}; } bool isLessThan(MathLib::bigint x, std::vector<const ValueFlow::Value*>* ref = nullptr) const { if (!this->maxvalue.empty() && this->maxvalue.front() < x) { if (ref) *ref = maxRef; return true; } return false; } bool isGreaterThan(MathLib::bigint x, std::vector<const ValueFlow::Value*>* ref = nullptr) const { if (!this->minvalue.empty() && this->minvalue.front() > x) { if (ref) *ref = minRef; return true; } return false; } bool isScalar() const { return minvalue.size() == 1 && minvalue == maxvalue; } bool empty() const { return minvalue.empty() && maxvalue.empty(); } bool isScalarOrEmpty() const { return empty() || isScalar(); } MathLib::bigint getScalar() const { assert(isScalar()); return minvalue.front(); } std::vector<const ValueFlow::Value*> getScalarRef() const { assert(isScalar()); if (minRef != maxRef) return merge(minRef, maxRef); return minRef; } static Interval fromInt(MathLib::bigint x, const ValueFlow::Value* ref = nullptr) { Interval result; result.setMinValue(x, ref); result.setMaxValue(x, ref); return result; } template<class Predicate> static Interval fromValues(const std::list<ValueFlow::Value>& values, Predicate predicate) { Interval result; const ValueFlow::Value* minValue = getCompareValue(values, predicate, std::less<MathLib::bigint>{}); if (minValue) { if (minValue->isImpossible() && minValue->bound == ValueFlow::Value::Bound::Upper) result.setMinValue(minValue->intvalue + 1, minValue); if (minValue->isPossible() && minValue->bound == ValueFlow::Value::Bound::Lower) result.setMinValue(minValue->intvalue, minValue); if (!minValue->isImpossible() && (minValue->bound == ValueFlow::Value::Bound::Point || minValue->isKnown()) && std::count_if(values.begin(), values.end(), predicate) == 1) return Interval::fromInt(minValue->intvalue, minValue); } const ValueFlow::Value* maxValue = getCompareValue(values, predicate, std::greater<MathLib::bigint>{}); if (maxValue) { if (maxValue->isImpossible() && maxValue->bound == ValueFlow::Value::Bound::Lower) result.setMaxValue(maxValue->intvalue - 1, maxValue); if (maxValue->isPossible() && maxValue->bound == ValueFlow::Value::Bound::Upper) result.setMaxValue(maxValue->intvalue, maxValue); assert(!maxValue->isKnown()); } return result; } static Interval fromValues(const std::list<ValueFlow::Value>& values) { return Interval::fromValues(values, [](const ValueFlow::Value&) { return true; }); } template<class F> static std::vector<MathLib::bigint> apply(const std::vector<MathLib::bigint>& x, const std::vector<MathLib::bigint>& y, F f) { if (x.empty()) return {}; if (y.empty()) return {}; return {f(x.front(), y.front())}; } static std::vector<const ValueFlow::Value*> merge(std::vector<const ValueFlow::Value*> x, const std::vector<const ValueFlow::Value*>& y) { x.insert(x.end(), y.cbegin(), y.cend()); return x; } friend Interval operator-(const Interval& lhs, const Interval& rhs) { Interval result; result.minvalue = Interval::apply(lhs.minvalue, rhs.maxvalue, std::minus<MathLib::bigint>{}); result.maxvalue = Interval::apply(lhs.maxvalue, rhs.minvalue, std::minus<MathLib::bigint>{}); if (!result.minvalue.empty()) result.minRef = merge(lhs.minRef, rhs.maxRef); if (!result.maxvalue.empty()) result.maxRef = merge(lhs.maxRef, rhs.minRef); return result; } static std::vector<int> equal(const Interval& lhs, const Interval& rhs, std::vector<const ValueFlow::Value*>* ref = nullptr) { if (!lhs.isScalar()) return {}; if (!rhs.isScalar()) return {}; if (ref) *ref = merge(lhs.getScalarRef(), rhs.getScalarRef()); return {lhs.minvalue == rhs.minvalue}; } static std::vector<int> compare(const Interval& lhs, const Interval& rhs, std::vector<const ValueFlow::Value*>* ref = nullptr) { Interval diff = lhs - rhs; if (diff.isGreaterThan(0, ref)) return {1}; if (diff.isLessThan(0, ref)) return {-1}; std::vector<int> eq = Interval::equal(lhs, rhs, ref); if (!eq.empty()) { if (eq.front() == 0) return {1, -1}; return {0}; } if (diff.isGreaterThan(-1, ref)) return {0, 1}; if (diff.isLessThan(1, ref)) return {0, -1}; return {}; } static std::vector<bool> compare(const std::string& op, const Interval& lhs, const Interval& rhs, std::vector<const ValueFlow::Value*>* ref = nullptr) { std::vector<int> r = compare(lhs, rhs, ref); if (r.empty()) return {}; bool b = calculate(op, r.front(), 0); if (std::all_of(r.cbegin() + 1, r.cend(), [&](int i) { return b == calculate(op, i, 0); })) return {b}; return {}; } }; } static void addToErrorPath(ValueFlow::Value& value, const std::vector<const ValueFlow::Value*>& refs) { std::unordered_set<const Token*> locations; for (const ValueFlow::Value* ref : refs) { if (ref->condition && !value.condition) value.condition = ref->condition; std::copy_if(ref->errorPath.cbegin(), ref->errorPath.cend(), std::back_inserter(value.errorPath), [&](const ErrorPathItem& e) { return locations.insert(e.first).second; }); std::copy_if(ref->debugPath.cbegin(), ref->debugPath.cend(), std::back_inserter(value.debugPath), [&](const ErrorPathItem& e) { return locations.insert(e.first).second; }); } } static void setValueKind(ValueFlow::Value& value, const std::vector<const ValueFlow::Value*>& refs) { bool isPossible = false; bool isInconclusive = false; for (const ValueFlow::Value* ref : refs) { if (ref->isPossible()) isPossible = true; if (ref->isInconclusive()) isInconclusive = true; } if (isInconclusive) value.setInconclusive(); else if (isPossible) value.setPossible(); else value.setKnown(); } static bool inferNotEqual(const std::list<ValueFlow::Value>& values, MathLib::bigint x) { return std::any_of(values.cbegin(), values.cend(), [&](const ValueFlow::Value& value) { return value.isImpossible() && value.intvalue == x; }); } std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model, const std::string& op, std::list<ValueFlow::Value> lhsValues, std::list<ValueFlow::Value> rhsValues) { std::vector<ValueFlow::Value> result; auto notMatch = [&](const ValueFlow::Value& value) { return !model->match(value); }; lhsValues.remove_if(notMatch); if (lhsValues.empty()) return result; rhsValues.remove_if(notMatch); if (rhsValues.empty()) return result; Interval lhs = Interval::fromValues(lhsValues); Interval rhs = Interval::fromValues(rhsValues); if (op == "-") { Interval diff = lhs - rhs; if (diff.isScalar()) { std::vector<const ValueFlow::Value*> refs = diff.getScalarRef(); ValueFlow::Value value(diff.getScalar()); addToErrorPath(value, refs); setValueKind(value, refs); result.push_back(std::move(value)); } else { if (!diff.minvalue.empty()) { ValueFlow::Value value(diff.minvalue.front() - 1); value.setImpossible(); value.bound = ValueFlow::Value::Bound::Upper; addToErrorPath(value, diff.minRef); result.push_back(std::move(value)); } if (!diff.maxvalue.empty()) { ValueFlow::Value value(diff.maxvalue.front() + 1); value.setImpossible(); value.bound = ValueFlow::Value::Bound::Lower; addToErrorPath(value, diff.maxRef); result.push_back(std::move(value)); } } } else if ((op == "!=" || op == "==") && lhs.isScalarOrEmpty() && rhs.isScalarOrEmpty()) { if (lhs.isScalar() && rhs.isScalar()) { std::vector<const ValueFlow::Value*> refs = Interval::merge(lhs.getScalarRef(), rhs.getScalarRef()); ValueFlow::Value value(calculate(op, lhs.getScalar(), rhs.getScalar())); addToErrorPath(value, refs); setValueKind(value, refs); result.push_back(std::move(value)); } else { std::vector<const ValueFlow::Value*> refs; if (lhs.isScalar() && inferNotEqual(rhsValues, lhs.getScalar())) refs = lhs.getScalarRef(); else if (rhs.isScalar() && inferNotEqual(lhsValues, rhs.getScalar())) refs = rhs.getScalarRef(); if (!refs.empty()) { ValueFlow::Value value(op == "!="); addToErrorPath(value, refs); setValueKind(value, refs); result.push_back(std::move(value)); } } } else { std::vector<const ValueFlow::Value*> refs; std::vector<bool> r = Interval::compare(op, lhs, rhs, &refs); if (!r.empty()) { ValueFlow::Value value(r.front()); addToErrorPath(value, refs); setValueKind(value, refs); result.push_back(std::move(value)); } } return result; } std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model, const std::string& op, MathLib::bigint lhs, std::list<ValueFlow::Value> rhsValues) { return infer(model, op, {model->yield(lhs)}, std::move(rhsValues)); } std::vector<ValueFlow::Value> infer(const ValuePtr<InferModel>& model, const std::string& op, std::list<ValueFlow::Value> lhsValues, MathLib::bigint rhs) { return infer(model, op, std::move(lhsValues), {model->yield(rhs)}); } std::vector<MathLib::bigint> getMinValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values) { return Interval::fromValues(values, [&](const ValueFlow::Value& v) { return model->match(v); }).minvalue; } std::vector<MathLib::bigint> getMaxValue(const ValuePtr<InferModel>& model, const std::list<ValueFlow::Value>& values) { return Interval::fromValues(values, [&](const ValueFlow::Value& v) { return model->match(v); }).maxvalue; } namespace { struct IntegralInferModel : InferModel { bool match(const ValueFlow::Value& value) const override { return value.isIntValue(); } ValueFlow::Value yield(MathLib::bigint value) const override { ValueFlow::Value result(value); result.valueType = ValueFlow::Value::ValueType::INT; result.setKnown(); return result; } }; } ValuePtr<InferModel> makeIntegralInferModel() { return IntegralInferModel{}; } ValueFlow::Value inferCondition(const std::string& op, const Token* varTok, MathLib::bigint val) { if (!varTok) return ValueFlow::Value{}; if (varTok->hasKnownIntValue()) return ValueFlow::Value{}; std::vector<ValueFlow::Value> r = infer(makeIntegralInferModel(), op, varTok->values(), val); if (r.size() == 1 && r.front().isKnown()) return r.front(); return ValueFlow::Value{}; }
15,500
C++
.cpp
385
28.903896
126
0.54619
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,131
settings.cpp
danmar_cppcheck/lib/settings.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "settings.h" #include "path.h" #include "summaries.h" #include "vfvalue.h" #include <cctype> #include <fstream> #include <iostream> #include <sstream> #include <utility> #include "json.h" #ifndef _WIN32 #include <unistd.h> // for getpid() #else #include <process.h> // for getpid() #endif std::atomic<bool> Settings::mTerminated; const char Settings::SafeChecks::XmlRootName[] = "safe-checks"; const char Settings::SafeChecks::XmlClasses[] = "class-public"; const char Settings::SafeChecks::XmlExternalFunctions[] = "external-functions"; const char Settings::SafeChecks::XmlInternalFunctions[] = "internal-functions"; const char Settings::SafeChecks::XmlExternalVariables[] = "external-variables"; static int getPid() { #ifndef _WIN32 return getpid(); #else return _getpid(); #endif } Settings::Settings() { severity.setEnabled(Severity::error, true); certainty.setEnabled(Certainty::normal, true); setCheckLevel(Settings::CheckLevel::exhaustive); executor = defaultExecutor(); pid = getPid(); } std::string Settings::loadCppcheckCfg(Settings& settings, Suppressions& suppressions, bool debug) { // TODO: this always needs to be run *after* the Settings has been filled static const std::string cfgFilename = "cppcheck.cfg"; std::string fileName; #ifdef FILESDIR { const std::string filesdirCfg = Path::join(FILESDIR, cfgFilename); if (debug) std::cout << "looking for '" << filesdirCfg << "'" << std::endl; if (Path::isFile(filesdirCfg)) fileName = filesdirCfg; } #endif // cppcheck-suppress knownConditionTrueFalse if (fileName.empty()) { // TODO: make sure that exename is set fileName = Path::getPathFromFilename(settings.exename) + cfgFilename; if (debug) std::cout << "looking for '" << fileName << "'" << std::endl; if (!Path::isFile(fileName)) { if (debug) std::cout << "no configuration found" << std::endl; return ""; } } std::ifstream fin(fileName); if (!fin.is_open()) return "could not open file"; picojson::value json; fin >> json; { const std::string& lastErr = picojson::get_last_error(); if (!lastErr.empty()) return "not a valid JSON - " + lastErr; } const picojson::object& obj = json.get<picojson::object>(); { const picojson::object::const_iterator it = obj.find("productName"); if (it != obj.cend()) { const auto& v = it->second; if (!v.is<std::string>()) return "'productName' is not a string"; settings.cppcheckCfgProductName = v.get<std::string>(); } } { const picojson::object::const_iterator it = obj.find("about"); if (it != obj.cend()) { const auto& v = it->second; if (!v.is<std::string>()) return "'about' is not a string"; settings.cppcheckCfgAbout = v.get<std::string>(); } } { const picojson::object::const_iterator it = obj.find("addons"); if (it != obj.cend()) { const auto& entry = it->second; if (!entry.is<picojson::array>()) return "'addons' is not an array"; for (const picojson::value &v : entry.get<picojson::array>()) { if (!v.is<std::string>()) return "'addons' array entry is not a string"; const std::string &s = v.get<std::string>(); if (!Path::isAbsolute(s)) settings.addons.emplace(Path::join(Path::getPathFromFilename(fileName), s)); else settings.addons.emplace(s); } } } { const picojson::object::const_iterator it = obj.find("suppressions"); if (it != obj.cend()) { const auto& entry = it->second; if (!entry.is<picojson::array>()) return "'suppressions' is not an array"; for (const picojson::value &v : entry.get<picojson::array>()) { if (!v.is<std::string>()) return "'suppressions' array entry is not a string"; const std::string &s = v.get<std::string>(); const std::string err = suppressions.nomsg.addSuppressionLine(s); if (!err.empty()) return "could not parse suppression '" + s + "' - " + err; } } } { const picojson::object::const_iterator it = obj.find("safety"); if (it != obj.cend()) { const auto& v = it->second; if (!v.is<bool>()) return "'safety' is not a bool"; settings.safety = settings.safety || v.get<bool>(); } } return ""; } std::pair<std::string, std::string> Settings::getNameAndVersion(const std::string& productName) { if (productName.empty()) return {}; const std::string::size_type pos1 = productName.rfind(' '); if (pos1 == std::string::npos) return {}; if (pos1 + 2 >= productName.length()) return {}; for (auto pos2 = pos1 + 1; pos2 < productName.length(); ++pos2) { const char c = productName[pos2]; const char prev = productName[pos2-1]; if (std::isdigit(c)) continue; if (c == '.' && std::isdigit(prev)) continue; if (c == 's' && pos2 + 1 == productName.length() && std::isdigit(prev)) continue; return {}; } return {productName.substr(0, pos1), productName.substr(pos1+1)}; } std::string Settings::parseEnabled(const std::string &str, std::tuple<SimpleEnableGroup<Severity>, SimpleEnableGroup<Checks>> &groups) { // Enable parameters may be comma separated... if (str.find(',') != std::string::npos) { std::string::size_type prevPos = 0; std::string::size_type pos = 0; while ((pos = str.find(',', pos)) != std::string::npos) { if (pos == prevPos) return std::string("--enable parameter is empty"); std::string errmsg(parseEnabled(str.substr(prevPos, pos - prevPos), groups)); if (!errmsg.empty()) return errmsg; ++pos; prevPos = pos; } if (prevPos >= str.length()) return std::string("--enable parameter is empty"); return parseEnabled(str.substr(prevPos), groups); } auto& severity = std::get<0>(groups); auto& checks = std::get<1>(groups); if (str == "all") { // "error" is always enabled and cannot be controlled - so exclude it from "all" SimpleEnableGroup<Severity> newSeverity; newSeverity.fill(); newSeverity.disable(Severity::error); severity.enable(newSeverity); checks.enable(Checks::missingInclude); checks.enable(Checks::unusedFunction); } else if (str == "warning") { severity.enable(Severity::warning); } else if (str == "style") { severity.enable(Severity::style); } else if (str == "performance") { severity.enable(Severity::performance); } else if (str == "portability") { severity.enable(Severity::portability); } else if (str == "information") { severity.enable(Severity::information); } else if (str == "unusedFunction") { checks.enable(Checks::unusedFunction); } else if (str == "missingInclude") { checks.enable(Checks::missingInclude); } #ifdef CHECK_INTERNAL else if (str == "internal") { checks.enable(Checks::internalCheck); } #endif else { // the actual option is prepending in the applyEnabled() call if (str.empty()) return " parameter is empty"; return " parameter with the unknown name '" + str + "'"; } return ""; } std::string Settings::addEnabled(const std::string &str) { return applyEnabled(str, true); } std::string Settings::removeEnabled(const std::string &str) { return applyEnabled(str, false); } std::string Settings::applyEnabled(const std::string &str, bool enable) { std::tuple<SimpleEnableGroup<Severity>, SimpleEnableGroup<Checks>> groups; std::string errmsg = parseEnabled(str, groups); if (!errmsg.empty()) return (enable ? "--enable" : "--disable") + errmsg; const auto s = std::get<0>(groups); const auto c = std::get<1>(groups); if (enable) { severity.enable(s); checks.enable(c); } else { severity.disable(s); checks.disable(c); } // FIXME: hack to make sure "error" is always enabled severity.enable(Severity::error); return errmsg; } bool Settings::isEnabled(const ValueFlow::Value *value, bool inconclusiveCheck) const { if (!severity.isEnabled(Severity::warning) && (value->condition || value->defaultArg)) return false; if (!certainty.isEnabled(Certainty::inconclusive) && (inconclusiveCheck || value->isInconclusive())) return false; return true; } void Settings::loadSummaries() { Summaries::loadReturn(buildDir, summaryReturn); } void Settings::setCheckLevel(CheckLevel level) { if (level == CheckLevel::normal) { // Checking should finish in reasonable time. checkLevel = level; vfOptions.maxSubFunctionArgs = 8; vfOptions.maxIfCount = 100; vfOptions.doConditionExpressionAnalysis = false; vfOptions.maxForwardBranches = 4; } else if (level == CheckLevel::exhaustive) { // Checking can take a little while. ~ 10 times slower than normal analysis is OK. checkLevel = CheckLevel::exhaustive; vfOptions.maxIfCount = -1; vfOptions.maxSubFunctionArgs = 256; vfOptions.doConditionExpressionAnalysis = true; vfOptions.maxForwardBranches = -1; } } // These tables are auto generated from Cppcheck Premium script static const std::set<std::string> autosarCheckers{ "accessMoved", "argumentSize", "arrayIndexOutOfBounds", "arrayIndexOutOfBoundsCond", "arrayIndexThenCheck", "bufferAccessOutOfBounds", "comparePointers", "constParameter", "cstyleCast", "ctuOneDefinitionRuleViolation", "doubleFree", "duplInheritedMember", "duplicateBreak", "exceptThrowInDestructor", "funcArgNamesDifferent", "functionConst", "functionStatic", "invalidContainer", "memleak", "mismatchAllocDealloc", "missingReturn", "negativeIndex", "noExplicitConstructor", "nullPointer", "nullPointerArithmetic", "nullPointerArithmeticRedundantCheck", "nullPointerDefaultArg", "nullPointerRedundantCheck", "objectIndex", "overlappingWriteFunction", "overlappingWriteUnion", "pointerOutOfBounds", "pointerOutOfBoundsCond", "preprocessorErrorDirective", "redundantAssignment", "redundantInitialization", "returnDanglingLifetime", "shadowArgument", "shadowFunction", "shadowVariable", "shiftTooManyBits", "sizeofFunctionCall", "throwInNoexceptFunction", "uninitMemberVar", "uninitdata", "unreachableCode", "unreadVariable", "unsignedLessThanZero", "unusedFunction", "unusedStructMember", "unusedValue", "unusedVariable", "useInitializationList", "variableScope", "virtualCallInConstructor", "zerodiv", "zerodivcond" }; static const std::set<std::string> certCCheckers{ "IOWithoutPositioning", "autoVariables", "autovarInvalidDeallocation", "bitwiseOnBoolean", "comparePointers", "danglingLifetime", "deallocret", "deallocuse", "doubleFree", "floatConversionOverflow", "invalidFunctionArg", "invalidLengthModifierError", "invalidLifetime", "invalidScanfFormatWidth", "invalidscanf", "leakReturnValNotUsed", "leakUnsafeArgAlloc", "memleak", "memleakOnRealloc", "mismatchAllocDealloc", "missingReturn", "nullPointer", "nullPointerArithmetic", "nullPointerArithmeticRedundantCheck", "nullPointerDefaultArg", "nullPointerRedundantCheck", "preprocessorErrorDirective", "resourceLeak", "returnDanglingLifetime", "sizeofCalculation", "stringLiteralWrite", "uninitStructMember", "uninitdata", "uninitvar", "unknownEvaluationOrder", "useClosedFile", "wrongPrintfScanfArgNum", "wrongPrintfScanfParameterPositionError" }; static const std::set<std::string> certCppCheckers{ "IOWithoutPositioning", "accessMoved", "comparePointers", "containerOutOfBounds", "ctuOneDefinitionRuleViolation", "danglingLifetime", "danglingReference", "danglingTempReference", "danglingTemporaryLifetime", "deallocThrow", "deallocuse", "doubleFree", "eraseDereference", "exceptThrowInDestructor", "initializerList", "invalidContainer", "memleak", "mismatchAllocDealloc", "missingReturn", "nullPointer", "operatorEqToSelf", "returnDanglingLifetime", "sizeofCalculation", "uninitvar", "virtualCallInConstructor", "virtualDestructor" }; static const std::set<std::string> misrac2012Checkers{ "argumentSize", "autovarInvalidDeallocation", "bufferAccessOutOfBounds", "comparePointers", "compareValueOutOfTypeRangeError", "constParameterPointer", "danglingLifetime", "danglingTemporaryLifetime", "duplicateBreak", "funcArgNamesDifferent", "incompatibleFileOpen", "invalidFunctionArg", "knownConditionTrueFalse", "leakNoVarFunctionCall", "leakReturnValNotUsed", "memleak", "memleakOnRealloc", "missingReturn", "overlappingWriteFunction", "overlappingWriteUnion", "pointerOutOfBounds", "preprocessorErrorDirective", "redundantAssignInSwitch", "redundantAssignment", "redundantCondition", "resourceLeak", "returnDanglingLifetime", "shadowVariable", "sizeofCalculation", "sizeofwithsilentarraypointer", "syntaxError", "uninitvar", "unknownEvaluationOrder", "unreachableCode", "unreadVariable", "unusedLabel", "unusedVariable", "useClosedFile", "writeReadOnlyFile" }; static const std::set<std::string> misrac2023Checkers{ "argumentSize", "autovarInvalidDeallocation", "bufferAccessOutOfBounds", "comparePointers", "compareValueOutOfTypeRangeError", "constParameterPointer", "danglingLifetime", "danglingTemporaryLifetime", "duplicateBreak", "funcArgNamesDifferent", "incompatibleFileOpen", "invalidFunctionArg", "knownConditionTrueFalse", "leakNoVarFunctionCall", "leakReturnValNotUsed", "memleak", "memleakOnRealloc", "missingReturn", "overlappingWriteFunction", "overlappingWriteUnion", "pointerOutOfBounds", "preprocessorErrorDirective", "redundantAssignInSwitch", "redundantAssignment", "redundantCondition", "resourceLeak", "returnDanglingLifetime", "shadowVariable", "sizeofCalculation", "sizeofwithsilentarraypointer", "syntaxError", "uninitvar", "unknownEvaluationOrder", "unreachableCode", "unreadVariable", "unusedLabel", "unusedVariable", "useClosedFile", "writeReadOnlyFile" }; static const std::set<std::string> misracpp2008Checkers{ "autoVariables", "comparePointers", "constParameter", "constVariable", "cstyleCast", "ctuOneDefinitionRuleViolation", "danglingLifetime", "duplInheritedMember", "duplicateBreak", "exceptThrowInDestructor", "funcArgNamesDifferent", "functionConst", "functionStatic", "missingReturn", "noExplicitConstructor", "overlappingWriteFunction", "overlappingWriteUnion", "pointerOutOfBounds", "preprocessorErrorDirective", "redundantAssignment", "redundantInitialization", "returnReference", "returnTempReference", "shadowVariable", "shiftTooManyBits", "sizeofFunctionCall", "uninitDerivedMemberVar", "uninitDerivedMemberVarPrivate", "uninitMemberVar", "uninitMemberVarPrivate", "uninitStructMember", "uninitdata", "uninitvar", "unknownEvaluationOrder", "unreachableCode", "unreadVariable", "unsignedLessThanZero", "unusedFunction", "unusedStructMember", "unusedVariable", "variableScope", "virtualCallInConstructor" }; static const std::set<std::string> misracpp2023Checkers{ "accessForwarded", "accessMoved", "autoVariables", "compareBoolExpressionWithInt", "comparePointers", "compareValueOutOfTypeRangeError", "constParameter", "constParameterReference", "ctuOneDefinitionRuleViolation", "danglingLifetime", "identicalConditionAfterEarlyExit", "identicalInnerCondition", "ignoredReturnValue", "invalidFunctionArg", "invalidFunctionArgBool", "invalidFunctionArgStr", "knownConditionTrueFalse", "missingReturn", "noExplicitConstructor", "operatorEqToSelf", "overlappingWriteUnion", "pointerOutOfBounds", "pointerOutOfBoundsCond", "preprocessorErrorDirective", "redundantAssignInSwitch", "redundantAssignment", "redundantCopy", "redundantInitialization", "shadowVariable", "subtractPointers", "syntaxError", "uninitMemberVar", "uninitvar", "unknownEvaluationOrder", "unreachableCode", "unreadVariable", "virtualCallInConstructor" }; bool Settings::isPremiumEnabled(const char id[]) const { if (premiumArgs.find("autosar") != std::string::npos && autosarCheckers.count(id)) return true; if (premiumArgs.find("cert-c-") != std::string::npos && certCCheckers.count(id)) return true; if (premiumArgs.find("cert-c++") != std::string::npos && certCppCheckers.count(id)) return true; if (premiumArgs.find("misra-c-") != std::string::npos && (misrac2012Checkers.count(id) || misrac2023Checkers.count(id))) return true; if (premiumArgs.find("misra-c++-2008") != std::string::npos && misracpp2008Checkers.count(id)) return true; if (premiumArgs.find("misra-c++-2023") != std::string::npos && misracpp2023Checkers.count(id)) return true; return false; } void Settings::setMisraRuleTexts(const ExecuteCmdFn& executeCommand) { if (premiumArgs.find("--misra-c-20") != std::string::npos) { const auto it = std::find_if(addonInfos.cbegin(), addonInfos.cend(), [](const AddonInfo& a) { return a.name == "premiumaddon.json"; }); if (it != addonInfos.cend()) { std::string arg; if (premiumArgs.find("--misra-c-2023") != std::string::npos) arg = "--misra-c-2023-rule-texts"; else arg = "--misra-c-2012-rule-texts"; std::string output; executeCommand(it->executable, {std::move(arg)}, "2>&1", output); setMisraRuleTexts(output); } } } void Settings::setMisraRuleTexts(const std::string& data) { mMisraRuleTexts.clear(); std::istringstream istr(data); std::string line; while (std::getline(istr, line)) { std::string::size_type pos = line.find(' '); if (pos == std::string::npos) continue; std::string id = line.substr(0, pos); std::string text = line.substr(pos + 1); if (id.empty() || text.empty()) continue; if (text[text.size() -1] == '\r') text.erase(text.size() -1); mMisraRuleTexts[id] = std::move(text); } } std::string Settings::getMisraRuleText(const std::string& id, const std::string& text) const { if (id.compare(0, 9, "misra-c20") != 0) return text; const auto it = mMisraRuleTexts.find(id.substr(id.rfind('-') + 1)); return it != mMisraRuleTexts.end() ? it->second : text; } Settings::ExecutorType Settings::defaultExecutor() { static constexpr ExecutorType defaultExecutor = #if defined(HAS_THREADING_MODEL_FORK) ExecutorType::Process; #elif defined(HAS_THREADING_MODEL_THREAD) ExecutorType::Thread; #endif return defaultExecutor; }
21,078
C++
.cpp
655
26.164885
134
0.653046
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,132
checkstl.cpp
danmar_cppcheck/lib/checkstl.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "checkstl.h" #include "astutils.h" #include "errortypes.h" #include "library.h" #include "mathlib.h" #include "pathanalysis.h" #include "settings.h" #include "standards.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "utils.h" #include "valueflow.h" #include "checknullpointer.h" #include <algorithm> #include <iterator> #include <list> #include <map> #include <set> #include <sstream> #include <tuple> #include <unordered_map> #include <utility> #include <vector> // Register this check class (by creating a static instance of it) namespace { CheckStl instance; } // CWE IDs used: static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE597(597U); // Use of Wrong Operator in String Comparison static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime static const CWE CWE667(667U); // Improper Locking static const CWE CWE704(704U); // Incorrect Type Conversion or Cast static const CWE CWE762(762U); // Mismatched Memory Management Routines static const CWE CWE786(786U); // Access of Memory Location Before Start of Buffer static const CWE CWE788(788U); // Access of Memory Location After End of Buffer static const CWE CWE825(825U); // Expired Pointer Dereference static const CWE CWE833(833U); // Deadlock static const CWE CWE834(834U); // Excessive Iteration static bool isElementAccessYield(Library::Container::Yield yield) { return contains({Library::Container::Yield::ITEM, Library::Container::Yield::AT_INDEX}, yield); } static bool containerAppendsElement(const Library::Container* container, const Token* parent) { if (Token::Match(parent, ". %name% (")) { const Library::Container::Action action = container->getAction(parent->strAt(1)); if (contains({Library::Container::Action::INSERT, Library::Container::Action::APPEND, Library::Container::Action::CHANGE, Library::Container::Action::CHANGE_INTERNAL, Library::Container::Action::PUSH, Library::Container::Action::RESIZE}, action)) return true; } return false; } static bool containerYieldsElement(const Library::Container* container, const Token* parent) { if (Token::Match(parent, ". %name% (")) { const Library::Container::Yield yield = container->getYield(parent->strAt(1)); if (isElementAccessYield(yield)) return true; } return false; } static bool containerPopsElement(const Library::Container* container, const Token* parent) { if (Token::Match(parent, ". %name% (")) { const Library::Container::Action action = container->getAction(parent->strAt(1)); if (contains({ Library::Container::Action::POP }, action)) return true; } return false; } static const Token* getContainerIndex(const Library::Container* container, const Token* parent) { if (Token::Match(parent, ". %name% (")) { const Library::Container::Yield yield = container->getYield(parent->strAt(1)); if (yield == Library::Container::Yield::AT_INDEX && !Token::simpleMatch(parent->tokAt(2), "( )")) return parent->tokAt(2)->astOperand2(); } if (!container->arrayLike_indexOp && !container->stdStringLike) return nullptr; if (Token::simpleMatch(parent, "[")) return parent->astOperand2(); return nullptr; } static const Token* getContainerFromSize(const Library::Container* container, const Token* tok) { if (!tok) return nullptr; if (Token::Match(tok->tokAt(-2), ". %name% (")) { const Library::Container::Yield yield = container->getYield(tok->strAt(-1)); if (yield == Library::Container::Yield::SIZE) return tok->tokAt(-2)->astOperand1(); } return nullptr; } void CheckStl::outOfBounds() { logChecker("CheckStl::outOfBounds"); for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) { for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) { const Library::Container *container = getLibraryContainer(tok); if (!container || container->stdAssociativeLike) continue; const Token * parent = astParentSkipParens(tok); const Token* accessTok = parent; if (Token::simpleMatch(accessTok, ".") && Token::simpleMatch(accessTok->astParent(), "(")) accessTok = accessTok->astParent(); if (astIsIterator(accessTok) && Token::simpleMatch(accessTok->astParent(), "+")) accessTok = accessTok->astParent(); const Token* indexTok = getContainerIndex(container, parent); if (indexTok == tok) continue; for (const ValueFlow::Value &value : tok->values()) { if (!value.isContainerSizeValue()) continue; if (value.isImpossible()) continue; if (value.isInconclusive() && !mSettings->certainty.isEnabled(Certainty::inconclusive)) continue; if (!value.errorSeverity() && !mSettings->severity.isEnabled(Severity::warning)) continue; if (value.intvalue == 0 && (indexTok || (containerYieldsElement(container, parent) && !containerAppendsElement(container, parent)) || containerPopsElement(container, parent))) { std::string indexExpr; if (indexTok && !indexTok->hasKnownValue()) indexExpr = indexTok->expressionString(); outOfBoundsError(accessTok, tok->expressionString(), &value, indexExpr, nullptr); continue; } if (indexTok) { std::vector<ValueFlow::Value> indexValues = ValueFlow::isOutOfBounds(value, indexTok, mSettings->severity.isEnabled(Severity::warning)); if (!indexValues.empty()) { outOfBoundsError( accessTok, tok->expressionString(), &value, indexTok->expressionString(), &indexValues.front()); continue; } } } if (indexTok && !indexTok->hasKnownIntValue()) { const ValueFlow::Value* value = ValueFlow::findValue(indexTok->values(), *mSettings, [&](const ValueFlow::Value& v) { if (!v.isSymbolicValue()) return false; if (v.isImpossible()) return false; if (v.intvalue < 0) return false; const Token* sizeTok = v.tokvalue; if (sizeTok && sizeTok->isCast()) sizeTok = sizeTok->astOperand2() ? sizeTok->astOperand2() : sizeTok->astOperand1(); const Token* containerTok = getContainerFromSize(container, sizeTok); if (!containerTok) return false; return containerTok->exprId() == tok->exprId(); }); if (!value) continue; outOfBoundsError(accessTok, tok->expressionString(), nullptr, indexTok->expressionString(), value); } } } } static std::string indexValueString(const ValueFlow::Value& indexValue, const std::string& containerName = emptyString) { if (indexValue.isIteratorStartValue()) return "at position " + std::to_string(indexValue.intvalue) + " from the beginning"; if (indexValue.isIteratorEndValue()) return "at position " + std::to_string(-indexValue.intvalue) + " from the end"; std::string indexString = std::to_string(indexValue.intvalue); if (indexValue.isSymbolicValue()) { indexString = containerName + ".size()"; if (indexValue.intvalue != 0) indexString += "+" + std::to_string(indexValue.intvalue); } if (indexValue.bound == ValueFlow::Value::Bound::Lower) return "greater or equal to " + indexString; return indexString; } void CheckStl::outOfBoundsError(const Token *tok, const std::string &containerName, const ValueFlow::Value *containerSize, const std::string &index, const ValueFlow::Value *indexValue) { // Do not warn if both the container size and index value are possible if (containerSize && indexValue && containerSize->isPossible() && indexValue->isPossible()) return; const std::string expression = tok ? tok->expressionString() : (containerName+"[x]"); std::string errmsg; if (!containerSize) { if (indexValue && indexValue->condition) errmsg = ValueFlow::eitherTheConditionIsRedundant(indexValue->condition) + " or '" + index + "' can have the value " + indexValueString(*indexValue, containerName) + ". Expression '" + expression + "' causes access out of bounds."; else errmsg = "Out of bounds access in expression '" + expression + "'"; } else if (containerSize->intvalue == 0) { if (containerSize->condition) errmsg = ValueFlow::eitherTheConditionIsRedundant(containerSize->condition) + " or expression '" + expression + "' causes access out of bounds."; else if (indexValue == nullptr && !index.empty() && tok->valueType() && tok->valueType()->type == ValueType::ITERATOR) errmsg = "Out of bounds access in expression '" + expression + "' because '$symbol' is empty and '" + index + "' may be non-zero."; else errmsg = "Out of bounds access in expression '" + expression + "' because '$symbol' is empty."; } else if (indexValue) { if (containerSize->condition) errmsg = ValueFlow::eitherTheConditionIsRedundant(containerSize->condition) + " or size of '$symbol' can be " + std::to_string(containerSize->intvalue) + ". Expression '" + expression + "' causes access out of bounds."; else if (indexValue->condition) errmsg = ValueFlow::eitherTheConditionIsRedundant(indexValue->condition) + " or '" + index + "' can have the value " + indexValueString(*indexValue) + ". Expression '" + expression + "' causes access out of bounds."; else errmsg = "Out of bounds access in '" + expression + "', if '$symbol' size is " + std::to_string(containerSize->intvalue) + " and '" + index + "' is " + indexValueString(*indexValue); } else { // should not happen return; } ErrorPath errorPath; if (!indexValue) errorPath = getErrorPath(tok, containerSize, "Access out of bounds"); else { ErrorPath errorPath1 = getErrorPath(tok, containerSize, "Access out of bounds"); ErrorPath errorPath2 = getErrorPath(tok, indexValue, "Access out of bounds"); if (errorPath1.size() <= 1) errorPath = std::move(errorPath2); else if (errorPath2.size() <= 1) errorPath = std::move(errorPath1); else { errorPath = std::move(errorPath1); errorPath.splice(errorPath.end(), errorPath2); } } reportError(errorPath, (containerSize && !containerSize->errorSeverity()) || (indexValue && !indexValue->errorSeverity()) ? Severity::warning : Severity::error, "containerOutOfBounds", "$symbol:" + containerName +"\n" + errmsg, CWE398, (containerSize && containerSize->isInconclusive()) || (indexValue && indexValue->isInconclusive()) ? Certainty::inconclusive : Certainty::normal); } bool CheckStl::isContainerSize(const Token *containerToken, const Token *expr) const { if (!Token::simpleMatch(expr, "( )")) return false; if (!Token::Match(expr->astOperand1(), ". %name% (")) return false; if (!isSameExpression(false, containerToken, expr->astOperand1()->astOperand1(), *mSettings, false, false)) return false; return containerToken->valueType()->container->getYield(expr->strAt(-1)) == Library::Container::Yield::SIZE; } bool CheckStl::isContainerSizeGE(const Token * containerToken, const Token *expr) const { if (!expr) return false; if (isContainerSize(containerToken, expr)) return true; if (expr->str() == "*") { const Token *mul; if (isContainerSize(containerToken, expr->astOperand1())) mul = expr->astOperand2(); else if (isContainerSize(containerToken, expr->astOperand2())) mul = expr->astOperand1(); else return false; return mul && (!mul->hasKnownIntValue() || mul->values().front().intvalue != 0); } if (expr->str() == "+") { const Token *op; if (isContainerSize(containerToken, expr->astOperand1())) op = expr->astOperand2(); else if (isContainerSize(containerToken, expr->astOperand2())) op = expr->astOperand1(); else return false; return op && op->getValueGE(0, *mSettings); } return false; } void CheckStl::outOfBoundsIndexExpression() { logChecker("CheckStl::outOfBoundsIndexExpression"); for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) { for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) { if (!tok->isName() || !tok->valueType()) continue; const Library::Container *container = tok->valueType()->container; if (!container) continue; if (!container->arrayLike_indexOp && !container->stdStringLike) continue; if (!Token::Match(tok, "%name% [")) continue; if (isContainerSizeGE(tok, tok->next()->astOperand2())) outOfBoundsIndexExpressionError(tok, tok->next()->astOperand2()); } } } void CheckStl::outOfBoundsIndexExpressionError(const Token *tok, const Token *index) { const std::string varname = tok ? tok->str() : std::string("var"); const std::string i = index ? index->expressionString() : (varname + ".size()"); std::string errmsg = "Out of bounds access of $symbol, index '" + i + "' is out of bounds."; reportError(tok, Severity::error, "containerOutOfBoundsIndexExpression", "$symbol:" + varname +"\n" + errmsg, CWE398, Certainty::normal); } // Error message for bad iterator usage.. void CheckStl::invalidIteratorError(const Token *tok, const std::string &iteratorName) { reportError(tok, Severity::error, "invalidIterator1", "$symbol:"+iteratorName+"\nInvalid iterator: $symbol", CWE664, Certainty::normal); } void CheckStl::iteratorsError(const Token* tok, const std::string& containerName1, const std::string& containerName2) { reportError(tok, Severity::error, "iterators1", "$symbol:" + containerName1 + "\n" "$symbol:" + containerName2 + "\n" "Same iterator is used with different containers '" + containerName1 + "' and '" + containerName2 + "'.", CWE664, Certainty::normal); } void CheckStl::iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName1, const std::string& containerName2) { std::list<const Token*> callstack = { tok, containerTok }; reportError(callstack, Severity::error, "iterators2", "$symbol:" + containerName1 + "\n" "$symbol:" + containerName2 + "\n" "Same iterator is used with different containers '" + containerName1 + "' and '" + containerName2 + "'.", CWE664, Certainty::normal); } void CheckStl::iteratorsError(const Token* tok, const Token* containerTok, const std::string& containerName) { std::list<const Token*> callstack = { tok, containerTok }; reportError(callstack, Severity::error, "iterators3", "$symbol:" + containerName + "\n" "Same iterator is used with containers '$symbol' that are temporaries or defined in different scopes.", CWE664, Certainty::normal); } // Error message used when dereferencing an iterator that has been erased.. void CheckStl::dereferenceErasedError(const Token *erased, const Token* deref, const std::string &itername, bool inconclusive) { if (erased) { std::list<const Token*> callstack = { deref, erased }; reportError(callstack, Severity::error, "eraseDereference", "$symbol:" + itername + "\n" "Iterator '$symbol' used after element has been erased.\n" "The iterator '$symbol' is invalid after the element it pointed to has been erased. " "Dereferencing or comparing it with another iterator is invalid operation.", CWE664, inconclusive ? Certainty::inconclusive : Certainty::normal); } else { reportError(deref, Severity::error, "eraseDereference", "$symbol:" + itername + "\n" "Invalid iterator '$symbol' used.\n" "The iterator '$symbol' is invalid before being assigned. " "Dereferencing or comparing it with another iterator is invalid operation.", CWE664, inconclusive ? Certainty::inconclusive : Certainty::normal); } } static const Token *skipMembers(const Token *tok) { while (Token::Match(tok, "%name% .")) tok = tok->tokAt(2); return tok; } static bool isIterator(const Variable *var, bool& inconclusiveType) { // Check that its an iterator if (!var || !var->isLocal() || !Token::Match(var->typeEndToken(), "iterator|const_iterator|reverse_iterator|const_reverse_iterator|auto")) return false; inconclusiveType = false; if (var->typeEndToken()->str() == "auto") return (var->nameToken()->valueType() && var->nameToken()->valueType()->type == ValueType::Type::ITERATOR); if (var->type()) { // If it is defined, ensure that it is defined like an iterator // look for operator* and operator++ const Function* end = var->type()->getFunction("operator*"); const Function* incOperator = var->type()->getFunction("operator++"); if (!end || end->argCount() > 0 || !incOperator) return false; inconclusiveType = true; // heuristics only } return true; } static std::string getContainerName(const Token *containerToken) { if (!containerToken) return std::string(); std::string ret(containerToken->str()); for (const Token *nametok = containerToken; nametok; nametok = nametok->tokAt(-2)) { if (!Token::Match(nametok->tokAt(-2), "%name% .")) break; ret = nametok->strAt(-2) + '.' + ret; } return ret; } static bool isVector(const Token* tok) { if (!tok) return false; const Variable *var = tok->variable(); const Token *decltok = var ? var->typeStartToken() : nullptr; return Token::simpleMatch(decltok, "std :: vector"); } void CheckStl::iterators() { logChecker("CheckStl::iterators"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); // Filling map of iterators id and their scope begin std::map<int, const Token*> iteratorScopeBeginInfo; for (const Variable* var : symbolDatabase->variableList()) { bool inconclusiveType=false; if (!isIterator(var, inconclusiveType)) continue; const int iteratorId = var->declarationId(); if (iteratorId != 0) iteratorScopeBeginInfo[iteratorId] = var->nameToken(); } for (const Variable* var : symbolDatabase->variableList()) { bool inconclusiveType=false; if (!isIterator(var, inconclusiveType)) continue; if (inconclusiveType && !mSettings->certainty.isEnabled(Certainty::inconclusive)) continue; const int iteratorId = var->declarationId(); // the validIterator flag says if the iterator has a valid value or not bool validIterator = Token::Match(var->nameToken()->next(), "[(=:{]"); const Scope* invalidationScope = nullptr; // The container this iterator can be used with const Token* containerToken = nullptr; const Scope* containerAssignScope = nullptr; // When "validatingToken" is reached the validIterator is set to true const Token* validatingToken = nullptr; const Token* eraseToken = nullptr; // Scan through the rest of the code and see if the iterator is // used against other containers. for (const Token *tok2 = var->nameToken(); tok2 && tok2 != var->scope()->bodyEnd; tok2 = tok2->next()) { if (invalidationScope && tok2 == invalidationScope->bodyEnd) validIterator = true; // Assume that the iterator becomes valid again if (containerAssignScope && tok2 == containerAssignScope->bodyEnd) containerToken = nullptr; // We don't know which containers might be used with the iterator if (tok2 == validatingToken) { validIterator = true; eraseToken = nullptr; invalidationScope = nullptr; } // Is the iterator used in a insert/erase operation? if (Token::Match(tok2, "%name% . insert|erase ( *| %varid% )|,", iteratorId) && !isVector(tok2)) { const Token* itTok = tok2->tokAt(4); if (itTok->str() == "*") { if (tok2->strAt(2) == "insert") continue; itTok = itTok->next(); } // It is bad to insert/erase an invalid iterator if (!validIterator) invalidIteratorError(tok2, itTok->str()); // If insert/erase is used on different container then // report an error if (containerToken && tok2->varId() != containerToken->varId()) { // skip error message if container is a set.. const Variable *variableInfo = tok2->variable(); const Token *decltok = variableInfo ? variableInfo->typeStartToken() : nullptr; if (Token::simpleMatch(decltok, "std :: set")) continue; // No warning // skip error message if the iterator is erased/inserted by value if (itTok->strAt(-1) == "*") continue; // inserting iterator range.. if (tok2->strAt(2) == "insert") { const Token *par2 = itTok->nextArgument(); if (!par2 || par2->nextArgument()) continue; while (par2->str() != ")") { if (par2->varId() == containerToken->varId()) break; bool inconclusiveType2=false; if (isIterator(par2->variable(), inconclusiveType2)) break; // TODO: check if iterator points at same container if (par2->str() == "(") par2 = par2->link(); par2 = par2->next(); } if (par2->str() != ")") continue; } // Not different containers if a reference is used.. if (containerToken && containerToken->variable() && containerToken->variable()->isReference()) { const Token *nameToken = containerToken->variable()->nameToken(); if (Token::Match(nameToken, "%name% =")) { const Token *name1 = nameToken->tokAt(2); const Token *name2 = tok2; while (Token::Match(name1, "%name%|.|::") && name2 && name1->str() == name2->str()) { name1 = name1->next(); name2 = name2->next(); } if (!Token::simpleMatch(name1, ";") || !Token::Match(name2, "[;,()=]")) continue; } } // Show error message, mismatching iterator is used. iteratorsError(tok2, getContainerName(containerToken), getContainerName(tok2)); } // invalidate the iterator if it is erased else if (tok2->strAt(2) == "erase" && (tok2->strAt(4) != "*" || (containerToken && tok2->varId() == containerToken->varId()))) { validIterator = false; eraseToken = tok2; invalidationScope = tok2->scope(); } // skip the operation tok2 = itTok->next(); } // it = foo.erase(.. // taking the result of an erase is ok else if (Token::Match(tok2, "%varid% = %name% .", iteratorId) && Token::simpleMatch(skipMembers(tok2->tokAt(2)), "erase (")) { // the returned iterator is valid validatingToken = skipMembers(tok2->tokAt(2))->linkAt(1); tok2 = validatingToken->link(); } // Reassign the iterator else if (Token::Match(tok2, "%varid% = %name% .", iteratorId) && Token::Match(skipMembers(tok2->tokAt(2)), "begin|rbegin|cbegin|crbegin|find (")) { validatingToken = skipMembers(tok2->tokAt(2))->linkAt(1); containerToken = skipMembers(tok2->tokAt(2))->tokAt(-2); if (containerToken->varId() == 0 || Token::simpleMatch(validatingToken, ") .")) containerToken = nullptr; containerAssignScope = tok2->scope(); // skip ahead tok2 = validatingToken->link(); } // Reassign the iterator else if (Token::Match(tok2, "%varid% =", iteratorId)) { break; } // Passing iterator to function. Iterator might be initialized else if (Token::Match(tok2, "%varid% ,|)", iteratorId)) { validIterator = true; } // Dereferencing invalid iterator? else if (!validIterator && Token::Match(tok2, "* %varid%", iteratorId)) { dereferenceErasedError(eraseToken, tok2, tok2->strAt(1), inconclusiveType); tok2 = tok2->next(); } else if (!validIterator && Token::Match(tok2, "%varid% . %name%", iteratorId)) { dereferenceErasedError(eraseToken, tok2, tok2->str(), inconclusiveType); tok2 = tok2->tokAt(2); } // bailout handling. Assume that the iterator becomes valid if we see return/break. // TODO: better handling else if (tok2->scope() == invalidationScope && Token::Match(tok2, "return|break|continue")) { validatingToken = Token::findsimplematch(tok2->next(), ";"); } // bailout handling. Assume that the iterator becomes valid if we see else. // TODO: better handling else if (tok2->str() == "else") { validIterator = true; } } } } void CheckStl::mismatchingContainerIteratorError(const Token* containerTok, const Token* iterTok, const Token* containerTok2) { const std::string container(containerTok ? containerTok->expressionString() : std::string("v1")); const std::string container2(containerTok2 ? containerTok2->expressionString() : std::string("v2")); const std::string iter(iterTok ? iterTok->expressionString() : std::string("it")); reportError(containerTok, Severity::error, "mismatchingContainerIterator", "Iterator '" + iter + "' referring to container '" + container2 + "' is used with container '" + container + "'.", CWE664, Certainty::normal); } // Error message for bad iterator usage.. void CheckStl::mismatchingContainersError(const Token* tok1, const Token* tok2) { const std::string expr1(tok1 ? tok1->expressionString() : std::string("v1")); const std::string expr2(tok2 ? tok2->expressionString() : std::string("v2")); reportError(tok1, Severity::error, "mismatchingContainers", "Iterators of different containers '" + expr1 + "' and '" + expr2 + "' are used together.", CWE664, Certainty::normal); } void CheckStl::mismatchingContainerExpressionError(const Token *tok1, const Token *tok2) { const std::string expr1(tok1 ? tok1->expressionString() : std::string("v1")); const std::string expr2(tok2 ? tok2->expressionString() : std::string("v2")); reportError(tok1, Severity::warning, "mismatchingContainerExpression", "Iterators to containers from different expressions '" + expr1 + "' and '" + expr2 + "' are used together.", CWE664, Certainty::normal); } void CheckStl::sameIteratorExpressionError(const Token *tok) { reportError(tok, Severity::style, "sameIteratorExpression", "Same iterators expression are used for algorithm.", CWE664, Certainty::normal); } static std::vector<const Token*> getAddressContainer(const Token* tok) { if (Token::simpleMatch(tok, "[") && tok->astOperand1()) return { tok->astOperand1() }; while (Token::simpleMatch(tok, "::") && tok->astOperand2()) tok = tok->astOperand2(); std::vector<ValueFlow::Value> values = ValueFlow::getLifetimeObjValues(tok, /*inconclusive*/ false); std::vector<const Token*> res; for (const auto& v : values) { if (v.tokvalue) res.emplace_back(v.tokvalue); } if (res.empty()) res.emplace_back(tok); return res; } static bool isSameIteratorContainerExpression(const Token* tok1, const Token* tok2, const Settings& settings, ValueFlow::Value::LifetimeKind kind = ValueFlow::Value::LifetimeKind::Iterator) { if (isSameExpression(false, tok1, tok2, settings, false, false)) { return !astIsContainerOwned(tok1) || !isTemporary(tok1, &settings.library); } if (astContainerYield(tok2) == Library::Container::Yield::ITEM) return true; if (kind == ValueFlow::Value::LifetimeKind::Address || kind == ValueFlow::Value::LifetimeKind::Iterator) { const auto address1 = getAddressContainer(tok1); const auto address2 = getAddressContainer(tok2); return std::any_of(address1.begin(), address1.end(), [&](const Token* tok1) { return std::any_of(address2.begin(), address2.end(), [&](const Token* tok2) { return isSameExpression(false, tok1, tok2, settings, false, false); }); }); } return false; } static ValueFlow::Value getLifetimeIteratorValue(const Token* tok, MathLib::bigint path = 0) { auto findIterVal = [](const std::vector<ValueFlow::Value>& values, const std::vector<ValueFlow::Value>::const_iterator beg) { return std::find_if(beg, values.cend(), [](const ValueFlow::Value& v) { return v.lifetimeKind == ValueFlow::Value::LifetimeKind::Iterator; }); }; std::vector<ValueFlow::Value> values = ValueFlow::getLifetimeObjValues(tok, false, path); auto it = findIterVal(values, values.begin()); if (it != values.end()) { auto it2 = findIterVal(values, it + 1); if (it2 == values.cend()) return *it; } if (values.size() == 1) return values.front(); return ValueFlow::Value{}; } bool CheckStl::checkIteratorPair(const Token* tok1, const Token* tok2) { if (!tok1) return false; if (!tok2) return false; ValueFlow::Value val1 = getLifetimeIteratorValue(tok1); ValueFlow::Value val2 = getLifetimeIteratorValue(tok2); if (val1.tokvalue && val2.tokvalue && val1.lifetimeKind == val2.lifetimeKind) { if (val1.lifetimeKind == ValueFlow::Value::LifetimeKind::Lambda) return false; if (tok1->astParent() == tok2->astParent() && Token::Match(tok1->astParent(), "%comp%|-")) { if (val1.lifetimeKind == ValueFlow::Value::LifetimeKind::Address) return false; if (val1.lifetimeKind == ValueFlow::Value::LifetimeKind::Object && (!astIsContainer(val1.tokvalue) || !astIsContainer(val2.tokvalue))) return false; } if (isSameIteratorContainerExpression(val1.tokvalue, val2.tokvalue, *mSettings, val1.lifetimeKind)) return false; if (val1.tokvalue->expressionString() == val2.tokvalue->expressionString()) iteratorsError(tok1, val1.tokvalue, val1.tokvalue->expressionString()); else mismatchingContainersError(val1.tokvalue, val2.tokvalue); return true; } if (Token::Match(tok1->astParent(), "%comp%|-")) { if (astIsIntegral(tok1, true) || astIsIntegral(tok2, true) || astIsFloat(tok1, true) || astIsFloat(tok2, true)) return false; } const Token* iter1 = getIteratorExpression(tok1); const Token* iter2 = getIteratorExpression(tok2); if (iter1 && iter2 && !isSameIteratorContainerExpression(iter1, iter2, *mSettings)) { mismatchingContainerExpressionError(iter1, iter2); return true; } return false; } namespace { struct ArgIteratorInfo { const Token* tok; const Library::ArgumentChecks::IteratorInfo* info; }; } void CheckStl::mismatchingContainers() { logChecker("CheckStl::misMatchingContainers"); // Check if different containers are used in various calls of standard functions const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "%comp%|-")) { if (checkIteratorPair(tok->astOperand1(), tok->astOperand2())) continue; } if (!Token::Match(tok, "%name% ( !!)")) continue; const Token * const ftok = tok; const std::vector<const Token *> args = getArguments(ftok); if (args.size() < 2) continue; // Group args together by container std::map<int, std::vector<ArgIteratorInfo>> containers; for (int argnr = 1; argnr <= args.size(); ++argnr) { const Library::ArgumentChecks::IteratorInfo *i = mSettings->library.getArgIteratorInfo(ftok, argnr); if (!i) continue; const Token * const argTok = args[argnr - 1]; containers[i->container].emplace_back(ArgIteratorInfo{argTok, i}); } // Lambda is used to escape the nested loops [&] { for (const auto& p : containers) { const std::vector<ArgIteratorInfo>& cargs = p.second; for (ArgIteratorInfo iter1 : cargs) { for (ArgIteratorInfo iter2 : cargs) { if (iter1.tok == iter2.tok) continue; if (iter1.info->first && iter2.info->last && isSameExpression(false, iter1.tok, iter2.tok, *mSettings, false, false)) sameIteratorExpressionError(iter1.tok); if (checkIteratorPair(iter1.tok, iter2.tok)) return; } } } }(); } } for (const Variable *var : symbolDatabase->variableList()) { if (var && var->isStlStringType() && Token::Match(var->nameToken(), "%var% (") && Token::Match(var->nameToken()->tokAt(2), "%name% . begin|cbegin|rbegin|crbegin ( ) , %name% . end|cend|rend|crend ( ) ,|)")) { if (var->nameToken()->strAt(2) != var->nameToken()->strAt(8)) { mismatchingContainersError(var->nameToken(), var->nameToken()->tokAt(2)); } } } } void CheckStl::mismatchingContainerIterator() { logChecker("CheckStl::misMatchingContainerIterator"); // Check if different containers are used in various calls of standard functions const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!astIsContainer(tok)) continue; if (!astIsLHS(tok)) continue; if (!Token::Match(tok->astParent(), ". %name% ( !!)")) continue; const Token* const ftok = tok->astParent()->next(); const std::vector<const Token *> args = getArguments(ftok); const Library::Container * c = tok->valueType()->container; const Library::Container::Action action = c->getAction(tok->strAt(2)); const Token* iterTok = nullptr; if (action == Library::Container::Action::INSERT && args.size() == 2) { // Skip if iterator pair if (astIsIterator(args.back())) continue; if (!astIsIterator(args.front())) continue; iterTok = args.front(); } else if (action == Library::Container::Action::ERASE) { if (!astIsIterator(args.front())) continue; iterTok = args.front(); } else { continue; } ValueFlow::Value val = getLifetimeIteratorValue(iterTok); if (!val.tokvalue) continue; if (!val.isKnown() && Token::simpleMatch(val.tokvalue->astParent(), ":")) continue; if (val.lifetimeKind != ValueFlow::Value::LifetimeKind::Iterator) continue; if (iterTok->str() == "*" && iterTok->astOperand1()->valueType() && iterTok->astOperand1()->valueType()->type == ValueType::ITERATOR) continue; if (isSameIteratorContainerExpression(tok, val.tokvalue, *mSettings)) continue; mismatchingContainerIteratorError(tok, iterTok, val.tokvalue); } } } static const Token* getInvalidMethod(const Token* tok) { if (!astIsLHS(tok)) return nullptr; if (Token::Match(tok->astParent(), ". assign|clear|swap")) return tok->astParent()->next(); if (Token::Match(tok->astParent(), "%assign%")) return tok->astParent(); const Token* ftok = nullptr; if (Token::Match(tok->astParent(), ". %name% (")) ftok = tok->astParent()->next(); if (!ftok) return nullptr; if (const Library::Container * c = tok->valueType()->container) { const Library::Container::Action action = c->getAction(ftok->str()); if (c->unstableErase) { if (action == Library::Container::Action::ERASE) return ftok; } if (c->unstableInsert) { if (action == Library::Container::Action::RESIZE) return ftok; if (action == Library::Container::Action::CLEAR) return ftok; if (action == Library::Container::Action::PUSH) return ftok; if (action == Library::Container::Action::POP) return ftok; if (action == Library::Container::Action::INSERT) return ftok; if (action == Library::Container::Action::CHANGE) return ftok; if (action == Library::Container::Action::CHANGE_INTERNAL) return ftok; if (Token::Match(ftok, "insert|emplace")) return ftok; } } return nullptr; } namespace { struct InvalidContainerAnalyzer { struct Info { struct Reference { const Token* tok; ErrorPath errorPath; const Token* ftok; }; std::unordered_map<int, Reference> expressions; void add(const std::vector<Reference>& refs) { for (const Reference& r : refs) { add(r); } } void add(const Reference& r) { if (!r.tok) return; expressions.insert(std::make_pair(r.tok->exprId(), r)); } std::vector<Reference> invalidTokens() const { std::vector<Reference> result; std::transform(expressions.cbegin(), expressions.cend(), std::back_inserter(result), SelectMapValues{}); return result; } }; std::unordered_map<const Function*, Info> invalidMethods; std::vector<Info::Reference> invalidatesContainer(const Token* tok) const { std::vector<Info::Reference> result; if (Token::Match(tok, "%name% (")) { const Function* f = tok->function(); if (!f) return result; ErrorPathItem epi = std::make_pair(tok, "Calling function " + tok->str()); const bool dependsOnThis = exprDependsOnThis(tok->next()); auto it = invalidMethods.find(f); if (it != invalidMethods.end()) { std::vector<Info::Reference> refs = it->second.invalidTokens(); std::copy_if(refs.cbegin(), refs.cend(), std::back_inserter(result), [&](const Info::Reference& r) { const Variable* var = r.tok->variable(); if (!var) return false; if (dependsOnThis && !var->isLocal() && !var->isGlobal() && !var->isStatic()) return true; if (!var->isArgument()) return false; if (!var->isReference()) return false; return true; }); std::vector<const Token*> args = getArguments(tok); for (Info::Reference& r : result) { r.errorPath.push_front(epi); r.ftok = tok; const Variable* var = r.tok->variable(); if (!var) continue; if (var->isArgument()) { const int n = getArgumentPos(var, f); const Token* tok2 = nullptr; if (n >= 0 && n < args.size()) tok2 = args[n]; r.tok = tok2; } } } } else if (astIsContainer(tok)) { const Token* ftok = getInvalidMethod(tok); if (ftok) { ErrorPath ep; ep.emplace_front(ftok, "After calling '" + ftok->expressionString() + "', iterators or references to the container's data may be invalid ."); result.emplace_back(Info::Reference{tok, std::move(ep), ftok}); } } return result; } void analyze(const SymbolDatabase* symboldatabase) { for (const Scope* scope : symboldatabase->functionScopes) { const Function* f = scope->function; if (!f) continue; for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "if|while|for|goto|return")) break; std::vector<Info::Reference> c = invalidatesContainer(tok); if (c.empty()) continue; invalidMethods[f].add(c); } } } }; } static const Token* getLoopContainer(const Token* tok) { if (!Token::simpleMatch(tok, "for (")) return nullptr; const Token* sepTok = tok->next()->astOperand2(); if (!Token::simpleMatch(sepTok, ":")) return nullptr; return sepTok->astOperand2(); } static const ValueFlow::Value* getInnerLifetime(const Token* tok, nonneg int id, ErrorPath* errorPath = nullptr, int depth = 4) { if (depth < 0) return nullptr; if (!tok) return nullptr; for (const ValueFlow::Value& val : tok->values()) { if (!val.isLocalLifetimeValue()) continue; if (contains({ValueFlow::Value::LifetimeKind::Address, ValueFlow::Value::LifetimeKind::SubObject, ValueFlow::Value::LifetimeKind::Lambda}, val.lifetimeKind)) { if (val.isInconclusive()) return nullptr; if (val.capturetok) return getInnerLifetime(val.capturetok, id, errorPath, depth - 1); if (errorPath) errorPath->insert(errorPath->end(), val.errorPath.cbegin(), val.errorPath.cend()); return getInnerLifetime(val.tokvalue, id, errorPath, depth - 1); } if (!val.tokvalue->variable()) continue; if (val.tokvalue->varId() != id) continue; return &val; } return nullptr; } static const Token* endOfExpression(const Token* tok) { if (!tok) return nullptr; const Token* parent = tok->astParent(); while (Token::simpleMatch(parent, ".")) parent = parent->astParent(); if (!parent) return tok->next(); const Token* endToken = nextAfterAstRightmostLeaf(parent); if (!endToken) return parent->next(); return endToken; } void CheckStl::invalidContainer() { logChecker("CheckStl::invalidContainer"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); const Library& library = mSettings->library; InvalidContainerAnalyzer analyzer; analyzer.analyze(symbolDatabase); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (const Token* contTok = getLoopContainer(tok)) { const Token* blockStart = tok->linkAt(1)->next(); const Token* blockEnd = blockStart->link(); if (contTok->exprId() == 0) continue; if (!astIsContainer(contTok)) continue; for (const Token* tok2 = blockStart; tok2 != blockEnd; tok2 = tok2->next()) { bool bail = false; for (const InvalidContainerAnalyzer::Info::Reference& r : analyzer.invalidatesContainer(tok2)) { if (!astIsContainer(r.tok)) continue; if (r.tok->exprId() != contTok->exprId()) continue; const Scope* s = tok2->scope(); if (!s) continue; if (isReturnScope(s->bodyEnd, mSettings->library)) continue; invalidContainerLoopError(r.ftok, tok, r.errorPath); bail = true; break; } if (bail) break; } } else { for (const InvalidContainerAnalyzer::Info::Reference& r : analyzer.invalidatesContainer(tok)) { if (!astIsContainer(r.tok)) continue; std::set<nonneg int> skipVarIds; // Skip if the variable is assigned to const Token* assignExpr = tok; while (assignExpr->astParent()) { const bool isRHS = astIsRHS(assignExpr); assignExpr = assignExpr->astParent(); if (Token::Match(assignExpr, "%assign%")) { if (!isRHS) assignExpr = nullptr; break; } } if (Token::Match(assignExpr, "%assign%") && Token::Match(assignExpr->astOperand1(), "%var%")) skipVarIds.insert(assignExpr->astOperand1()->varId()); const Token* endToken = endOfExpression(tok); const ValueFlow::Value* v = nullptr; ErrorPath errorPath; PathAnalysis::Info info = PathAnalysis{endToken, library}.forwardFind([&](const PathAnalysis::Info& info) { if (!info.tok->variable()) return false; if (info.tok->varId() == 0) return false; if (skipVarIds.count(info.tok->varId()) > 0) return false; // if (Token::simpleMatch(info.tok->next(), ".")) // return false; if (Token::Match(info.tok->astParent(), "%assign%") && astIsLHS(info.tok)) skipVarIds.insert(info.tok->varId()); if (info.tok->variable()->isReference() && !isVariableDecl(info.tok) && reaches(info.tok->variable()->nameToken(), tok, library, nullptr)) { ErrorPath ep; bool addressOf = false; const Variable* var = ValueFlow::getLifetimeVariable(info.tok, ep, *mSettings, &addressOf); // Check the reference is created before the change if (var && var->declarationId() == r.tok->varId() && !addressOf) { // An argument always reaches if (var->isArgument() || (!var->isReference() && !var->isRValueReference() && !isVariableDecl(tok) && reaches(var->nameToken(), tok, library, &ep))) { errorPath = std::move(ep); return true; } } } ErrorPath ep; const ValueFlow::Value* val = getInnerLifetime(info.tok, r.tok->varId(), &ep); // Check the iterator is created before the change if (val && val->tokvalue != tok && reaches(val->tokvalue, tok, library, &ep)) { v = val; errorPath = std::move(ep); return true; } return false; }); if (!info.tok) continue; errorPath.insert(errorPath.end(), info.errorPath.cbegin(), info.errorPath.cend()); errorPath.insert(errorPath.end(), r.errorPath.cbegin(), r.errorPath.cend()); if (v) { invalidContainerError(info.tok, r.tok, v, std::move(errorPath)); } else { invalidContainerReferenceError(info.tok, r.tok, std::move(errorPath)); } } } } } } void CheckStl::invalidContainerLoopError(const Token* tok, const Token* loopTok, ErrorPath errorPath) { const std::string method = tok ? tok->str() : "erase"; errorPath.emplace_back(loopTok, "Iterating container here."); // Remove duplicate entries from error path errorPath.remove_if([&](const ErrorPathItem& epi) { return epi.first == tok; }); const std::string msg = "Calling '" + method + "' while iterating the container is invalid."; errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "invalidContainerLoop", msg, CWE664, Certainty::normal); } void CheckStl::invalidContainerError(const Token *tok, const Token * /*contTok*/, const ValueFlow::Value *val, ErrorPath errorPath) { const bool inconclusive = val ? val->isInconclusive() : false; if (val) errorPath.insert(errorPath.begin(), val->errorPath.cbegin(), val->errorPath.cend()); std::string msg = "Using " + lifetimeMessage(tok, val, errorPath); errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "invalidContainer", msg + " that may be invalid.", CWE664, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckStl::invalidContainerReferenceError(const Token* tok, const Token* contTok, ErrorPath errorPath) { std::string name = contTok ? contTok->expressionString() : "x"; std::string msg = "Reference to " + name; errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "invalidContainerReference", msg + " that may be invalid.", CWE664, Certainty::normal); } void CheckStl::stlOutOfBounds() { logChecker("CheckStl::stlOutOfBounds"); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); // Scan through all scopes.. for (const Scope &scope : symbolDatabase->scopeList) { const Token* tok = scope.classDef; // only interested in conditions if ((!scope.isLoopScope() && scope.type != Scope::eIf) || !tok) continue; const Token *condition = nullptr; if (scope.type == Scope::eFor) { if (Token::simpleMatch(tok->next()->astOperand2(), ";") && Token::simpleMatch(tok->next()->astOperand2()->astOperand2(), ";")) condition = tok->next()->astOperand2()->astOperand2()->astOperand1(); } else if (Token::simpleMatch(tok, "do {") && Token::simpleMatch(tok->linkAt(1), "} while (")) condition = tok->linkAt(1)->tokAt(2)->astOperand2(); else condition = tok->next()->astOperand2(); if (!condition) continue; std::vector<const Token *> conds; visitAstNodes(condition, [&](const Token *cond) { if (Token::Match(cond, "%oror%|&&")) return ChildrenToVisit::op1_and_op2; if (cond->isComparisonOp()) conds.emplace_back(cond); return ChildrenToVisit::none; }); for (const Token *cond : conds) { const Token *vartok; const Token *containerToken; // check in the ast that cond is of the form "%var% <= %var% . %name% ( )" if (cond->str() == "<=" && Token::Match(cond->astOperand1(), "%var%") && cond->astOperand2()->str() == "(" && cond->astOperand2()->astOperand1()->str() == "." && Token::Match(cond->astOperand2()->astOperand1()->astOperand1(), "%var%") && Token::Match(cond->astOperand2()->astOperand1()->astOperand2(), "%name%")) { vartok = cond->astOperand1(); containerToken = cond->next(); } else { continue; } if (containerToken->hasKnownValue(ValueFlow::Value::ValueType::CONTAINER_SIZE)) continue; // Is it a array like container? const Library::Container* container = containerToken->valueType() ? containerToken->valueType()->container : nullptr; if (!container) continue; if (container->getYield(containerToken->strAt(2)) != Library::Container::Yield::SIZE) continue; // variable id for loop variable. const int numId = vartok->varId(); // variable id for the container variable const int declarationId = containerToken->varId(); const std::string &containerName = containerToken->str(); for (const Token *tok3 = scope.bodyStart; tok3 && tok3 != scope.bodyEnd; tok3 = tok3->next()) { if (tok3->varId() == declarationId) { tok3 = tok3->next(); if (Token::Match(tok3, ". %name% ( )")) { if (container->getYield(tok3->strAt(1)) == Library::Container::Yield::SIZE) break; } else if (container->arrayLike_indexOp && Token::Match(tok3, "[ %varid% ]", numId)) stlOutOfBoundsError(tok3, tok3->strAt(1), containerName, false); else if (Token::Match(tok3, ". %name% ( %varid% )", numId)) { const Library::Container::Yield yield = container->getYield(tok3->strAt(1)); if (yield == Library::Container::Yield::AT_INDEX) stlOutOfBoundsError(tok3, tok3->strAt(3), containerName, true); } } } } } } void CheckStl::stlOutOfBoundsError(const Token *tok, const std::string &num, const std::string &var, bool at) { if (at) reportError(tok, Severity::error, "stlOutOfBounds", "$symbol:" + var + "\nWhen " + num + "==$symbol.size(), $symbol.at(" + num + ") is out of bounds.", CWE788, Certainty::normal); else reportError(tok, Severity::error, "stlOutOfBounds", "$symbol:" + var + "\nWhen " + num + "==$symbol.size(), $symbol[" + num + "] is out of bounds.", CWE788, Certainty::normal); } void CheckStl::negativeIndex() { logChecker("CheckStl::negativeIndex"); // Negative index is out of bounds.. const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "%var% [") || !tok->next()->astOperand2()) continue; const Variable * const var = tok->variable(); if (!var || tok == var->nameToken()) continue; const Library::Container * const container = mSettings->library.detectContainer(var->typeStartToken()); if (!container || !container->arrayLike_indexOp) continue; const ValueFlow::Value *index = tok->next()->astOperand2()->getValueLE(-1, *mSettings); if (!index) continue; negativeIndexError(tok, *index); } } } void CheckStl::negativeIndexError(const Token *tok, const ValueFlow::Value &index) { const ErrorPath errorPath = getErrorPath(tok, &index, "Negative array index"); std::ostringstream errmsg; if (index.condition) errmsg << ValueFlow::eitherTheConditionIsRedundant(index.condition) << ", otherwise there is negative array index " << index.intvalue << "."; else errmsg << "Array index " << index.intvalue << " is out of bounds."; const auto severity = index.errorSeverity() && index.isKnown() ? Severity::error : Severity::warning; const auto certainty = index.isInconclusive() ? Certainty::inconclusive : Certainty::normal; reportError(errorPath, severity, "negativeContainerIndex", errmsg.str(), CWE786, certainty); } void CheckStl::erase() { logChecker("CheckStl::erase"); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type == Scope::eFor && Token::simpleMatch(scope.classDef, "for (")) { const Token *tok = scope.classDef->linkAt(1); if (!Token::Match(tok->tokAt(-3), "; ++| %var% ++| ) {")) continue; tok = tok->previous(); if (!tok->isName()) tok = tok->previous(); eraseCheckLoopVar(scope, tok->variable()); } else if (scope.type == Scope::eWhile && Token::Match(scope.classDef, "while ( %var% !=")) { eraseCheckLoopVar(scope, scope.classDef->tokAt(2)->variable()); } } } void CheckStl::eraseCheckLoopVar(const Scope &scope, const Variable *var) { bool inconclusiveType=false; if (!isIterator(var, inconclusiveType)) return; for (const Token *tok = scope.bodyStart; tok != scope.bodyEnd; tok = tok->next()) { if (tok->str() != "(") continue; if (!Token::Match(tok->tokAt(-2), ". erase ( ++| %varid% )", var->declarationId())) continue; // Vector erases are handled by invalidContainer check if (isVector(tok->tokAt(-3))) continue; if (Token::Match(tok->astParent(), "=|return")) continue; // Iterator is invalid.. int indentlevel = 0U; const Token *tok2 = tok->link(); for (; tok2 != scope.bodyEnd; tok2 = tok2->next()) { if (tok2->str() == "{") { ++indentlevel; continue; } if (tok2->str() == "}") { if (indentlevel > 0U) --indentlevel; else if (Token::simpleMatch(tok2, "} else {")) tok2 = tok2->linkAt(2); continue; } if (tok2->varId() == var->declarationId()) { if (Token::simpleMatch(tok2->next(), "=")) break; dereferenceErasedError(tok, tok2, tok2->str(), inconclusiveType); break; } if (indentlevel == 0U && Token::Match(tok2, "break|return|goto")) break; } if (tok2 == scope.bodyEnd) dereferenceErasedError(tok, scope.classDef, var->nameToken()->str(), inconclusiveType); } } void CheckStl::stlBoundaries() { logChecker("CheckStl::stlBoundaries"); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Variable* var : symbolDatabase->variableList()) { if (!var || !var->scope() || !var->scope()->isExecutable()) continue; const Library::Container* container = mSettings->library.detectIterator(var->typeStartToken()); if (!container || container->opLessAllowed) continue; const Token* const end = var->scope()->bodyEnd; for (const Token *tok = var->nameToken(); tok != end; tok = tok->next()) { if (Token::Match(tok, "!!* %varid% <", var->declarationId())) { stlBoundariesError(tok); } else if (Token::Match(tok, "> %varid% !!.", var->declarationId())) { stlBoundariesError(tok); } } } } // Error message for bad boundary usage.. void CheckStl::stlBoundariesError(const Token *tok) { reportError(tok, Severity::error, "stlBoundaries", "Dangerous comparison using operator< on iterator.\n" "Iterator compared with operator<. This is dangerous since the order of items in the " "container is not guaranteed. One should use operator!= instead to compare iterators.", CWE664, Certainty::normal); } static bool if_findCompare(const Token * const tokBack, bool stdStringLike) { const Token *tok = tokBack->astParent(); if (!tok) return true; if (tok->isComparisonOp()) { if (stdStringLike) { const Token * const tokOther = tokBack->astSibling(); return !tokOther || !tokOther->hasKnownIntValue() || tokOther->getKnownIntValue() != 0; } return (!tok->astOperand1()->isNumber() && !tok->astOperand2()->isNumber()); } if (tok->isArithmeticalOp()) // result is used in some calculation return true; // TODO: check if there is a comparison of the result somewhere if (tok->str() == ".") return true; // Dereferencing is OK, the programmer might know that the element exists - TODO: An inconclusive warning might be appropriate if (tok->isAssignmentOp()) return if_findCompare(tok, stdStringLike); // Go one step upwards in the AST return false; } void CheckStl::if_find() { const bool printWarning = mSettings->severity.isEnabled(Severity::warning); const bool printPerformance = mSettings->severity.isEnabled(Severity::performance); if (!printWarning && !printPerformance) return; logChecker("CheckStl::if_find"); // warning,performance const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if ((scope.type != Scope::eIf && scope.type != Scope::eWhile) || !scope.classDef) continue; const Token *conditionStart = scope.classDef->next(); if (Token::simpleMatch(conditionStart->astOperand2(), ";")) conditionStart = conditionStart->astOperand2(); for (const Token *tok = conditionStart; tok->str() != "{"; tok = tok->next()) { const Token* funcTok = nullptr; const Library::Container* container = nullptr; if (Token::Match(tok, "%name% (")) tok = tok->linkAt(1); else if (tok->variable() && Token::Match(tok, "%var% . %name% (")) { container = mSettings->library.detectContainer(tok->variable()->typeStartToken()); funcTok = tok->tokAt(2); } // check also for vector-like or pointer containers else if (tok->variable() && tok->astParent() && (tok->astParent()->str() == "*" || tok->astParent()->str() == "[")) { const Token *tok2 = tok->astParent(); if (!Token::Match(tok2->astParent(), ". %name% (")) continue; funcTok = tok2->astParent()->next(); if (tok->variable()->isArrayOrPointer()) container = mSettings->library.detectContainer(tok->variable()->typeStartToken()); else { // Container of container - find the inner container container = mSettings->library.detectContainer(tok->variable()->typeStartToken()); // outer container tok2 = Token::findsimplematch(tok->variable()->typeStartToken(), "<", tok->variable()->typeEndToken()); if (container && container->type_templateArgNo >= 0 && tok2) { tok2 = tok2->next(); for (int j = 0; j < container->type_templateArgNo; j++) tok2 = tok2->nextTemplateArgument(); container = mSettings->library.detectContainer(tok2); // inner container } else container = nullptr; } } Library::Container::Action action{}; if (container && ((action = container->getAction(funcTok->str())) == Library::Container::Action::FIND || action == Library::Container::Action::FIND_CONST)) { if (if_findCompare(funcTok->next(), container->stdStringLike)) continue; if (printWarning && container->getYield(funcTok->str()) == Library::Container::Yield::ITERATOR) if_findError(tok, false); else if (printPerformance && container->stdStringLike && funcTok->str() == "find") if_findError(tok, true); } else if (printWarning && Token::Match(tok, "std :: find|find_if (")) { // check that result is checked properly if (!if_findCompare(tok->tokAt(3), false)) { if_findError(tok, false); } } } } } void CheckStl::if_findError(const Token *tok, bool str) { if (str && mSettings->standards.cpp >= Standards::CPP20) reportError(tok, Severity::performance, "stlIfStrFind", "Inefficient usage of string::find() in condition; string::starts_with() could be faster.\n" "Either inefficient or wrong usage of string::find(). string::starts_with() will be faster if " "string::find's result is compared with 0, because it will not scan the whole " "string. If your intention is to check that there are no findings in the string, " "you should compare with std::string::npos.", CWE597, Certainty::normal); if (!str) reportError(tok, Severity::warning, "stlIfFind", "Suspicious condition. The result of find() is an iterator, but it is not properly checked.", CWE398, Certainty::normal); } static std::pair<const Token *, const Token *> isMapFind(const Token *tok) { if (!Token::simpleMatch(tok, "(")) return {}; if (!Token::simpleMatch(tok->astOperand1(), ".")) return {}; if (!astIsContainer(tok->astOperand1()->astOperand1())) return {}; const Token * contTok = tok->astOperand1()->astOperand1(); const Library::Container * container = contTok->valueType()->container; if (!container) return {}; if (!container->stdAssociativeLike) return {}; if (!Token::Match(tok->astOperand1(), ". find|count (")) return {}; if (!tok->astOperand2()) return {}; return {contTok, tok->astOperand2()}; } static const Token* skipLocalVars(const Token* const tok) { if (!tok) return tok; if (Token::simpleMatch(tok, "{")) return skipLocalVars(tok->next()); if (tok->isAssignmentOp()) { const Token *top = tok->astTop(); const Token *varTok = top->astOperand1(); const Variable *var = varTok->variable(); if (!var) return tok; if (var->scope() != tok->scope()) return tok; const Token *endTok = nextAfterAstRightmostLeaf(top); if (!endTok) return tok; return skipLocalVars(endTok->next()); } return tok; } static const Token *findInsertValue(const Token *tok, const Token *containerTok, const Token *keyTok, const Settings &settings) { const Token *startTok = skipLocalVars(tok); const Token *top = startTok->astTop(); const Token *icontainerTok = nullptr; const Token *ikeyTok = nullptr; const Token *ivalueTok = nullptr; if (Token::simpleMatch(top, "=") && Token::simpleMatch(top->astOperand1(), "[")) { icontainerTok = top->astOperand1()->astOperand1(); ikeyTok = top->astOperand1()->astOperand2(); ivalueTok = top->astOperand2(); } if (Token::simpleMatch(top, "(") && Token::Match(top->astOperand1(), ". insert|emplace (") && !astIsIterator(top->astOperand1()->tokAt(2))) { icontainerTok = top->astOperand1()->astOperand1(); const Token *itok = top->astOperand1()->tokAt(2)->astOperand2(); if (Token::simpleMatch(itok, ",")) { ikeyTok = itok->astOperand1(); ivalueTok = itok->astOperand2(); } else { ikeyTok = itok; } } if (!ikeyTok || !icontainerTok) return nullptr; if (isSameExpression(true, containerTok, icontainerTok, settings, true, false) && isSameExpression(true, keyTok, ikeyTok, settings, true, true)) { if (ivalueTok) return ivalueTok; return ikeyTok; } return nullptr; } void CheckStl::checkFindInsert() { if (!mSettings->severity.isEnabled(Severity::performance)) return; logChecker("CheckStl::checkFindInsert"); // performance const SymbolDatabase *const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::simpleMatch(tok, "if (")) continue; if (!Token::simpleMatch(tok->linkAt(1), ") {")) continue; if (!Token::Match(tok->next()->astOperand2(), "%comp%")) continue; const Token *condTok = tok->next()->astOperand2(); const Token *containerTok; const Token *keyTok; std::tie(containerTok, keyTok) = isMapFind(condTok->astOperand1()); if (!containerTok) continue; // In < C++17 we only warn for small simple types if (mSettings->standards.cpp < Standards::CPP17 && !(keyTok && keyTok->valueType() && (keyTok->valueType()->isIntegral() || keyTok->valueType()->pointer > 0))) continue; const Token *thenTok = tok->linkAt(1)->next(); const Token *valueTok = findInsertValue(thenTok, containerTok, keyTok, *mSettings); if (!valueTok) continue; if (Token::simpleMatch(thenTok->link(), "} else {")) { const Token *valueTok2 = findInsertValue(thenTok->link()->tokAt(2), containerTok, keyTok, *mSettings); if (!valueTok2) continue; if (isSameExpression(true, valueTok, valueTok2, *mSettings, true, true)) { checkFindInsertError(valueTok); } } else { checkFindInsertError(valueTok); } } } } void CheckStl::checkFindInsertError(const Token *tok) { std::string replaceExpr; if (tok && Token::simpleMatch(tok->astParent(), "=") && tok == tok->astParent()->astOperand2() && Token::simpleMatch(tok->astParent()->astOperand1(), "[")) { if (mSettings->standards.cpp < Standards::CPP11) // We will recommend using emplace/try_emplace instead return; const std::string f = (mSettings->standards.cpp < Standards::CPP17) ? "emplace" : "try_emplace"; replaceExpr = " Instead of '" + tok->astParent()->expressionString() + "' consider using '" + tok->astParent()->astOperand1()->astOperand1()->expressionString() + "." + f + "(" + tok->astParent()->astOperand1()->astOperand2()->expressionString() + ", " + tok->expressionString() + ");'."; } reportError( tok, Severity::performance, "stlFindInsert", "Searching before insertion is not necessary." + replaceExpr, CWE398, Certainty::normal); } /** * Is container.size() slow? */ static bool isCpp03ContainerSizeSlow(const Token *tok) { if (!tok) return false; const Variable* var = tok->variable(); return var && var->isStlType("list"); } void CheckStl::size() { if (!mSettings->severity.isEnabled(Severity::performance)) return; if (mSettings->standards.cpp >= Standards::CPP11) return; logChecker("CheckStl::size"); // performance,c++03 const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "%var% . size ( )") || Token::Match(tok, "%name% . %var% . size ( )")) { // get the variable const Token *varTok = tok; if (tok->strAt(2) != "size") varTok = varTok->tokAt(2); const Token* const end = varTok->tokAt(5); // check for comparison to zero if ((!tok->previous()->isArithmeticalOp() && Token::Match(end, "==|<=|!=|> 0")) || (end->next() && !end->next()->isArithmeticalOp() && Token::Match(tok->tokAt(-2), "0 ==|>=|!=|<"))) { if (isCpp03ContainerSizeSlow(varTok)) { sizeError(varTok); continue; } } // check for comparison to one if ((!tok->previous()->isArithmeticalOp() && Token::Match(end, ">=|< 1") && !end->tokAt(2)->isArithmeticalOp()) || (end->next() && !end->next()->isArithmeticalOp() && Token::Match(tok->tokAt(-2), "1 <=|>") && !tok->tokAt(-3)->isArithmeticalOp())) { if (isCpp03ContainerSizeSlow(varTok)) sizeError(varTok); } // check for using as boolean expression else if ((Token::Match(tok->tokAt(-2), "if|while (") && end->str() == ")") || (tok->previous()->tokType() == Token::eLogicalOp && Token::Match(end, "&&|)|,|;|%oror%"))) { if (isCpp03ContainerSizeSlow(varTok)) sizeError(varTok); } } } } } void CheckStl::sizeError(const Token *tok) { const std::string varname = tok ? tok->str() : std::string("list"); reportError(tok, Severity::performance, "stlSize", "$symbol:" + varname + "\n" "Possible inefficient checking for '$symbol' emptiness.\n" "Checking for '$symbol' emptiness might be inefficient. " "Using $symbol.empty() instead of $symbol.size() can be faster. " "$symbol.size() can take linear time but $symbol.empty() is " "guaranteed to take constant time.", CWE398, Certainty::normal); } void CheckStl::redundantCondition() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("redundantIfRemove")) return; logChecker("CheckStl::redundantCondition"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eIf) continue; const Token* tok = scope.classDef->tokAt(2); if (!Token::Match(tok, "%name% . find ( %any% ) != %name% . end|rend|cend|crend ( ) ) { %name% . remove|erase ( %any% ) ;")) continue; // Get tokens for the fields %name% and %any% const Token *var1 = tok; const Token *any1 = var1->tokAt(4); const Token *var2 = any1->tokAt(3); const Token *var3 = var2->tokAt(7); const Token *any2 = var3->tokAt(4); // Check if all the "%name%" fields are the same and if all the "%any%" are the same.. if (var1->str() == var2->str() && var2->str() == var3->str() && any1->str() == any2->str()) { redundantIfRemoveError(tok); } } } void CheckStl::redundantIfRemoveError(const Token *tok) { reportError(tok, Severity::style, "redundantIfRemove", "Redundant checking of STL container element existence before removing it.\n" "Redundant checking of STL container element existence before removing it. " "It is safe to call the remove method on a non-existing element.", CWE398, Certainty::normal); } void CheckStl::missingComparison() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckStl::missingComparison"); // warning const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eFor || !scope.classDef) continue; for (const Token *tok2 = scope.classDef->tokAt(2); tok2 != scope.bodyStart; tok2 = tok2->next()) { if (tok2->str() == ";") break; if (!Token::Match(tok2, "%var% = %name% . begin|rbegin|cbegin|crbegin ( ) ; %name% != %name% . end|rend|cend|crend ( ) ; ++| %name% ++| ) {")) continue; // same container if (tok2->strAt(2) != tok2->strAt(10)) break; const int iteratorId(tok2->varId()); // same iterator if (iteratorId == tok2->tokAt(10)->varId()) break; // increment iterator if (!Token::Match(tok2->tokAt(16), "++ %varid% )", iteratorId) && !Token::Match(tok2->tokAt(16), "%varid% ++ )", iteratorId)) { break; } const Token *incrementToken = nullptr; // Parse loop.. for (const Token *tok3 = scope.bodyStart; tok3 != scope.bodyEnd; tok3 = tok3->next()) { if (tok3->varId() == iteratorId) { if (Token::Match(tok3, "%varid% = %name% . insert ( ++| %varid% ++| ,", iteratorId)) { // skip insertion.. tok3 = tok3->linkAt(6); if (!tok3) break; } else if (Token::simpleMatch(tok3->astParent(), "++")) incrementToken = tok3; else if (Token::simpleMatch(tok3->astParent(), "+")) { if (Token::Match(tok3->astSibling(), "%num%")) { const Token* tokenGrandParent = tok3->astParent()->astParent(); if (Token::Match(tokenGrandParent, "==|!=")) break; } } else if (Token::Match(tok3->astParent(), "==|!=")) incrementToken = nullptr; } else if (tok3->str() == "break" || tok3->str() == "return") incrementToken = nullptr; } if (incrementToken) missingComparisonError(incrementToken, tok2->tokAt(16)); } } } void CheckStl::missingComparisonError(const Token *incrementToken1, const Token *incrementToken2) { std::list<const Token*> callstack = { incrementToken1,incrementToken2 }; std::ostringstream errmsg; errmsg << "Missing bounds check for extra iterator increment in loop.\n" << "The iterator incrementing is suspicious - it is incremented at line "; if (incrementToken1) errmsg << incrementToken1->linenr(); errmsg << " and then at line "; if (incrementToken2) errmsg << incrementToken2->linenr(); errmsg << ". The loop might unintentionally skip an element in the container. " << "There is no comparison between these increments to prevent that the iterator is " << "incremented beyond the end."; reportError(callstack, Severity::warning, "StlMissingComparison", errmsg.str(), CWE834, Certainty::normal); } static bool isLocal(const Token *tok) { const Variable *var = tok->variable(); return var && !var->isStatic() && var->isLocal(); } namespace { const std::set<std::string> stl_string_stream = { "istringstream", "ostringstream", "stringstream", "wstringstream" }; } void CheckStl::string_c_str() { const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const bool printPerformance = mSettings->severity.isEnabled(Severity::performance); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); logChecker("CheckStl::string_c_str"); // Find all functions that take std::string as argument struct StrArg { nonneg int n; std::string argtype; }; std::multimap<const Function*, StrArg> c_strFuncParam; if (printPerformance) { for (const Scope &scope : symbolDatabase->scopeList) { for (const Function &func : scope.functionList) { nonneg int numpar = 0; for (const Variable &var : func.argumentList) { numpar++; if ((var.isStlStringType() || var.isStlStringViewType()) && (!var.isReference() || var.isConst())) c_strFuncParam.emplace(&func, StrArg{ numpar, var.getTypeName() }); } } } } auto isString = [](const Token* str) -> bool { while (Token::Match(str, "::|.")) str = str->astOperand2(); if (Token::Match(str, "(|[") && !(str->valueType() && str->valueType()->type == ValueType::ITERATOR)) str = str->previous(); return str && ((str->variable() && str->variable()->isStlStringType()) || // variable (str->function() && isStlStringType(str->function()->retDef)) || // function returning string (str->valueType() && str->valueType()->type == ValueType::ITERATOR && isStlStringType(str->valueType()->containerTypeToken))); // iterator pointing to string }; // Try to detect common problems when using string::c_str() for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eFunction || !scope.function) continue; enum : std::uint8_t {charPtr, stdString, stdStringConstRef, Other} returnType = Other; if (Token::Match(scope.function->tokenDef->tokAt(-2), "char|wchar_t *")) returnType = charPtr; else if (Token::Match(scope.function->tokenDef->tokAt(-5), "const std :: string|wstring &")) returnType = stdStringConstRef; else if (Token::Match(scope.function->tokenDef->tokAt(-3), "std :: string|wstring !!&")) returnType = stdString; for (const Token *tok = scope.bodyStart; tok && tok != scope.bodyEnd; tok = tok->next()) { // Invalid usage.. if (Token::Match(tok, "throw %var% . c_str|data ( ) ;") && isLocal(tok->next()) && tok->next()->variable() && tok->next()->variable()->isStlStringType()) { string_c_strThrowError(tok); } else if (tok->variable() && tok->strAt(1) == "=") { if (Token::Match(tok->tokAt(2), "%var% . str ( ) . c_str|data ( ) ;")) { const Variable* var = tok->variable(); const Variable* var2 = tok->tokAt(2)->variable(); if (var->isPointer() && var2 && var2->isStlType(stl_string_stream)) string_c_strError(tok); } else if (Token::Match(tok->tokAt(2), "%name% (") && Token::Match(tok->linkAt(3), ") . c_str|data ( ) ;") && tok->tokAt(2)->function() && Token::Match(tok->tokAt(2)->function()->retDef, "std :: string|wstring %name%")) { const Variable* var = tok->variable(); if (var->isPointer()) string_c_strError(tok); } else if (printPerformance && tok->tokAt(1)->astOperand2() && Token::Match(tok->tokAt(1)->astOperand2()->tokAt(-3), "%var% . c_str|data ( ) ;")) { const Token* vartok = tok->tokAt(1)->astOperand2()->tokAt(-3); if ((tok->variable()->isStlStringType() || tok->variable()->isStlStringViewType()) && vartok->variable() && vartok->variable()->isStlStringType()) string_c_strAssignment(tok, tok->variable()->getTypeName()); } } else if (printPerformance && tok->function() && Token::Match(tok, "%name% ( !!)") && tok->str() != scope.className) { const auto range = c_strFuncParam.equal_range(tok->function()); for (std::multimap<const Function*, StrArg>::const_iterator i = range.first; i != range.second; ++i) { if (i->second.n == 0) continue; const Token* tok2 = tok->tokAt(2); int j; for (j = 0; tok2 && j < i->second.n - 1; j++) tok2 = tok2->nextArgument(); if (tok2) tok2 = tok2->nextArgument(); else break; if (!tok2 && j == i->second.n - 1) tok2 = tok->linkAt(1); else if (tok2) tok2 = tok2->previous(); else break; if (tok2 && Token::Match(tok2->tokAt(-4), ". c_str|data ( )")) { if (isString(tok2->tokAt(-4)->astOperand1())) { string_c_strParam(tok, i->second.n, i->second.argtype); } else if (Token::Match(tok2->tokAt(-9), "%name% . str ( )")) { // Check ss.str().c_str() as parameter const Variable* ssVar = tok2->tokAt(-9)->variable(); if (ssVar && ssVar->isStlType(stl_string_stream)) string_c_strParam(tok, i->second.n, i->second.argtype); } } } } else if (printPerformance && Token::Match(tok, "%var% (|{ %var% . c_str|data ( ) !!,") && tok->variable() && (tok->variable()->isStlStringType() || tok->variable()->isStlStringViewType()) && tok->tokAt(2)->variable() && tok->tokAt(2)->variable()->isStlStringType()) { string_c_strConstructor(tok, tok->variable()->getTypeName()); } else if (printPerformance && tok->next() && tok->next()->variable() && tok->next()->variable()->isStlStringType() && tok->valueType() && tok->valueType()->type == ValueType::CONTAINER && ((Token::Match(tok->previous(), "%var% + %var% . c_str|data ( )") && tok->previous()->variable() && tok->previous()->variable()->isStlStringType()) || (Token::Match(tok->tokAt(-5), "%var% . c_str|data ( ) + %var%") && tok->tokAt(-5)->variable() && tok->tokAt(-5)->variable()->isStlStringType()))) { string_c_strConcat(tok); } else if (printPerformance && Token::simpleMatch(tok, "<<") && tok->astOperand2() && Token::Match(tok->astOperand2()->astOperand1(), ". c_str|data ( )")) { const Token* str = tok->astOperand2()->astOperand1()->astOperand1(); if (isString(str)) { const Token* strm = tok; while (Token::simpleMatch(strm, "<<")) strm = strm->astOperand1(); if (strm && strm->variable() && strm->variable()->isStlType()) string_c_strStream(tok); } } // Using c_str() to get the return value is only dangerous if the function returns a char* else if ((returnType == charPtr || (printPerformance && (returnType == stdString || returnType == stdStringConstRef))) && tok->str() == "return") { bool err = false; const Token* tok2 = tok->next(); if (Token::Match(tok2, "std :: string|wstring (") && Token::Match(tok2->linkAt(3), ") . c_str|data ( ) ;")) { err = true; } else if (Token::simpleMatch(tok2, "(") && Token::Match(tok2->link(), ") . c_str|data ( ) ;")) { // Check for "+ localvar" or "+ std::string(" inside the bracket bool is_implicit_std_string = printInconclusive; const Token *search_end = tok2->link(); for (const Token *search_tok = tok2->next(); search_tok != search_end; search_tok = search_tok->next()) { if (Token::Match(search_tok, "+ %var%") && isLocal(search_tok->next()) && search_tok->next()->variable() && search_tok->next()->variable()->isStlStringType()) { is_implicit_std_string = true; break; } if (Token::Match(search_tok, "+ std :: string|wstring (")) { is_implicit_std_string = true; break; } } if (is_implicit_std_string) err = true; } bool local = false; bool ptrOrRef = false; const Variable* lastVar = nullptr; const Function* lastFunc = nullptr; bool funcStr = false; if (Token::Match(tok2, "%var% .")) { local = isLocal(tok2); bool refToNonLocal = false; if (tok2->variable() && tok2->variable()->isReference()) { const Token *refTok = tok2->variable()->nameToken(); refToNonLocal = true; // safe assumption is default to avoid FPs if (Token::Match(refTok, "%var% = %var% .|;|[")) refToNonLocal = !isLocal(refTok->tokAt(2)); } ptrOrRef = refToNonLocal || (tok2->variable() && (tok2->variable()->isPointer() || tok2->variable()->isSmartPointer())); } while (tok2) { if (Token::Match(tok2, "%var% .|::")) { if (ptrOrRef) local = false; lastVar = tok2->variable(); tok2 = tok2->tokAt(2); } else if (Token::Match(tok2, "%name% (") && Token::simpleMatch(tok2->linkAt(1), ") .")) { lastFunc = tok2->function(); local = false; funcStr = tok2->str() == "str"; tok2 = tok2->linkAt(1)->tokAt(2); } else break; } if (Token::Match(tok2, "c_str|data ( ) ;")) { if ((local || returnType != charPtr) && lastVar && lastVar->isStlStringType()) err = true; else if (funcStr && lastVar && lastVar->isStlType(stl_string_stream)) err = true; else if (lastFunc && Token::Match(lastFunc->tokenDef->tokAt(-3), "std :: string|wstring")) err = true; } if (err) { if (returnType == charPtr) string_c_strError(tok); else string_c_strReturn(tok); } } } } } void CheckStl::string_c_strThrowError(const Token* tok) { reportError(tok, Severity::error, "stlcstrthrow", "Dangerous usage of c_str(). The value returned by c_str() is invalid after throwing exception.\n" "Dangerous usage of c_str(). The string is destroyed after the c_str() call so the thrown pointer is invalid."); } void CheckStl::string_c_strError(const Token* tok) { reportError(tok, Severity::error, "stlcstr", "Dangerous usage of c_str(). The value returned by c_str() is invalid after this call.\n" "Dangerous usage of c_str(). The c_str() return value is only valid until its string is deleted.", CWE664, Certainty::normal); } void CheckStl::string_c_strReturn(const Token* tok) { reportError(tok, Severity::performance, "stlcstrReturn", "Returning the result of c_str() in a function that returns std::string is slow and redundant.\n" "The conversion from const char* as returned by c_str() to std::string creates an unnecessary string copy. Solve that by directly returning the string.", CWE704, Certainty::normal); } void CheckStl::string_c_strParam(const Token* tok, nonneg int number, const std::string& argtype) { std::ostringstream oss; oss << "Passing the result of c_str() to a function that takes " << argtype << " as argument no. " << number << " is slow and redundant.\n" "The conversion from const char* as returned by c_str() to " << argtype << " creates an unnecessary string copy or length calculation. Solve that by directly passing the string."; reportError(tok, Severity::performance, "stlcstrParam", oss.str(), CWE704, Certainty::normal); } void CheckStl::string_c_strConstructor(const Token* tok, const std::string& argtype) { std::string msg = "Constructing a " + argtype + " from the result of c_str() is slow and redundant.\n" "Constructing a " + argtype + " from const char* requires a call to strlen(). Solve that by directly passing the string."; reportError(tok, Severity::performance, "stlcstrConstructor", msg, CWE704, Certainty::normal); } void CheckStl::string_c_strAssignment(const Token* tok, const std::string& argtype) { std::string msg = "Assigning the result of c_str() to a " + argtype + " is slow and redundant.\n" "Assigning a const char* to a " + argtype + " requires a call to strlen(). Solve that by directly assigning the string."; reportError(tok, Severity::performance, "stlcstrAssignment", msg, CWE704, Certainty::normal); } void CheckStl::string_c_strConcat(const Token* tok) { std::string msg = "Concatenating the result of c_str() and a std::string is slow and redundant.\n" "Concatenating a const char* with a std::string requires a call to strlen(). Solve that by directly concatenating the strings."; reportError(tok, Severity::performance, "stlcstrConcat", msg, CWE704, Certainty::normal); } void CheckStl::string_c_strStream(const Token* tok) { std::string msg = "Passing the result of c_str() to a stream is slow and redundant.\n" "Passing a const char* to a stream requires a call to strlen(). Solve that by directly passing the string."; reportError(tok, Severity::performance, "stlcstrStream", msg, CWE704, Certainty::normal); } //--------------------------------------------------------------------------- // //--------------------------------------------------------------------------- namespace { const std::set<std::string> stl_containers_with_empty_and_clear = { "deque", "forward_list", "list", "map", "multimap", "multiset", "set", "string", "unordered_map", "unordered_multimap", "unordered_multiset", "unordered_set", "vector", "wstring" }; } void CheckStl::uselessCalls() { const bool printPerformance = mSettings->severity.isEnabled(Severity::performance); const bool printWarning = mSettings->severity.isEnabled(Severity::warning); if (!printPerformance && !printWarning) return; logChecker("CheckStl::uselessCalls"); // performance,warning const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (printWarning && Token::Match(tok, "%var% . compare|find|rfind|find_first_not_of|find_first_of|find_last_not_of|find_last_of ( %name% [,)]") && tok->varId() == tok->tokAt(4)->varId()) { const Variable* var = tok->variable(); if (!var || !var->isStlType()) continue; uselessCallsReturnValueError(tok->tokAt(4), tok->str(), tok->strAt(2)); } else if (printPerformance && Token::Match(tok, "%var% . swap ( %name% )") && tok->varId() == tok->tokAt(4)->varId()) { const Variable* var = tok->variable(); if (!var || !var->isStlType()) continue; uselessCallsSwapError(tok, tok->str()); } else if (printPerformance && Token::Match(tok, "%var% . substr (") && tok->variable() && tok->variable()->isStlStringType()) { const Token* funcTok = tok->tokAt(3); const std::vector<const Token*> args = getArguments(funcTok); if (Token::Match(tok->tokAt(-2), "%var% =") && tok->varId() == tok->tokAt(-2)->varId() && !args.empty() && args[0]->hasKnownIntValue() && args[0]->getKnownIntValue() == 0) { uselessCallsSubstrError(tok, Token::simpleMatch(funcTok->astParent(), "=") ? SubstrErrorType::PREFIX : SubstrErrorType::PREFIX_CONCAT); } else if (args.empty() || (args[0]->hasKnownIntValue() && args[0]->getKnownIntValue() == 0 && (args.size() == 1 || (args.size() == 2 && tok->linkAt(3)->strAt(-1) == "npos" && !tok->linkAt(3)->previous()->variable())))) { uselessCallsSubstrError(tok, SubstrErrorType::COPY); } else if (args.size() == 2 && args[1]->hasKnownIntValue() && args[1]->getKnownIntValue() == 0) { uselessCallsSubstrError(tok, SubstrErrorType::EMPTY); } } else if (printWarning && Token::Match(tok, "[{};] %var% . empty ( ) ;") && !tok->tokAt(4)->astParent() && tok->next()->variable() && tok->next()->variable()->isStlType(stl_containers_with_empty_and_clear)) uselessCallsEmptyError(tok->next()); else if (Token::Match(tok, "[{};] std :: remove|remove_if|unique (") && tok->tokAt(5)->nextArgument()) uselessCallsRemoveError(tok->next(), tok->strAt(3)); else if (printPerformance && tok->valueType() && tok->valueType()->type == ValueType::CONTAINER) { if (Token::Match(tok, "%var% = { %var% . begin ( ) ,") && tok->varId() == tok->tokAt(3)->varId()) uselessCallsConstructorError(tok); else if (const Variable* var = tok->variable()) { std::string pattern = "%var% = "; for (const Token* t = var->typeStartToken(); t != var->typeEndToken()->next(); t = t->next()) { pattern += t->str(); pattern += ' '; } pattern += "{|( %varid% . begin ( ) ,"; if (Token::Match(tok, pattern.c_str(), tok->varId())) uselessCallsConstructorError(tok); } } } } } void CheckStl::uselessCallsReturnValueError(const Token *tok, const std::string &varname, const std::string &function) { std::ostringstream errmsg; errmsg << "$symbol:" << varname << '\n'; errmsg << "$symbol:" << function << '\n'; errmsg << "It is inefficient to call '" << varname << "." << function << "(" << varname << ")' as it always returns 0.\n" << "'std::string::" << function << "()' returns zero when given itself as parameter " << "(" << varname << "." << function << "(" << varname << ")). As it is currently the " << "code is inefficient. It is possible either the string searched ('" << varname << "') or searched for ('" << varname << "') is wrong."; reportError(tok, Severity::warning, "uselessCallsCompare", errmsg.str(), CWE628, Certainty::normal); } void CheckStl::uselessCallsSwapError(const Token *tok, const std::string &varname) { reportError(tok, Severity::performance, "uselessCallsSwap", "$symbol:" + varname + "\n" "It is inefficient to swap a object with itself by calling '$symbol.swap($symbol)'\n" "The 'swap()' function has no logical effect when given itself as parameter " "($symbol.swap($symbol)). As it is currently the " "code is inefficient. Is the object or the parameter wrong here?", CWE628, Certainty::normal); } void CheckStl::uselessCallsSubstrError(const Token *tok, SubstrErrorType type) { std::string msg = "Ineffective call of function 'substr' because "; switch (type) { case SubstrErrorType::EMPTY: msg += "it returns an empty string."; break; case SubstrErrorType::COPY: msg += "it returns a copy of the object. Use operator= instead."; break; case SubstrErrorType::PREFIX: msg += "a prefix of the string is assigned to itself. Use resize() or pop_back() instead."; break; case SubstrErrorType::PREFIX_CONCAT: msg += "a prefix of the string is assigned to itself. Use replace() instead."; break; } reportError(tok, Severity::performance, "uselessCallsSubstr", msg, CWE398, Certainty::normal); } void CheckStl::uselessCallsConstructorError(const Token *tok) { const std::string msg = "Inefficient constructor call: container '" + tok->str() + "' is assigned a partial copy of itself. Use erase() or resize() instead."; reportError(tok, Severity::performance, "uselessCallsConstructor", msg, CWE398, Certainty::normal); } void CheckStl::uselessCallsEmptyError(const Token *tok) { reportError(tok, Severity::warning, "uselessCallsEmpty", "Ineffective call of function 'empty()'. Did you intend to call 'clear()' instead?", CWE398, Certainty::normal); } void CheckStl::uselessCallsRemoveError(const Token *tok, const std::string& function) { reportError(tok, Severity::warning, "uselessCallsRemove", "$symbol:" + function + "\n" "Return value of std::$symbol() ignored. Elements remain in container.\n" "The return value of std::$symbol() is ignored. This function returns an iterator to the end of the range containing those elements that should be kept. " "Elements past new end remain valid but with unspecified values. Use the erase method of the container to delete them.", CWE762, Certainty::normal); } // Check for iterators being dereferenced before being checked for validity. // E.g. if (*i && i != str.end()) { } void CheckStl::checkDereferenceInvalidIterator() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckStl::checkDereferenceInvalidIterator"); // warning // Iterate over "if", "while", and "for" conditions where there may // be an iterator that is dereferenced before being checked for validity. for (const Scope &scope : mTokenizer->getSymbolDatabase()->scopeList) { if (!(scope.type == Scope::eIf || scope.isLoopScope())) continue; const Token* const tok = scope.classDef; const Token* startOfCondition = tok->next(); if (scope.type == Scope::eDo) startOfCondition = startOfCondition->link()->tokAt(2); if (!startOfCondition) // ticket #6626 invalid code continue; const Token* endOfCondition = startOfCondition->link(); if (!endOfCondition) continue; // For "for" loops, only search between the two semicolons if (scope.type == Scope::eFor) { startOfCondition = Token::findsimplematch(tok->tokAt(2), ";", endOfCondition); if (!startOfCondition) continue; endOfCondition = Token::findsimplematch(startOfCondition->next(), ";", endOfCondition); if (!endOfCondition) continue; } // Only consider conditions composed of all "&&" terms and // conditions composed of all "||" terms const bool isOrExpression = Token::findsimplematch(startOfCondition, "||", endOfCondition) != nullptr; const bool isAndExpression = Token::findsimplematch(startOfCondition, "&&", endOfCondition) != nullptr; // Look for a check of the validity of an iterator const Token* validityCheckTok = nullptr; if (!isOrExpression && isAndExpression) { validityCheckTok = Token::findmatch(startOfCondition, "&& %var% != %name% . end|rend|cend|crend ( )", endOfCondition); } else if (isOrExpression && !isAndExpression) { validityCheckTok = Token::findmatch(startOfCondition, "%oror% %var% == %name% . end|rend|cend|crend ( )", endOfCondition); } if (!validityCheckTok) continue; const int iteratorVarId = validityCheckTok->next()->varId(); // If the iterator dereference is to the left of the check for // the iterator's validity, report an error. const Token* const dereferenceTok = Token::findmatch(startOfCondition, "* %varid%", validityCheckTok, iteratorVarId); if (dereferenceTok) dereferenceInvalidIteratorError(dereferenceTok, dereferenceTok->strAt(1)); } } void CheckStl::checkDereferenceInvalidIterator2() { const bool printInconclusive = (mSettings->certainty.isEnabled(Certainty::inconclusive)); logChecker("CheckStl::checkDereferenceInvalidIterator2"); for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "sizeof|decltype|typeid|typeof (")) { tok = tok->linkAt(1); continue; } if (Token::Match(tok, "%assign%")) continue; std::vector<ValueFlow::Value> contValues; std::copy_if(tok->values().cbegin(), tok->values().cend(), std::back_inserter(contValues), [&](const ValueFlow::Value& value) { if (value.isImpossible()) return false; if (!printInconclusive && value.isInconclusive()) return false; return value.isContainerSizeValue(); }); // Can iterator point to END or before START? for (const ValueFlow::Value& value:tok->values()) { if (value.isImpossible()) continue; if (!printInconclusive && value.isInconclusive()) continue; if (!value.isIteratorValue()) continue; bool isInvalidIterator = false; const ValueFlow::Value* cValue = nullptr; if (value.isIteratorEndValue() && value.intvalue >= 0) { isInvalidIterator = value.intvalue > 0; } else if (value.isIteratorStartValue() && value.intvalue < 0) { isInvalidIterator = true; } else { auto it = std::find_if(contValues.cbegin(), contValues.cend(), [&](const ValueFlow::Value& c) { if (value.path != c.path) return false; if (value.isIteratorStartValue() && value.intvalue >= c.intvalue) return true; if (value.isIteratorEndValue() && -value.intvalue > c.intvalue) return true; return false; }); if (it == contValues.end()) continue; cValue = &*it; if (value.isIteratorStartValue() && value.intvalue > cValue->intvalue) isInvalidIterator = true; } bool inconclusive = false; bool unknown = false; const Token* emptyAdvance = nullptr; const Token* advanceIndex = nullptr; if (cValue && cValue->intvalue == 0) { if (Token::Match(tok->astParent(), "+|-") && astIsIntegral(tok->astSibling(), false)) { if (tok->astSibling() && tok->astSibling()->hasKnownIntValue()) { if (tok->astSibling()->values().front().intvalue == 0) continue; } else { advanceIndex = tok->astSibling(); } emptyAdvance = tok->astParent(); } else if (Token::Match(tok->astParent(), "++|--")) { emptyAdvance = tok->astParent(); } } if (!CheckNullPointer::isPointerDeRef(tok, unknown, *mSettings) && !isInvalidIterator && !emptyAdvance) { if (!unknown) continue; inconclusive = true; } if (cValue) { const ValueFlow::Value& lValue = getLifetimeIteratorValue(tok, cValue->path); if (!lValue.isLifetimeValue()) continue; if (emptyAdvance) outOfBoundsError(emptyAdvance, lValue.tokvalue->expressionString(), cValue, advanceIndex ? advanceIndex->expressionString() : emptyString, nullptr); else outOfBoundsError(tok, lValue.tokvalue->expressionString(), cValue, tok->expressionString(), &value); } else { dereferenceInvalidIteratorError(tok, &value, inconclusive); } } } } void CheckStl::dereferenceInvalidIteratorError(const Token* tok, const ValueFlow::Value *value, bool inconclusive) { const std::string& varname = tok ? tok->expressionString() : "var"; const std::string errmsgcond("$symbol:" + varname + '\n' + ValueFlow::eitherTheConditionIsRedundant(value ? value->condition : nullptr) + " or there is possible dereference of an invalid iterator: $symbol."); if (!tok || !value) { reportError(tok, Severity::error, "derefInvalidIterator", "Dereference of an invalid iterator", CWE825, Certainty::normal); reportError(tok, Severity::warning, "derefInvalidIteratorRedundantCheck", errmsgcond, CWE825, Certainty::normal); return; } if (!mSettings->isEnabled(value, inconclusive)) return; const ErrorPath errorPath = getErrorPath(tok, value, "Dereference of an invalid iterator"); if (value->condition) { reportError(errorPath, Severity::warning, "derefInvalidIteratorRedundantCheck", errmsgcond, CWE825, (inconclusive || value->isInconclusive()) ? Certainty::inconclusive : Certainty::normal); } else { std::string errmsg = std::string(value->isKnown() ? "Dereference" : "Possible dereference") + " of an invalid iterator"; if (!varname.empty()) errmsg = "$symbol:" + varname + '\n' + errmsg + ": $symbol"; reportError(errorPath, value->isKnown() ? Severity::error : Severity::warning, "derefInvalidIterator", errmsg, CWE825, (inconclusive || value->isInconclusive()) ? Certainty::inconclusive : Certainty::normal); } } void CheckStl::dereferenceInvalidIteratorError(const Token* deref, const std::string &iterName) { reportError(deref, Severity::warning, "derefInvalidIterator", "$symbol:" + iterName + "\n" "Possible dereference of an invalid iterator: $symbol\n" "Possible dereference of an invalid iterator: $symbol. Make sure to check that the iterator is valid before dereferencing it - not after.", CWE825, Certainty::normal); } void CheckStl::useStlAlgorithmError(const Token *tok, const std::string &algoName) { reportError(tok, Severity::style, "useStlAlgorithm", "Consider using " + algoName + " algorithm instead of a raw loop.", CWE398, Certainty::normal); } static bool isEarlyExit(const Token *start) { if (start->str() != "{") return false; const Token *endToken = start->link(); const Token *tok = Token::findmatch(start, "return|throw|break", endToken); if (!tok) return false; const Token *endStatement = Token::findsimplematch(tok, "; }", endToken); if (!endStatement) return false; if (endStatement->next() != endToken) return false; return true; } static const Token *singleStatement(const Token *start) { if (start->str() != "{") return nullptr; const Token *endToken = start->link(); const Token *endStatement = Token::findsimplematch(start->next(), ";"); if (!Token::simpleMatch(endStatement, "; }")) return nullptr; if (endStatement->next() != endToken) return nullptr; return endStatement; } static const Token *singleAssignInScope(const Token *start, nonneg int varid, bool &input, bool &hasBreak, const Settings& settings) { const Token *endStatement = singleStatement(start); if (!endStatement) return nullptr; if (!Token::Match(start->next(), "%var% %assign%")) return nullptr; const Token *assignTok = start->tokAt(2); if (isVariableChanged(assignTok->next(), endStatement, assignTok->astOperand1()->varId(), /*globalvar*/ false, settings)) return nullptr; if (isVariableChanged(assignTok->next(), endStatement, varid, /*globalvar*/ false, settings)) return nullptr; input = Token::findmatch(assignTok->next(), "%varid%", endStatement, varid) || !Token::Match(start->next(), "%var% ="); hasBreak = Token::simpleMatch(endStatement->previous(), "break"); return assignTok; } static const Token *singleMemberCallInScope(const Token *start, nonneg int varid, bool &input, const Settings& settings) { if (start->str() != "{") return nullptr; const Token *endToken = start->link(); if (!Token::Match(start->next(), "%var% . %name% (")) return nullptr; if (!Token::simpleMatch(start->linkAt(4), ") ; }")) return nullptr; const Token *endStatement = start->linkAt(4)->next(); if (endStatement->next() != endToken) return nullptr; const Token *dotTok = start->tokAt(2); if (!Token::findmatch(dotTok->tokAt(2), "%varid%", endStatement, varid)) return nullptr; input = Token::Match(start->next(), "%var% . %name% ( %varid% )", varid); if (isVariableChanged(dotTok->next(), endStatement, dotTok->astOperand1()->varId(), /*globalvar*/ false, settings)) return nullptr; return dotTok; } static const Token *singleIncrementInScope(const Token *start, nonneg int varid, bool &input) { if (start->str() != "{") return nullptr; const Token *varTok = nullptr; if (Token::Match(start->next(), "++ %var% ; }")) varTok = start->tokAt(2); else if (Token::Match(start->next(), "%var% ++ ; }")) varTok = start->tokAt(1); if (!varTok) return nullptr; input = varTok->varId() == varid; return varTok; } static const Token *singleConditionalInScope(const Token *start, nonneg int varid, const Settings& settings) { if (start->str() != "{") return nullptr; const Token *endToken = start->link(); if (!Token::simpleMatch(start->next(), "if (")) return nullptr; if (!Token::simpleMatch(start->linkAt(2), ") {")) return nullptr; const Token *bodyTok = start->linkAt(2)->next(); const Token *endBodyTok = bodyTok->link(); if (!Token::simpleMatch(endBodyTok, "} }")) return nullptr; if (endBodyTok->next() != endToken) return nullptr; if (!Token::findmatch(start, "%varid%", bodyTok, varid)) return nullptr; if (isVariableChanged(start, bodyTok, varid, /*globalvar*/ false, settings)) return nullptr; return bodyTok; } static bool addByOne(const Token *tok, nonneg int varid) { if (Token::Match(tok, "+= %any% ;") && tok->tokAt(1)->hasKnownIntValue() && tok->tokAt(1)->getValue(1)) { return true; } if (Token::Match(tok, "= %varid% + %any% ;", varid) && tok->tokAt(3)->hasKnownIntValue() && tok->tokAt(3)->getValue(1)) { return true; } return false; } static bool accumulateBoolLiteral(const Token *tok, nonneg int varid) { if (Token::Match(tok, "%assign% %bool% ;") && tok->tokAt(1)->hasKnownIntValue()) { return true; } if (Token::Match(tok, "= %varid% %oror%|%or%|&&|& %bool% ;", varid) && tok->tokAt(3)->hasKnownIntValue()) { return true; } return false; } static bool accumulateBool(const Token *tok, nonneg int varid) { // Missing %oreq% so we have to check both manually if (Token::simpleMatch(tok, "&=") || Token::simpleMatch(tok, "|=")) { return true; } if (Token::Match(tok, "= %varid% %oror%|%or%|&&|&", varid)) { return true; } return false; } static bool hasVarIds(const Token *tok, nonneg int var1, nonneg int var2) { if (tok->astOperand1()->varId() == tok->astOperand2()->varId()) return false; if (tok->astOperand1()->varId() == var1 || tok->astOperand1()->varId() == var2) { if (tok->astOperand2()->varId() == var1 || tok->astOperand2()->varId() == var2) { return true; } } return false; } static std::string flipMinMax(const std::string &algo) { if (algo == "std::max_element") return "std::min_element"; if (algo == "std::min_element") return "std::max_element"; return algo; } static std::string minmaxCompare(const Token *condTok, nonneg int loopVar, nonneg int assignVar, bool invert = false) { if (!Token::Match(condTok, "<|<=|>=|>")) return "std::accumulate"; if (!hasVarIds(condTok, loopVar, assignVar)) return "std::accumulate"; std::string algo = "std::max_element"; if (Token::Match(condTok, "<|<=")) algo = "std::min_element"; if (condTok->astOperand1()->varId() == assignVar) algo = flipMinMax(algo); if (invert) algo = flipMinMax(algo); return algo; } namespace { struct LoopAnalyzer { const Token* bodyTok = nullptr; const Token* loopVar = nullptr; const Settings* settings = nullptr; std::set<nonneg int> varsChanged; explicit LoopAnalyzer(const Token* tok, const Settings* psettings) : bodyTok(tok->linkAt(1)->next()), settings(psettings) { const Token* splitTok = tok->next()->astOperand2(); if (Token::simpleMatch(splitTok, ":") && splitTok->previous()->varId() != 0) { loopVar = splitTok->previous(); } if (valid()) { findChangedVariables(); } } bool isLoopVarChanged() const { return varsChanged.count(loopVar->varId()) > 0; } bool isModified(const Token* tok) const { if (tok->variable() && tok->variable()->isConst()) return false; int n = 1 + (astIsPointer(tok) ? 1 : 0); for (int i = 0; i < n; i++) { bool inconclusive = false; if (isVariableChangedByFunctionCall(tok, i, *settings, &inconclusive)) return true; if (inconclusive) return true; if (isVariableChanged(tok, i, *settings)) return true; } return false; } template<class Predicate, class F> void findTokens(Predicate pred, F f) const { for (const Token* tok = bodyTok; precedes(tok, bodyTok->link()); tok = tok->next()) { if (pred(tok)) f(tok); } } template<class Predicate> const Token* findToken(Predicate pred) const { for (const Token* tok = bodyTok; precedes(tok, bodyTok->link()); tok = tok->next()) { if (pred(tok)) return tok; } return nullptr; } bool hasGotoOrBreak() const { return findToken([](const Token* tok) { return Token::Match(tok, "goto|break"); }); } bool valid() const { return bodyTok && loopVar; } std::string findAlgo() const { if (!valid()) return ""; bool loopVarChanged = isLoopVarChanged(); if (!loopVarChanged && varsChanged.empty()) { if (hasGotoOrBreak()) return ""; bool alwaysTrue = true; bool alwaysFalse = true; auto hasReturn = [](const Token* tok) { return Token::simpleMatch(tok, "return"); }; findTokens(hasReturn, [&](const Token* tok) { const Token* returnTok = tok->astOperand1(); if (!returnTok || !returnTok->hasKnownIntValue() || !astIsBool(returnTok)) { alwaysTrue = false; alwaysFalse = false; return; } (returnTok->values().front().intvalue ? alwaysTrue : alwaysFalse) &= true; (returnTok->values().front().intvalue ? alwaysFalse : alwaysTrue) &= false; }); if (alwaysTrue == alwaysFalse) return ""; if (alwaysTrue) return "std::any_of"; return "std::all_of or std::none_of"; } return ""; } bool isLocalVar(const Variable* var) const { if (!var) return false; if (var->isPointer() || var->isReference()) return false; if (var->declarationId() == loopVar->varId()) return false; const Scope* scope = var->scope(); return scope && scope->isNestedIn(bodyTok->scope()); } private: void findChangedVariables() { std::set<nonneg int> vars; for (const Token* tok = bodyTok; precedes(tok, bodyTok->link()); tok = tok->next()) { if (tok->varId() == 0) continue; if (vars.count(tok->varId()) > 0) continue; if (isLocalVar(tok->variable())) { vars.insert(tok->varId()); continue; } if (!isModified(tok)) continue; varsChanged.insert(tok->varId()); vars.insert(tok->varId()); } } }; } // namespace void CheckStl::useStlAlgorithm() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("useStlAlgorithm")) return; logChecker("CheckStl::useStlAlgorithm"); // style auto checkAssignee = [](const Token* tok) { if (astIsBool(tok)) // std::accumulate is not a good fit for bool values, std::all/any/none_of return early return false; return !astIsContainer(tok); // don't warn for containers, where overloaded operators can be costly }; auto isConditionWithoutSideEffects = [this](const Token* tok) -> bool { if (!Token::simpleMatch(tok, "{") || !Token::simpleMatch(tok->previous(), ")")) return false; return isConstExpression(tok->linkAt(-1)->astOperand2(), mSettings->library); }; for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) { for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) { // Parse range-based for loop if (!Token::simpleMatch(tok, "for (")) continue; if (!Token::simpleMatch(tok->linkAt(1), ") {")) continue; LoopAnalyzer a{tok, mSettings}; std::string algoName = a.findAlgo(); if (!algoName.empty()) { useStlAlgorithmError(tok, algoName); continue; } const Token *bodyTok = tok->linkAt(1)->next(); const Token *splitTok = tok->next()->astOperand2(); const Token* loopVar{}; bool isIteratorLoop = false; if (Token::simpleMatch(splitTok, ":")) { loopVar = splitTok->previous(); if (loopVar->varId() == 0) continue; if (Token::simpleMatch(splitTok->astOperand2(), "{")) continue; } else { // iterator-based loop? const Token* initTok = getInitTok(tok); const Token* condTok = getCondTok(tok); const Token* stepTok = getStepTok(tok); if (!initTok || !condTok || !stepTok) continue; loopVar = Token::Match(condTok, "%comp%") ? condTok->astOperand1() : nullptr; if (!Token::Match(loopVar, "%var%") || !loopVar->valueType() || loopVar->valueType()->type != ValueType::Type::ITERATOR) continue; if (!Token::simpleMatch(initTok, "=") || !Token::Match(initTok->astOperand1(), "%varid%", loopVar->varId())) continue; if (!stepTok->isIncDecOp()) continue; isIteratorLoop = true; } // Check for single assignment bool useLoopVarInAssign{}, hasBreak{}; const Token *assignTok = singleAssignInScope(bodyTok, loopVar->varId(), useLoopVarInAssign, hasBreak, *mSettings); if (assignTok) { if (!checkAssignee(assignTok->astOperand1())) continue; const int assignVarId = assignTok->astOperand1()->varId(); std::string algo; if (assignVarId == loopVar->varId()) { if (useLoopVarInAssign) algo = "std::transform"; else if (Token::Match(assignTok->next(), "%var%|%bool%|%num%|%char% ;")) algo = "std::fill"; else if (Token::Match(assignTok->next(), "%name% ( )")) algo = "std::generate"; else algo = "std::fill or std::generate"; } else { if (addByOne(assignTok, assignVarId)) algo = "std::distance"; else if (accumulateBool(assignTok, assignVarId)) algo = "std::any_of, std::all_of, std::none_of, or std::accumulate"; else if (Token::Match(assignTok, "= %var% <|<=|>=|> %var% ? %var% : %var%") && hasVarIds(assignTok->tokAt(6), loopVar->varId(), assignVarId)) algo = minmaxCompare(assignTok->tokAt(2), loopVar->varId(), assignVarId, assignTok->tokAt(5)->varId() == assignVarId); else algo = "std::accumulate"; } useStlAlgorithmError(assignTok, algo); continue; } // Check for container calls bool useLoopVarInMemCall; const Token *memberAccessTok = singleMemberCallInScope(bodyTok, loopVar->varId(), useLoopVarInMemCall, *mSettings); if (memberAccessTok && !isIteratorLoop) { const Token *memberCallTok = memberAccessTok->astOperand2(); const int contVarId = memberAccessTok->astOperand1()->varId(); if (contVarId == loopVar->varId()) continue; if (memberCallTok->str() == "push_back" || memberCallTok->str() == "push_front" || memberCallTok->str() == "emplace_back") { std::string algo; if (useLoopVarInMemCall) algo = "std::copy"; else algo = "std::transform"; useStlAlgorithmError(memberCallTok, algo); } continue; } // Check for increment in loop bool useLoopVarInIncrement; const Token *incrementTok = singleIncrementInScope(bodyTok, loopVar->varId(), useLoopVarInIncrement); if (incrementTok) { std::string algo; if (useLoopVarInIncrement) algo = "std::transform"; else algo = "std::distance"; useStlAlgorithmError(incrementTok, algo); continue; } // Check for conditionals const Token *condBodyTok = singleConditionalInScope(bodyTok, loopVar->varId(), *mSettings); if (condBodyTok) { // Check for single assign assignTok = singleAssignInScope(condBodyTok, loopVar->varId(), useLoopVarInAssign, hasBreak, *mSettings); if (assignTok) { if (!checkAssignee(assignTok->astOperand1())) continue; const int assignVarId = assignTok->astOperand1()->varId(); std::string algo; if (assignVarId == loopVar->varId()) { if (useLoopVarInAssign) algo = "std::transform"; else algo = "std::replace_if"; } else { if (addByOne(assignTok, assignVarId)) algo = "std::count_if"; else if (accumulateBoolLiteral(assignTok, assignVarId)) algo = "std::any_of, std::all_of, std::none_of, or std::accumulate"; else if (assignTok->str() != "=") algo = "std::accumulate"; else if (hasBreak && isConditionWithoutSideEffects(condBodyTok)) algo = "std::any_of, std::all_of, std::none_of"; else continue; } useStlAlgorithmError(assignTok, algo); continue; } // Check for container call memberAccessTok = singleMemberCallInScope(condBodyTok, loopVar->varId(), useLoopVarInMemCall, *mSettings); if (memberAccessTok) { const Token *memberCallTok = memberAccessTok->astOperand2(); const int contVarId = memberAccessTok->astOperand1()->varId(); if (contVarId == loopVar->varId()) continue; if (memberCallTok->str() == "push_back" || memberCallTok->str() == "push_front" || memberCallTok->str() == "emplace_back") { if (useLoopVarInMemCall) useStlAlgorithmError(memberAccessTok, "std::copy_if"); // There is no transform_if to suggest } continue; } // Check for increment in loop incrementTok = singleIncrementInScope(condBodyTok, loopVar->varId(), useLoopVarInIncrement); if (incrementTok) { std::string algo; if (useLoopVarInIncrement) algo = "std::transform"; else algo = "std::count_if"; useStlAlgorithmError(incrementTok, algo); continue; } // Check early return if (isEarlyExit(condBodyTok)) { const Token *loopVar2 = Token::findmatch(condBodyTok, "%varid%", condBodyTok->link(), loopVar->varId()); std::string algo; if (loopVar2 || (isIteratorLoop && loopVar->variable() && precedes(loopVar->variable()->nameToken(), tok))) // iterator declared outside the loop algo = "std::find_if"; else algo = "std::any_of"; useStlAlgorithmError(condBodyTok, algo); continue; } } } } } void CheckStl::knownEmptyContainerError(const Token *tok, const std::string& algo) { const std::string var = tok ? tok->expressionString() : std::string("var"); std::string msg; if (astIsIterator(tok)) { msg = "Using " + algo + " with iterator '" + var + "' that is always empty."; } else { msg = "Iterating over container '" + var + "' that is always empty."; } reportError(tok, Severity::style, "knownEmptyContainer", msg, CWE398, Certainty::normal); } static bool isKnownEmptyContainer(const Token* tok) { if (!tok) return false; return std::any_of(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& v) { if (!v.isKnown()) return false; if (!v.isContainerSizeValue()) return false; if (v.intvalue != 0) return false; return true; }); } void CheckStl::knownEmptyContainer() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("knownEmptyContainer")) return; logChecker("CheckStl::knownEmptyContainer"); // style for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) { for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "%name% ( !!)")) continue; // Parse range-based for loop if (tok->str() == "for") { if (!Token::simpleMatch(tok->linkAt(1), ") {")) continue; const Token *splitTok = tok->next()->astOperand2(); if (!Token::simpleMatch(splitTok, ":")) continue; const Token* contTok = splitTok->astOperand2(); if (!isKnownEmptyContainer(contTok)) continue; knownEmptyContainerError(contTok, emptyString); } else { const std::vector<const Token *> args = getArguments(tok); if (args.empty()) continue; for (int argnr = 1; argnr <= args.size(); ++argnr) { const Library::ArgumentChecks::IteratorInfo *i = mSettings->library.getArgIteratorInfo(tok, argnr); if (!i) continue; const Token * const argTok = args[argnr - 1]; if (!isKnownEmptyContainer(argTok)) continue; knownEmptyContainerError(argTok, tok->str()); break; } } } } } void CheckStl::eraseIteratorOutOfBoundsError(const Token *ftok, const Token* itertok, const ValueFlow::Value* val) { if (!ftok || !itertok || !val) { reportError(ftok, Severity::error, "eraseIteratorOutOfBounds", "Calling function 'erase()' on the iterator 'iter' which is out of bounds.", CWE628, Certainty::normal); reportError(ftok, Severity::warning, "eraseIteratorOutOfBoundsCond", "Either the condition 'x' is redundant or function 'erase()' is called on the iterator 'iter' which is out of bounds.", CWE628, Certainty::normal); return; } const std::string& func = ftok->str(); const std::string iter = itertok->expressionString(); const bool isConditional = val->isPossible(); std::string msg; if (isConditional) { msg = ValueFlow::eitherTheConditionIsRedundant(val->condition) + " or function '" + func + "()' is called on the iterator '" + iter + "' which is out of bounds."; } else { msg = "Calling function '" + func + "()' on the iterator '" + iter + "' which is out of bounds."; } const Severity severity = isConditional ? Severity::warning : Severity::error; const std::string id = isConditional ? "eraseIteratorOutOfBoundsCond" : "eraseIteratorOutOfBounds"; reportError(ftok, severity, id, msg, CWE628, Certainty::normal); } static const ValueFlow::Value* getOOBIterValue(const Token* tok, const ValueFlow::Value* sizeVal) { auto it = std::find_if(tok->values().begin(), tok->values().end(), [&](const ValueFlow::Value& v) { if (v.isPossible() || v.isKnown()) { switch (v.valueType) { case ValueFlow::Value::ValueType::ITERATOR_END: return v.intvalue >= 0; case ValueFlow::Value::ValueType::ITERATOR_START: return (v.intvalue < 0) || (sizeVal && v.intvalue >= sizeVal->intvalue); default: break; } } return false; }); return it != tok->values().end() ? &*it : nullptr; } void CheckStl::eraseIteratorOutOfBounds() { logChecker("CheckStl::eraseIteratorOutOfBounds"); for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) { for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) { if (!tok->valueType()) continue; const Library::Container* container = tok->valueType()->container; if (!container || !astIsLHS(tok) || !Token::simpleMatch(tok->astParent(), ".")) continue; const Token* const ftok = tok->astParent()->astOperand2(); const Library::Container::Action action = container->getAction(ftok->str()); if (action != Library::Container::Action::ERASE) continue; const std::vector<const Token*> args = getArguments(ftok); if (args.size() != 1) // TODO: check range overload continue; const ValueFlow::Value* sizeVal = tok->getKnownValue(ValueFlow::Value::ValueType::CONTAINER_SIZE); if (const ValueFlow::Value* errVal = getOOBIterValue(args[0], sizeVal)) eraseIteratorOutOfBoundsError(ftok, args[0], errVal); } } } static bool isMutex(const Variable* var) { const Token* tok = Token::typeDecl(var->nameToken()).first; return Token::Match(tok, "std :: mutex|recursive_mutex|timed_mutex|recursive_timed_mutex|shared_mutex"); } static bool isLockGuard(const Variable* var) { const Token* tok = Token::typeDecl(var->nameToken()).first; return Token::Match(tok, "std :: lock_guard|unique_lock|scoped_lock|shared_lock"); } static bool isLocalMutex(const Variable* var, const Scope* scope) { if (!var) return false; if (isLockGuard(var)) return false; return !var->isReference() && !var->isRValueReference() && !var->isStatic() && var->scope() == scope; } void CheckStl::globalLockGuardError(const Token* tok) { reportError(tok, Severity::warning, "globalLockGuard", "Lock guard is defined globally. Lock guards are intended to be local. A global lock guard could lead to a deadlock since it won't unlock until the end of the program.", CWE833, Certainty::normal); } void CheckStl::localMutexError(const Token* tok) { reportError(tok, Severity::warning, "localMutex", "The lock is ineffective because the mutex is locked at the same scope as the mutex itself.", CWE667, Certainty::normal); } void CheckStl::checkMutexes() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckStl::checkMutexes"); // warning for (const Scope *function : mTokenizer->getSymbolDatabase()->functionScopes) { std::set<nonneg int> checkedVars; for (const Token *tok = function->bodyStart; tok != function->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "%var%")) continue; const Variable* var = tok->variable(); if (!var) continue; if (Token::Match(tok, "%var% . lock ( )")) { if (!isMutex(var)) continue; if (!checkedVars.insert(var->declarationId()).second) continue; if (isLocalMutex(var, tok->scope())) localMutexError(tok); } else if (Token::Match(tok, "%var% (|{ %var% )|}|,")) { if (!isLockGuard(var)) continue; const Variable* mvar = tok->tokAt(2)->variable(); if (!mvar) continue; if (!checkedVars.insert(mvar->declarationId()).second) continue; if (var->isStatic() || var->isGlobal()) globalLockGuardError(tok); else if (isLocalMutex(mvar, tok->scope())) localMutexError(tok); } } } }
146,432
C++
.cpp
2,963
37.138373
231
0.558607
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,133
vf_sameexpressions.cpp
danmar_cppcheck/lib/vf_sameexpressions.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_sameexpressions.h" #include "astutils.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <utility> namespace ValueFlow { void analyzeSameExpressions(TokenList &tokenlist, const Settings& settings) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (tok->hasKnownIntValue()) continue; if (!tok->astOperand1() || !tok->astOperand2()) continue; if (tok->astOperand1()->isLiteral() || tok->astOperand2()->isLiteral()) continue; if (!astIsIntegral(tok->astOperand1(), false) && !astIsIntegral(tok->astOperand2(), false)) continue; Value val; if (Token::Match(tok, "==|>=|<=|/")) { val = ValueFlow::Value(1); val.setKnown(); } if (Token::Match(tok, "!=|>|<|%|-")) { val = ValueFlow::Value(0); val.setKnown(); } if (!val.isKnown()) continue; if (isSameExpression(false, tok->astOperand1(), tok->astOperand2(), settings, true, true, &val.errorPath)) { setTokenValue(tok, std::move(val), settings); } } } }
2,077
C++
.cpp
54
30.777778
120
0.60796
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,135
vf_arrayelement.cpp
danmar_cppcheck/lib/vf_arrayelement.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_arrayelement.h" #include "astutils.h" #include "library.h" #include "mathlib.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <list> #include <string> #include <utility> #include <vector> namespace ValueFlow { void analyzeArrayElement(TokenList& tokenlist, const Settings& settings) { for (Token* tok = tokenlist.front(); tok; tok = tok->next()) { if (tok->hasKnownIntValue()) continue; const Token* indexTok = nullptr; const Token* arrayTok = nullptr; if (Token::simpleMatch(tok, "[") && tok->isBinaryOp()) { indexTok = tok->astOperand2(); arrayTok = tok->astOperand1(); } else if (Token::Match(tok->tokAt(-2), ". %name% (") && astIsContainer(tok->tokAt(-2)->astOperand1())) { arrayTok = tok->tokAt(-2)->astOperand1(); const Library::Container* container = getLibraryContainer(arrayTok); if (!container || container->stdAssociativeLike) continue; const Library::Container::Yield yield = container->getYield(tok->strAt(-1)); if (yield != Library::Container::Yield::AT_INDEX) continue; indexTok = tok->astOperand2(); } if (!indexTok || !arrayTok) continue; for (const Value& arrayValue : arrayTok->values()) { if (!arrayValue.isTokValue()) continue; if (arrayValue.isImpossible()) continue; for (const Value& indexValue : indexTok->values()) { if (!indexValue.isIntValue()) continue; if (indexValue.isImpossible()) continue; if (!arrayValue.isKnown() && !indexValue.isKnown() && arrayValue.varId != 0 && indexValue.varId != 0 && !(arrayValue.varId == indexValue.varId && arrayValue.varvalue == indexValue.varvalue)) continue; Value result(0); result.condition = arrayValue.condition ? arrayValue.condition : indexValue.condition; result.setInconclusive(arrayValue.isInconclusive() || indexValue.isInconclusive()); result.varId = (arrayValue.varId != 0) ? arrayValue.varId : indexValue.varId; result.varvalue = (result.varId == arrayValue.varId) ? arrayValue.intvalue : indexValue.intvalue; if (arrayValue.valueKind == indexValue.valueKind) result.valueKind = arrayValue.valueKind; result.errorPath.insert(result.errorPath.end(), arrayValue.errorPath.cbegin(), arrayValue.errorPath.cend()); result.errorPath.insert(result.errorPath.end(), indexValue.errorPath.cbegin(), indexValue.errorPath.cend()); const MathLib::bigint index = indexValue.intvalue; if (arrayValue.tokvalue->tokType() == Token::eString) { const std::string s = arrayValue.tokvalue->strValue(); if (index == s.size()) { result.intvalue = 0; setTokenValue(tok, std::move(result), settings); } else if (index >= 0 && index < s.size()) { result.intvalue = s[index]; setTokenValue(tok, std::move(result), settings); } } else if (Token::simpleMatch(arrayValue.tokvalue, "{")) { std::vector<const Token*> args = getArguments(arrayValue.tokvalue); if (index < 0 || index >= args.size()) continue; const Token* arg = args[index]; if (!arg->hasKnownIntValue()) continue; const Value& v = arg->values().front(); result.intvalue = v.intvalue; result.errorPath.insert(result.errorPath.end(), v.errorPath.cbegin(), v.errorPath.cend()); setTokenValue(tok, std::move(result), settings); } } } } } }
5,195
C++
.cpp
102
36.764706
128
0.555096
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,136
checkvaarg.cpp
danmar_cppcheck/lib/checkvaarg.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "checkvaarg.h" #include "astutils.h" #include "errortypes.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include <cstddef> #include <iterator> #include <list> #include <vector> //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckVaarg instance; } //--------------------------------------------------------------------------- // Ensure that correct parameter is passed to va_start() //--------------------------------------------------------------------------- // CWE ids used: static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime static const CWE CWE688(688U); // Function Call With Incorrect Variable or Reference as Argument static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior void CheckVaarg::va_start_argument() { const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); const std::size_t functions = symbolDatabase->functionScopes.size(); const bool printWarnings = mSettings->severity.isEnabled(Severity::warning); logChecker("CheckVaarg::va_start_argument"); for (std::size_t i = 0; i < functions; ++i) { const Scope* scope = symbolDatabase->functionScopes[i]; const Function* function = scope->function; if (!function) continue; for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->scope()->isExecutable()) tok = tok->scope()->bodyEnd; else if (Token::simpleMatch(tok, "va_start (")) { const Token* param2 = tok->tokAt(2)->nextArgument(); if (!param2) continue; const Variable* var = param2->variable(); if (var && var->isReference()) referenceAs_va_start_error(param2, var->name()); if (var && var->index() + 2 < function->argCount() && printWarnings) { auto it = function->argumentList.end(); std::advance(it, -2); wrongParameterTo_va_start_error(tok, var->name(), it->name()); // cppcheck-suppress derefInvalidIterator // FP due to isVariableChangedByFunctionCall() } tok = tok->linkAt(1); } } } } void CheckVaarg::wrongParameterTo_va_start_error(const Token *tok, const std::string& paramIsName, const std::string& paramShouldName) { reportError(tok, Severity::warning, "va_start_wrongParameter", "'" + paramIsName + "' given to va_start() is not last named argument of the function. Did you intend to pass '" + paramShouldName + "'?", CWE688, Certainty::normal); } void CheckVaarg::referenceAs_va_start_error(const Token *tok, const std::string& paramName) { reportError(tok, Severity::error, "va_start_referencePassed", "Using reference '" + paramName + "' as parameter for va_start() results in undefined behaviour.", CWE758, Certainty::normal); } //--------------------------------------------------------------------------- // Detect missing va_end() if va_start() was used // Detect va_list usage after va_end() //--------------------------------------------------------------------------- void CheckVaarg::va_list_usage() { if (mSettings->clang) return; logChecker("CheckVaarg::va_list_usage"); // notclang const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Variable* var : symbolDatabase->variableList()) { if (!var || var->isPointer() || var->isReference() || var->isArray() || !var->scope() || var->typeStartToken()->str() != "va_list") continue; if (!var->isLocal() && !var->isArgument()) // Check only local variables and arguments continue; bool open = var->isArgument(); // va_list passed as argument are opened bool exitOnEndOfStatement = false; const Token* tok = var->nameToken()->next(); for (; tok && tok != var->scope()->bodyEnd; tok = tok->next()) { // Skip lambdas const Token* tok2 = findLambdaEndToken(tok); if (tok2) tok = tok2; if (Token::Match(tok, "va_start ( %varid%", var->declarationId())) { if (open) va_start_subsequentCallsError(tok, var->name()); open = true; tok = tok->linkAt(1); } else if (Token::Match(tok, "va_end ( %varid%", var->declarationId())) { if (!open) va_list_usedBeforeStartedError(tok, var->name()); open = false; tok = tok->linkAt(1); } else if (Token::simpleMatch(tok, "va_copy (")) { bool nopen = open; if (tok->linkAt(1)->previous()->varId() == var->declarationId()) { // Source if (!open) va_list_usedBeforeStartedError(tok, var->name()); } if (tok->tokAt(2)->varId() == var->declarationId()) { // Destination if (open) va_start_subsequentCallsError(tok, var->name()); nopen = true; } open = nopen; tok = tok->linkAt(1); } else if (Token::Match(tok, "throw|return")) exitOnEndOfStatement = true; else if (tok->str() == "break") { tok = findNextTokenFromBreak(tok); if (!tok) return; } else if (tok->str() == "goto" || (tok->isCpp() && tok->str() == "try")) { open = false; break; } else if (!open && tok->varId() == var->declarationId()) va_list_usedBeforeStartedError(tok, var->name()); else if (exitOnEndOfStatement && tok->str() == ";") break; } if (open && !var->isArgument()) va_end_missingError(tok, var->name()); } } void CheckVaarg::va_end_missingError(const Token *tok, const std::string& varname) { reportError(tok, Severity::error, "va_end_missing", "va_list '" + varname + "' was opened but not closed by va_end().", CWE664, Certainty::normal); } void CheckVaarg::va_list_usedBeforeStartedError(const Token *tok, const std::string& varname) { reportError(tok, Severity::error, "va_list_usedBeforeStarted", "va_list '" + varname + "' used before va_start() was called.", CWE664, Certainty::normal); } void CheckVaarg::va_start_subsequentCallsError(const Token *tok, const std::string& varname) { reportError(tok, Severity::error, "va_start_subsequentCalls", "va_start() or va_copy() called subsequently on '" + varname + "' without va_end() in between.", CWE664, Certainty::normal); }
7,814
C++
.cpp
160
40.05
209
0.573506
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,137
platform.cpp
danmar_cppcheck/lib/platform.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "platform.h" #include "path.h" #include <cstring> #include <iostream> #include <limits> #include <vector> #include "xml.h" Platform::Platform() { set(Type::Native); } bool Platform::set(Type t) { switch (t) { case Type::Unspecified: // unknown type sizes (sizes etc are set but are not known) case Type::Native: // same as system this code was compile on type = t; sizeof_bool = sizeof(bool); sizeof_short = sizeof(short); sizeof_int = sizeof(int); sizeof_long = sizeof(long); sizeof_long_long = sizeof(long long); sizeof_float = sizeof(float); sizeof_double = sizeof(double); sizeof_long_double = sizeof(long double); sizeof_wchar_t = sizeof(wchar_t); sizeof_size_t = sizeof(std::size_t); sizeof_pointer = sizeof(void *); if (type == Type::Unspecified) { defaultSign = '\0'; } else { defaultSign = std::numeric_limits<char>::is_signed ? 's' : 'u'; } char_bit = 8; short_bit = char_bit * sizeof_short; int_bit = char_bit * sizeof_int; long_bit = char_bit * sizeof_long; long_long_bit = char_bit * sizeof_long_long; return true; case Type::Win32W: case Type::Win32A: type = t; sizeof_bool = 1; // 4 in Visual C++ 4.2 sizeof_short = 2; sizeof_int = 4; sizeof_long = 4; sizeof_long_long = 8; sizeof_float = 4; sizeof_double = 8; sizeof_long_double = 8; sizeof_wchar_t = 2; sizeof_size_t = 4; sizeof_pointer = 4; defaultSign = '\0'; char_bit = 8; short_bit = char_bit * sizeof_short; int_bit = char_bit * sizeof_int; long_bit = char_bit * sizeof_long; long_long_bit = char_bit * sizeof_long_long; return true; case Type::Win64: type = t; sizeof_bool = 1; sizeof_short = 2; sizeof_int = 4; sizeof_long = 4; sizeof_long_long = 8; sizeof_float = 4; sizeof_double = 8; sizeof_long_double = 8; sizeof_wchar_t = 2; sizeof_size_t = 8; sizeof_pointer = 8; defaultSign = '\0'; char_bit = 8; short_bit = char_bit * sizeof_short; int_bit = char_bit * sizeof_int; long_bit = char_bit * sizeof_long; long_long_bit = char_bit * sizeof_long_long; return true; case Type::Unix32: type = t; sizeof_bool = 1; sizeof_short = 2; sizeof_int = 4; sizeof_long = 4; sizeof_long_long = 8; sizeof_float = 4; sizeof_double = 8; sizeof_long_double = 12; sizeof_wchar_t = 4; sizeof_size_t = 4; sizeof_pointer = 4; defaultSign = '\0'; char_bit = 8; short_bit = char_bit * sizeof_short; int_bit = char_bit * sizeof_int; long_bit = char_bit * sizeof_long; long_long_bit = char_bit * sizeof_long_long; return true; case Type::Unix64: type = t; sizeof_bool = 1; sizeof_short = 2; sizeof_int = 4; sizeof_long = 8; sizeof_long_long = 8; sizeof_float = 4; sizeof_double = 8; sizeof_long_double = 16; sizeof_wchar_t = 4; sizeof_size_t = 8; sizeof_pointer = 8; defaultSign = '\0'; char_bit = 8; short_bit = char_bit * sizeof_short; int_bit = char_bit * sizeof_int; long_bit = char_bit * sizeof_long; long_long_bit = char_bit * sizeof_long_long; return true; case Type::File: // sizes are not set. return false; } // unsupported platform return false; } bool Platform::set(const std::string& platformstr, std::string& errstr, const std::vector<std::string>& paths, bool debug) { if (platformstr == "win32A") set(Type::Win32A); else if (platformstr == "win32W") set(Type::Win32W); else if (platformstr == "win64") set(Type::Win64); else if (platformstr == "unix32") set(Type::Unix32); else if (platformstr == "unix64") set(Type::Unix64); else if (platformstr == "native") set(Type::Native); else if (platformstr == "unspecified") set(Type::Unspecified); else if (paths.empty()) { errstr = "unrecognized platform: '" + platformstr + "' (no lookup)."; return false; } else { bool found = false; for (const std::string& path : paths) { if (debug) std::cout << "looking for platform '" + platformstr + "' in '" + path + "'" << std::endl; if (loadFromFile(path.c_str(), platformstr, debug)) { found = true; break; } } if (!found) { errstr = "unrecognized platform: '" + platformstr + "'."; return false; } } return true; } bool Platform::loadFromFile(const char exename[], const std::string &filename, bool debug) { // TODO: only append .xml if missing // TODO: use native separators std::vector<std::string> filenames{ filename, filename + ".xml", "platforms/" + filename, "platforms/" + filename + ".xml" }; if (exename && (std::string::npos != Path::fromNativeSeparators(exename).find('/'))) { filenames.push_back(Path::getPathFromFilename(Path::fromNativeSeparators(exename)) + filename); filenames.push_back(Path::getPathFromFilename(Path::fromNativeSeparators(exename)) + "platforms/" + filename); filenames.push_back(Path::getPathFromFilename(Path::fromNativeSeparators(exename)) + "platforms/" + filename + ".xml"); } #ifdef FILESDIR std::string filesdir = FILESDIR; if (!filesdir.empty() && filesdir[filesdir.size()-1] != '/') filesdir += '/'; filenames.push_back(filesdir + ("platforms/" + filename)); filenames.push_back(filesdir + ("platforms/" + filename + ".xml")); #endif // open file.. tinyxml2::XMLDocument doc; bool success = false; for (const std::string & f : filenames) { if (debug) std::cout << "try to load platform file '" << f << "' ... "; if (doc.LoadFile(f.c_str()) == tinyxml2::XML_SUCCESS) { if (debug) std::cout << "Success" << std::endl; success = true; break; } if (debug) std::cout << doc.ErrorStr() << std::endl; } if (!success) return false; return loadFromXmlDocument(&doc); } static unsigned int xmlTextAsUInt(const tinyxml2::XMLElement* node, bool& error) { unsigned int retval = 0; if (node->QueryUnsignedText(&retval) != tinyxml2::XML_SUCCESS) error = true; return retval; } bool Platform::loadFromXmlDocument(const tinyxml2::XMLDocument *doc) { const tinyxml2::XMLElement * const rootnode = doc->FirstChildElement(); if (!rootnode || std::strcmp(rootnode->Name(), "platform") != 0) return false; bool error = false; for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) { const char* name = node->Name(); if (std::strcmp(name, "default-sign") == 0) { const char* str = node->GetText(); if (str) defaultSign = *str; else error = true; } else if (std::strcmp(name, "char_bit") == 0) char_bit = xmlTextAsUInt(node, error); else if (std::strcmp(name, "sizeof") == 0) { for (const tinyxml2::XMLElement *sz = node->FirstChildElement(); sz; sz = sz->NextSiblingElement()) { const char* szname = sz->Name(); if (std::strcmp(szname, "short") == 0) sizeof_short = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "bool") == 0) sizeof_bool = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "int") == 0) sizeof_int = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "long") == 0) sizeof_long = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "long-long") == 0) sizeof_long_long = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "float") == 0) sizeof_float = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "double") == 0) sizeof_double = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "long-double") == 0) sizeof_long_double = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "pointer") == 0) sizeof_pointer = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "size_t") == 0) sizeof_size_t = xmlTextAsUInt(sz, error); else if (std::strcmp(szname, "wchar_t") == 0) sizeof_wchar_t = xmlTextAsUInt(sz, error); } } } short_bit = char_bit * sizeof_short; int_bit = char_bit * sizeof_int; long_bit = char_bit * sizeof_long; long_long_bit = char_bit * sizeof_long_long; type = Type::File; return !error; } std::string Platform::getLimitsDefines(bool c99) const { std::string s; // climits / limits.h s += "CHAR_BIT="; s += std::to_string(char_bit); s += ";SCHAR_MIN="; s += std::to_string(min_value(char_bit)); s += ";SCHAR_MAX="; s += std::to_string(max_value(char_bit)); s += ";UCHAR_MAX="; s += std::to_string(max_value(char_bit+1)); s += ";CHAR_MIN="; if (defaultSign == 'u') s += std::to_string(min_value(char_bit)); else s += std::to_string(0); s += ";CHAR_MAX="; if (defaultSign == 'u') s += std::to_string(max_value(char_bit+1)); else s += std::to_string(max_value(char_bit)); // TODO //s += ";MB_LEN_MAX="; s += ";SHRT_MIN="; s += std::to_string(min_value(short_bit)); s += ";SHRT_MAX="; s += std::to_string(max_value(short_bit)); s += ";USHRT_MAX="; s += std::to_string(max_value(short_bit+1)); s += ";INT_MIN="; s += std::to_string(min_value(int_bit)); s += ";INT_MAX="; s += std::to_string(max_value(int_bit)); s += ";UINT_MAX="; s += std::to_string(max_value(int_bit+1)); s += ";LONG_MIN="; s += std::to_string(min_value(long_bit)); s += ";LONG_MAX="; s += std::to_string(max_value(long_bit)); s += ";ULONG_MAX="; s += std::to_string(max_value(long_bit+1)); if (c99) { s += ";LLONG_MIN="; s += std::to_string(min_value(long_long_bit)); s += ";LLONG_MAX="; s += std::to_string(max_value(long_long_bit)); s += ";ULLONG_MAX="; s += std::to_string(max_value(long_long_bit + 1)); } // cstdint / stdint.h // FIXME: these are currently hard-coded in std.cfg /* INTMAX_MIN INTMAX_MAX UINTMAX_MAX INTN_MIN INTN_MAX UINTN_MAX INT_LEASTN_MIN INT_LEASTN_MAX UINT_LEASTN_MAX INT_FASTN_MIN INT_FASTN_MAX UINT_FASTN_MAX INTPTR_MIN INTPTR_MAX UINTPTR_MAX SIZE_MAX PTRDIFF_MIN PTRDIFF_MAX SIG_ATOMIC_MIN SIG_ATOMIC_MAX WCHAR_MIN WCHAR_MAX WINT_MIN WINT_MAX // function-like macros // implemented in std.cfg INTMAX_C UINTMAX_C INTN_C UINTN_C */ // cfloat / float.h /* // TODO: implement FLT_RADIX FLT_MANT_DIG DBL_MANT_DIG LDBL_MANT_DIG FLT_DIG DBL_DIG LDBL_DIG FLT_MIN_EXP DBL_MIN_EXP LDBL_MIN_EXP FLT_MIN_10_EXP DBL_MIN_10_EXP LDBL_MIN_10_EXP FLT_MAX_EXP DBL_MAX_EXP LDBL_MAX_EXP FLT_MAX_10_EXP DBL_MAX_10_EXP LDBL_MAX_10_EXP FLT_MAX DBL_MAX LDBL_MAX FLT_EPSILON DBL_EPSILON LDBL_EPSILON FLT_MIN DBL_MIN LDBL_MIN FLT_ROUNDS // C99 / C++11 only FLT_EVAL_METHOD DECIMAL_DIG */ return s; } std::string Platform::getLimitsDefines(Standards::cstd_t cstd) const { return getLimitsDefines(cstd >= Standards::cstd_t::C99); } std::string Platform::getLimitsDefines(Standards::cppstd_t cppstd) const { return getLimitsDefines(cppstd >= Standards::cppstd_t::CPP11); }
13,530
C++
.cpp
410
25.063415
127
0.557942
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,138
checkboost.cpp
danmar_cppcheck/lib/checkboost.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "checkboost.h" #include "errortypes.h" #include "symboldatabase.h" #include "token.h" #include <vector> // Register this check class (by creating a static instance of it) namespace { CheckBoost instance; } static const CWE CWE664(664); void CheckBoost::checkBoostForeachModification() { logChecker("CheckBoost::checkBoostForeachModification"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) { if (!Token::simpleMatch(tok, "BOOST_FOREACH (")) continue; const Token *containerTok = tok->linkAt(1)->previous(); if (!Token::Match(containerTok, "%var% ) {")) continue; const Token *tok2 = containerTok->tokAt(2); const Token *end = tok2->link(); for (; tok2 != end; tok2 = tok2->next()) { if (Token::Match(tok2, "%varid% . insert|erase|push_back|push_front|pop_front|pop_back|clear|swap|resize|assign|merge|remove|remove_if|reverse|sort|splice|unique|pop|push", containerTok->varId())) { const Token* nextStatement = Token::findsimplematch(tok2->linkAt(3), ";", end); if (!Token::Match(nextStatement, "; break|return|throw")) boostForeachError(tok2); break; } } } } } void CheckBoost::boostForeachError(const Token *tok) { reportError(tok, Severity::error, "boostForeachError", "BOOST_FOREACH caches the end() iterator. It's undefined behavior if you modify the container inside.", CWE664, Certainty::normal ); }
2,565
C++
.cpp
57
38.22807
214
0.661465
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,139
errortypes.cpp
danmar_cppcheck/lib/errortypes.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "errortypes.h" #include "utils.h" static std::string typeToString(InternalError::Type type) { switch (type) { case InternalError::Type::AST: return "internalAstError"; case InternalError::Type::SYNTAX: return "syntaxError"; case InternalError::Type::UNKNOWN_MACRO: return "unknownMacro"; case InternalError::Type::INTERNAL: return "internalError"; case InternalError::Type::LIMIT: return "cppcheckLimit"; case InternalError::Type::INSTANTIATION: return "instantiationError"; } cppcheck::unreachable(); } InternalError::InternalError(const Token *tok, std::string errorMsg, Type type) : InternalError(tok, std::move(errorMsg), "", type) {} InternalError::InternalError(const Token *tok, std::string errorMsg, std::string details, Type type) : token(tok), errorMessage(std::move(errorMsg)), details(std::move(details)), type(type), id(typeToString(type)) {} std::string severityToString(Severity severity) { switch (severity) { case Severity::none: return ""; case Severity::error: return "error"; case Severity::warning: return "warning"; case Severity::style: return "style"; case Severity::performance: return "performance"; case Severity::portability: return "portability"; case Severity::information: return "information"; case Severity::debug: return "debug"; case Severity::internal: return "internal"; } throw InternalError(nullptr, "Unknown severity"); } // TODO: bail out on invalid severity Severity severityFromString(const std::string& severity) { if (severity.empty()) return Severity::none; if (severity == "none") return Severity::none; if (severity == "error") return Severity::error; if (severity == "warning") return Severity::warning; if (severity == "style") return Severity::style; if (severity == "performance") return Severity::performance; if (severity == "portability") return Severity::portability; if (severity == "information") return Severity::information; if (severity == "debug") return Severity::debug; if (severity == "internal") return Severity::internal; return Severity::none; }
3,116
C++
.cpp
92
28.967391
114
0.688432
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,140
vf_common.cpp
danmar_cppcheck/lib/vf_common.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_common.h" #include "astutils.h" #include "mathlib.h" #include "path.h" #include "platform.h" #include "settings.h" #include "standards.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "valueflow.h" #include "vf_settokenvalue.h" #include <cassert> #include <climits> #include <cstddef> #include <exception> #include <limits> #include <sstream> #include <utility> #include <vector> namespace ValueFlow { bool getMinMaxValues(const ValueType *vt, const Platform &platform, MathLib::bigint &minValue, MathLib::bigint &maxValue) { if (!vt || !vt->isIntegral() || vt->pointer) return false; int bits; switch (vt->type) { case ValueType::Type::BOOL: bits = 1; break; case ValueType::Type::CHAR: bits = platform.char_bit; break; case ValueType::Type::SHORT: bits = platform.short_bit; break; case ValueType::Type::INT: bits = platform.int_bit; break; case ValueType::Type::LONG: bits = platform.long_bit; break; case ValueType::Type::LONGLONG: bits = platform.long_long_bit; break; default: return false; } if (bits == 1) { minValue = 0; maxValue = 1; } else if (bits < 62) { if (vt->sign == ValueType::Sign::UNSIGNED) { minValue = 0; maxValue = (1LL << bits) - 1; } else { minValue = -(1LL << (bits - 1)); maxValue = (1LL << (bits - 1)) - 1; } } else if (bits == 64) { if (vt->sign == ValueType::Sign::UNSIGNED) { minValue = 0; maxValue = LLONG_MAX; // todo max unsigned value } else { minValue = LLONG_MIN; maxValue = LLONG_MAX; } } else { return false; } return true; } bool getMinMaxValues(const std::string &typestr, const Settings &settings, bool cpp, MathLib::bigint &minvalue, MathLib::bigint &maxvalue) { TokenList typeTokens(&settings); std::istringstream istr(typestr+";"); if (!typeTokens.createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C)) return false; typeTokens.simplifyPlatformTypes(); typeTokens.simplifyStdType(); const ValueType &vt = ValueType::parseDecl(typeTokens.front(), settings); return getMinMaxValues(&vt, settings.platform, minvalue, maxvalue); } long long truncateIntValue(long long value, size_t value_size, const ValueType::Sign dst_sign) { if (value_size == 0) return value; const MathLib::biguint unsignedMaxValue = std::numeric_limits<MathLib::biguint>::max() >> ((sizeof(unsignedMaxValue) - value_size) * 8); const MathLib::biguint signBit = 1ULL << (value_size * 8 - 1); value &= unsignedMaxValue; if (dst_sign == ValueType::Sign::SIGNED && (value & signBit)) value |= ~unsignedMaxValue; return value; } static nonneg int getSizeOfType(const Token *typeTok, const Settings &settings) { const ValueType &valueType = ValueType::parseDecl(typeTok, settings); return getSizeOf(valueType, settings); } // Handle various constants.. Token * valueFlowSetConstantValue(Token *tok, const Settings &settings) { if ((tok->isNumber() && MathLib::isInt(tok->str())) || (tok->tokType() == Token::eChar)) { try { MathLib::bigint signedValue = MathLib::toBigNumber(tok->str()); const ValueType* vt = tok->valueType(); if (vt && vt->sign == ValueType::UNSIGNED && signedValue < 0 && getSizeOf(*vt, settings) < sizeof(MathLib::bigint)) { MathLib::bigint minValue{}, maxValue{}; if (getMinMaxValues(tok->valueType(), settings.platform, minValue, maxValue)) signedValue += maxValue + 1; } Value value(signedValue); if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok, std::move(value), settings); } catch (const std::exception & /*e*/) { // Bad character literal } } else if (tok->isNumber() && MathLib::isFloat(tok->str())) { Value value; value.valueType = Value::ValueType::FLOAT; value.floatValue = MathLib::toDoubleNumber(tok->str()); if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok, std::move(value), settings); } else if (tok->enumerator() && tok->enumerator()->value_known) { Value value(tok->enumerator()->value); if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok, std::move(value), settings); } else if (tok->str() == "NULL" || (tok->isCpp() && tok->str() == "nullptr")) { Value value(0); if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok, std::move(value), settings); } else if (Token::simpleMatch(tok, "sizeof (")) { if (tok->next()->astOperand2() && !tok->next()->astOperand2()->isLiteral() && tok->next()->astOperand2()->valueType() && (tok->next()->astOperand2()->valueType()->pointer == 0 || // <- TODO this is a bailout, abort when there are array->pointer conversions (tok->next()->astOperand2()->variable() && !tok->next()->astOperand2()->variable()->isArray())) && !tok->next()->astOperand2()->valueType()->isEnum()) { // <- TODO this is a bailout, handle enum with non-int types const size_t sz = getSizeOf(*tok->next()->astOperand2()->valueType(), settings); if (sz) { Value value(sz); value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); return tok->linkAt(1); } } const Token *tok2 = tok->tokAt(2); // skip over tokens to find variable or type while (tok2 && !tok2->isStandardType() && Token::Match(tok2, "%name% ::|.|[")) { if (tok2->strAt(1) == "[") tok2 = tok2->linkAt(1)->next(); else tok2 = tok2->tokAt(2); } if (Token::simpleMatch(tok, "sizeof ( *")) { const ValueType *vt = tok->tokAt(2)->valueType(); const size_t sz = vt ? getSizeOf(*vt, settings) : 0; if (sz > 0) { Value value(sz); if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified) value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); } } else if (tok2->enumerator() && tok2->enumerator()->scope) { long long size = settings.platform.sizeof_int; const Token * type = tok2->enumerator()->scope->enumType; if (type) { size = getSizeOfType(type, settings); if (size == 0) tok->linkAt(1); } Value value(size); if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified) value.setKnown(); setTokenValue(tok, value, settings); setTokenValue(tok->next(), std::move(value), settings); } else if (tok2->type() && tok2->type()->isEnumType()) { long long size = settings.platform.sizeof_int; if (tok2->type()->classScope) { const Token * type = tok2->type()->classScope->enumType; if (type) { size = getSizeOfType(type, settings); } } Value value(size); if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified) value.setKnown(); setTokenValue(tok, value, settings); setTokenValue(tok->next(), std::move(value), settings); } else if (Token::Match(tok, "sizeof ( %var% ) /") && tok->next()->astParent() == tok->tokAt(4) && tok->tokAt(4)->astOperand2() && Token::simpleMatch(tok->tokAt(4)->astOperand2()->previous(), "sizeof (")) { // Get number of elements in array const Token *sz1 = tok->tokAt(2); const Token *sz2 = tok->tokAt(4)->astOperand2(); // left parenthesis of sizeof on rhs const nonneg int varid1 = sz1->varId(); if (varid1 && sz1->variable() && sz1->variable()->isArray() && !sz1->variable()->dimensions().empty() && sz1->variable()->dimensionKnown(0) && Token::Match(sz2->astOperand2(), "*|[") && Token::Match(sz2->astOperand2()->astOperand1(), "%varid%", varid1)) { Value value(sz1->variable()->dimension(0)); if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified) value.setKnown(); setTokenValue(tok->tokAt(4), std::move(value), settings); } } else if (Token::Match(tok2, "%var% )")) { const Variable *var = tok2->variable(); // only look for single token types (no pointers or references yet) if (var && var->typeStartToken() == var->typeEndToken()) { // find the size of the type size_t size = 0; if (var->isEnumType()) { size = settings.platform.sizeof_int; if (var->type()->classScope && var->type()->classScope->enumType) size = getSizeOfType(var->type()->classScope->enumType, settings); } else if (var->valueType()) { size = getSizeOf(*var->valueType(), settings); } else if (!var->type()) { size = getSizeOfType(var->typeStartToken(), settings); } // find the number of elements size_t count = 1; for (size_t i = 0; i < var->dimensions().size(); ++i) { if (var->dimensionKnown(i)) count *= var->dimension(i); else count = 0; } if (size && count > 0) { Value value(count * size); if (settings.platform.type != Platform::Type::Unspecified) value.setKnown(); setTokenValue(tok, value, settings); setTokenValue(tok->next(), std::move(value), settings); } } } else if (tok2->tokType() == Token::eString) { const size_t sz = Token::getStrSize(tok2, settings); if (sz > 0) { Value value(sz); value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); } } else if (tok2->tokType() == Token::eChar) { nonneg int sz = 0; if (tok2->isCpp() && settings.standards.cpp >= Standards::CPP20 && tok2->isUtf8()) sz = 1; else if (tok2->isUtf16()) sz = 2; else if (tok2->isUtf32()) sz = 4; else if (tok2->isLong()) sz = settings.platform.sizeof_wchar_t; else if ((!tok2->isCpp() && tok2->isCChar()) || (tok2->isCMultiChar())) sz = settings.platform.sizeof_int; else sz = 1; if (sz > 0) { Value value(sz); value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); } } else if (!tok2->type()) { const ValueType& vt = ValueType::parseDecl(tok2, settings); size_t sz = getSizeOf(vt, settings); const Token* brac = tok2->astParent(); while (Token::simpleMatch(brac, "[")) { const Token* num = brac->astOperand2(); if (num && ((num->isNumber() && MathLib::isInt(num->str())) || num->tokType() == Token::eChar)) { try { const MathLib::biguint dim = MathLib::toBigUNumber(num->str()); sz *= dim; brac = brac->astParent(); continue; } catch (const std::exception& /*e*/) { // Bad integer literal } } sz = 0; break; } if (sz > 0) { Value value(sz); if (!tok2->isTemplateArg() && settings.platform.type != Platform::Type::Unspecified) value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); } } // skip over enum tok = tok->linkAt(1); } else if (Token::Match(tok, "%name% [{(] [)}]") && (tok->isStandardType() || (tok->variable() && tok->variable()->nameToken() == tok && (tok->variable()->isPointer() || (tok->variable()->valueType() && tok->variable()->valueType()->isIntegral()))))) { Value value(0); if (!tok->isTemplateArg()) value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); } else if (Token::simpleMatch(tok, "= { } ;")) { const Token* lhs = tok->astOperand1(); if (lhs && lhs->valueType() && (lhs->valueType()->isIntegral() || lhs->valueType()->pointer > 0)) { Value value(0); value.setKnown(); setTokenValue(tok->next(), std::move(value), settings); } } return tok->next(); } Value castValue(Value value, const ValueType::Sign sign, nonneg int bit) { if (value.isFloatValue()) { value.valueType = Value::ValueType::INT; if (value.floatValue >= std::numeric_limits<int>::min() && value.floatValue <= std::numeric_limits<int>::max()) { value.intvalue = value.floatValue; } else { // don't perform UB value.intvalue = 0; } } if (bit < MathLib::bigint_bits) { constexpr MathLib::biguint one = 1; value.intvalue &= (one << bit) - 1; if (sign == ValueType::Sign::SIGNED && value.intvalue & (one << (bit - 1))) { value.intvalue |= ~((one << bit) - 1ULL); } } return value; } std::string debugString(const Value& v) { std::string kind; switch (v.valueKind) { case Value::ValueKind::Impossible: case Value::ValueKind::Known: kind = "always"; break; case Value::ValueKind::Inconclusive: kind = "inconclusive"; break; case Value::ValueKind::Possible: kind = "possible"; break; } return kind + " " + v.toString(); } void setSourceLocation(Value& v, SourceLocation ctx, const Token* tok, SourceLocation local) { std::string file = ctx.file_name(); if (file.empty()) return; std::string s = Path::stripDirectoryPart(file) + ":" + std::to_string(ctx.line()) + ": " + ctx.function_name() + " => " + local.function_name() + ": " + debugString(v); v.debugPath.emplace_back(tok, std::move(s)); } std::list<Value> getIteratorValues(std::list<Value> values, const Value::ValueKind* kind) { values.remove_if([&](const Value& v) { if (kind && v.valueKind != *kind) return true; return !v.isIteratorValue(); }); return values; } MathLib::bigint valueFlowGetStrLength(const Token* tok) { if (tok->tokType() == Token::eString) return Token::getStrLength(tok); if (astIsGenericChar(tok) || tok->tokType() == Token::eChar) return 1; if (const Value* v = tok->getKnownValue(Value::ValueType::CONTAINER_SIZE)) return v->intvalue; if (const Value* v = tok->getKnownValue(Value::ValueType::TOK)) { if (v->tokvalue != tok) return valueFlowGetStrLength(v->tokvalue); } return 0; } bool isBreakOrContinueScope(const Token* endToken) { if (!Token::simpleMatch(endToken, "}")) return false; return Token::Match(endToken->tokAt(-2), "break|continue ;"); } const Scope* getLoopScope(const Token* tok) { if (!tok) return nullptr; const Scope* scope = tok->scope(); while (scope && scope->type != Scope::eWhile && scope->type != Scope::eFor && scope->type != Scope::eDo) scope = scope->nestedIn; return scope; } void setSymbolic(Value& value, const Token* tok) { assert(tok && tok->exprId() > 0 && "Missing expr id for symbolic value"); value.valueType = Value::ValueType::SYMBOLIC; value.tokvalue = tok; } Value makeSymbolic(const Token* tok, MathLib::bigint delta) { Value value; value.setKnown(); setSymbolic(value, tok); value.intvalue = delta; return value; } void removeImpossible(std::list<Value>& values, int indirect) { values.remove_if([&](const Value& v) { if (indirect >= 0 && v.indirect != indirect) return false; return v.isImpossible(); }); } void changeKnownToPossible(std::list<Value> &values, int indirect) { for (Value& v: values) { if (indirect >= 0 && v.indirect != indirect) continue; v.changeKnownToPossible(); } } void lowerToPossible(std::list<Value>& values, int indirect) { changeKnownToPossible(values, indirect); removeImpossible(values, indirect); } }
19,997
C++
.cpp
451
30.962306
177
0.505995
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,141
fwdanalysis.cpp
danmar_cppcheck/lib/fwdanalysis.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "fwdanalysis.h" #include "astutils.h" #include "config.h" #include "library.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "vfvalue.h" #include <list> #include <string> #include <utility> static bool isUnchanged(const Token *startToken, const Token *endToken, const std::set<nonneg int> &exprVarIds, bool local) { for (const Token *tok = startToken; tok != endToken; tok = tok->next()) { if (!local && Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {")) // TODO: this is a quick bailout return false; if (tok->varId() == 0 || exprVarIds.find(tok->varId()) == exprVarIds.end()) continue; const Token *parent = tok; while (parent->astParent() && !parent->astParent()->isAssignmentOp() && parent->astParent()->tokType() != Token::Type::eIncDecOp) { if (parent->str() == "," || parent->isUnaryOp("&")) // TODO: This is a quick bailout return false; parent = parent->astParent(); } if (parent->astParent()) { if (parent->astParent()->tokType() == Token::Type::eIncDecOp) return false; if (parent->astParent()->isAssignmentOp() && parent == parent->astParent()->astOperand1()) return false; } } return true; } static bool hasFunctionCall(const Token *tok) { if (!tok) return false; if (Token::Match(tok, "%name% (")) // todo, const/pure function? return true; return hasFunctionCall(tok->astOperand1()) || hasFunctionCall(tok->astOperand2()); } static bool hasGccCompoundStatement(const Token *tok) { if (!tok) return false; if (tok->str() == "{" && Token::simpleMatch(tok->previous(), "( {")) return true; return hasGccCompoundStatement(tok->astOperand1()) || hasGccCompoundStatement(tok->astOperand2()); } static bool nonLocal(const Variable* var, bool deref) { return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isArgument() && var->isPointer()) || var->isStatic() || var->isReference() || var->isExtern(); } static bool hasVolatileCastOrVar(const Token *expr) { bool ret = false; visitAstNodes(expr, [&ret](const Token *tok) { if (tok->variable() && tok->variable()->isVolatile()) ret = true; else if (Token::simpleMatch(tok, "( volatile")) ret = true; return ret ? ChildrenToVisit::none : ChildrenToVisit::op1_and_op2; }); return ret; } FwdAnalysis::Result FwdAnalysis::checkRecursive(const Token *expr, const Token *startToken, const Token *endToken, const std::set<nonneg int> &exprVarIds, bool local, bool inInnerClass, int depth) { // Parse the given tokens if (++depth > 1000) return Result(Result::Type::BAILOUT); for (const Token* tok = startToken; precedes(tok, endToken); tok = tok->next()) { if (Token::simpleMatch(tok, "try {")) { // TODO: handle try return Result(Result::Type::BAILOUT); } if (Token::simpleMatch(tok, "break ;")) { return Result(Result::Type::BREAK, tok); } if (Token::simpleMatch(tok, "goto")) return Result(Result::Type::BAILOUT); if (!inInnerClass && tok->str() == "{" && tok->scope()->isClassOrStruct()) { // skip returns from local class definition FwdAnalysis::Result result = checkRecursive(expr, tok, tok->link(), exprVarIds, local, true, depth); if (result.type != Result::Type::NONE) return result; tok=tok->link(); } if (tok->str() == "continue") // TODO return Result(Result::Type::BAILOUT); if (const Token *lambdaEndToken = findLambdaEndToken(tok)) { tok = lambdaEndToken; const Result lambdaResult = checkRecursive(expr, lambdaEndToken->link()->next(), lambdaEndToken, exprVarIds, local, inInnerClass, depth); if (lambdaResult.type == Result::Type::READ || lambdaResult.type == Result::Type::BAILOUT) return lambdaResult; } if (Token::Match(tok, "return|throw")) { // TODO: Handle these better // Is expr variable used in expression? const Token* opTok = tok->astOperand1(); if (!opTok) opTok = tok->next(); std::pair<const Token*, const Token*> startEndTokens = opTok->findExpressionStartEndTokens(); FwdAnalysis::Result result = checkRecursive(expr, startEndTokens.first, startEndTokens.second->next(), exprVarIds, local, true, depth); if (result.type != Result::Type::NONE) return result; // #9167: if the return is inside an inner class, it does not tell us anything if (!inInnerClass) { if (!local && mWhat == What::Reassign) return Result(Result::Type::BAILOUT); return Result(Result::Type::RETURN); } } if (tok->str() == "}") { // Known value => possible value if (tok->scope() == expr->scope()) mValueFlowKnown = false; if (tok->scope()->isLoopScope()) { // check condition const Token *conditionStart = nullptr; const Token *conditionEnd = nullptr; if (Token::simpleMatch(tok->link()->previous(), ") {")) { conditionEnd = tok->link()->previous(); conditionStart = conditionEnd->link(); } else if (Token::simpleMatch(tok->link()->previous(), "do {") && Token::simpleMatch(tok, "} while (")) { conditionStart = tok->tokAt(2); conditionEnd = conditionStart->link(); } if (conditionStart && conditionEnd) { bool used = false; for (const Token *condTok = conditionStart; condTok != conditionEnd; condTok = condTok->next()) { if (exprVarIds.find(condTok->varId()) != exprVarIds.end()) { used = true; break; } } if (used) return Result(Result::Type::BAILOUT); } // check loop body again.. const FwdAnalysis::Result &result = checkRecursive(expr, tok->link(), tok, exprVarIds, local, inInnerClass, depth); if (result.type == Result::Type::BAILOUT || result.type == Result::Type::READ) return result; } } if (Token::simpleMatch(tok, "else {")) tok = tok->linkAt(1); if (Token::simpleMatch(tok, "asm (")) return Result(Result::Type::BAILOUT); if (mWhat == What::ValueFlow && (Token::Match(tok, "while|for (") || Token::simpleMatch(tok, "do {"))) { const Token *bodyStart = nullptr; const Token *conditionStart = nullptr; if (Token::simpleMatch(tok, "do {")) { bodyStart = tok->next(); if (Token::simpleMatch(bodyStart->link(), "} while (")) conditionStart = bodyStart->link()->tokAt(2); } else { conditionStart = tok->next(); if (Token::simpleMatch(conditionStart->link(), ") {")) bodyStart = conditionStart->link()->next(); } if (!bodyStart || !conditionStart) return Result(Result::Type::BAILOUT); // Is expr changed in condition? if (!isUnchanged(conditionStart, conditionStart->link(), exprVarIds, local)) return Result(Result::Type::BAILOUT); // Is expr changed in loop body? if (!isUnchanged(bodyStart, bodyStart->link(), exprVarIds, local)) return Result(Result::Type::BAILOUT); } if (mWhat == What::ValueFlow && Token::simpleMatch(tok, "if (") && Token::simpleMatch(tok->linkAt(1), ") {")) { const Token *bodyStart = tok->linkAt(1)->next(); const Token *conditionStart = tok->next(); const Token *condTok = conditionStart->astOperand2(); if (condTok->hasKnownIntValue()) { const bool cond = condTok->values().front().intvalue; if (cond) { FwdAnalysis::Result result = checkRecursive(expr, bodyStart, bodyStart->link(), exprVarIds, local, true, depth); if (result.type != Result::Type::NONE) return result; } else if (Token::simpleMatch(bodyStart->link(), "} else {")) { bodyStart = bodyStart->link()->tokAt(2); FwdAnalysis::Result result = checkRecursive(expr, bodyStart, bodyStart->link(), exprVarIds, local, true, depth); if (result.type != Result::Type::NONE) return result; } } tok = bodyStart->link(); if (isReturnScope(tok, mSettings.library)) return Result(Result::Type::BAILOUT); if (Token::simpleMatch(tok, "} else {")) tok = tok->linkAt(2); if (!tok) return Result(Result::Type::BAILOUT); // Is expr changed in condition? if (!isUnchanged(conditionStart, conditionStart->link(), exprVarIds, local)) return Result(Result::Type::BAILOUT); // Is expr changed in condition body? if (!isUnchanged(bodyStart, bodyStart->link(), exprVarIds, local)) return Result(Result::Type::BAILOUT); } if (!local && Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {")) { // TODO: this is a quick bailout return Result(Result::Type::BAILOUT); } if (mWhat == What::Reassign && Token::simpleMatch(tok, ";") && Token::simpleMatch(tok->astParent(), ";") && Token::simpleMatch(tok->astParent()->astParent(), "(") && Token::simpleMatch(tok->astParent()->astParent()->previous(), "for (") && !isUnchanged(tok, tok->astParent()->astParent()->link(), exprVarIds, local)) // TODO: This is a quick bailout to avoid FP #9420, there are false negatives (TODO_ASSERT_EQUALS) return Result(Result::Type::BAILOUT); if (expr->isName() && Token::Match(tok, "%name% (") && tok->str().find('<') != std::string::npos && tok->str().find(expr->str()) != std::string::npos) return Result(Result::Type::BAILOUT); if (exprVarIds.find(tok->varId()) != exprVarIds.end()) { const Token *parent = tok; bool other = false; bool same = tok->astParent() && isSameExpression(false, expr, tok, mSettings, true, false, nullptr); while (!same && Token::Match(parent->astParent(), "*|.|::|[|(|%cop%")) { parent = parent->astParent(); if (parent->str() == "(" && !parent->isCast()) break; if (isSameExpression(false, expr, parent, mSettings, true, false, nullptr)) { same = true; if (mWhat == What::ValueFlow) { KnownAndToken v; v.known = mValueFlowKnown; v.token = parent; mValueFlow.push_back(v); } } if (Token::Match(parent, ". %var%") && parent->next()->varId() && exprVarIds.find(parent->next()->varId()) == exprVarIds.end() && isSameExpression(false, expr->astOperand1(), parent->astOperand1(), mSettings, true, false, nullptr)) { other = true; break; } } if (mWhat != What::ValueFlow && same && Token::simpleMatch(parent->astParent(), "[") && parent == parent->astParent()->astOperand2()) { return Result(Result::Type::READ); } if (other) continue; if (Token::simpleMatch(parent->astParent(), "=") && parent == parent->astParent()->astOperand1()) { if (!local && hasFunctionCall(parent->astParent()->astOperand2())) { // TODO: this is a quick bailout return Result(Result::Type::BAILOUT); } if (hasOperand(parent->astParent()->astOperand2(), expr)) { if (mWhat == What::Reassign) return Result(Result::Type::READ); continue; } const auto startEnd = parent->astParent()->astOperand2()->findExpressionStartEndTokens(); for (const Token* tok2 = startEnd.first; tok2 != startEnd.second; tok2 = tok2->next()) { if (tok2->tokType() == Token::eLambda) return Result(Result::Type::BAILOUT); // TODO: analyze usage in lambda } // ({ .. }) if (hasGccCompoundStatement(parent->astParent()->astOperand2())) return Result(Result::Type::BAILOUT); // cppcheck-suppress shadowFunction - TODO: fix this const bool reassign = isSameExpression(false, expr, parent, mSettings, false, false, nullptr); if (reassign) return Result(Result::Type::WRITE, parent->astParent()); return Result(Result::Type::READ); } if (mWhat == What::Reassign) { if (parent->variable() && parent->variable()->type() && parent->variable()->type()->isUnionType() && parent->varId() == expr->varId()) { while (parent && Token::simpleMatch(parent->astParent(), ".")) parent = parent->astParent(); if (parent && parent->valueType() && Token::simpleMatch(parent->astParent(), "=") && !Token::Match(parent->astParent()->astParent(), "%assign%") && parent->astParent()->astOperand1() == parent) { const Token * assignment = parent->astParent()->astOperand2(); while (Token::simpleMatch(assignment, ".") && assignment->varId() != expr->varId()) assignment = assignment->astOperand1(); if (assignment && assignment->varId() != expr->varId()) { if (assignment->valueType() && assignment->valueType()->pointer) // Bailout return Result(Result::Type::BAILOUT); return Result(Result::Type::WRITE, parent->astParent()); } } return Result(Result::Type::READ); } if (parent->valueType() && parent->valueType()->pointer && Token::Match(parent->astParent(), "%assign%")) return Result(Result::Type::READ); } if (Token::Match(parent->astParent(), "%assign%") && !parent->astParent()->astParent() && parent == parent->astParent()->astOperand1()) { if (mWhat == What::Reassign) return Result(Result::Type::BAILOUT, parent->astParent()); if (mWhat == What::UnusedValue && (!parent->valueType() || parent->valueType()->reference != Reference::None)) return Result(Result::Type::BAILOUT, parent->astParent()); continue; } if (mWhat == What::UnusedValue && parent->isUnaryOp("&") && Token::Match(parent->astParent(), "[,(]")) { // Pass variable to function the writes it const Token *ftok = parent->astParent(); while (Token::simpleMatch(ftok, ",")) ftok = ftok->astParent(); if (ftok && Token::Match(ftok->previous(), "%name% (")) { const std::vector<const Token *> args = getArguments(ftok); int argnr = 0; while (argnr < args.size() && args[argnr] != parent) argnr++; if (argnr < args.size()) { if (mSettings.library.getArgDirection(ftok->astOperand1(), argnr + 1) == Library::ArgumentChecks::Direction::DIR_OUT) continue; } } return Result(Result::Type::BAILOUT, parent->astParent()); } // TODO: this is a quick bailout return Result(Result::Type::BAILOUT, parent->astParent()); } if (Token::Match(tok, ")|do {")) { if (tok->str() == ")" && Token::simpleMatch(tok->link()->previous(), "switch (")) // TODO: parse switch return Result(Result::Type::BAILOUT); const Result &result1 = checkRecursive(expr, tok->tokAt(2), tok->linkAt(1), exprVarIds, local, inInnerClass, depth); if (result1.type == Result::Type::READ || result1.type == Result::Type::BAILOUT) return result1; if (mWhat == What::UnusedValue && result1.type == Result::Type::WRITE && expr->variable() && expr->variable()->isReference()) return result1; if (mWhat == What::ValueFlow && result1.type == Result::Type::WRITE) mValueFlowKnown = false; if (mWhat == What::Reassign && result1.type == Result::Type::BREAK) { const Token *scopeEndToken = findNextTokenFromBreak(result1.token); if (scopeEndToken) { const Result &result2 = checkRecursive(expr, scopeEndToken->next(), endToken, exprVarIds, local, inInnerClass, depth); if (result2.type == Result::Type::BAILOUT) return result2; } } if (Token::simpleMatch(tok->linkAt(1), "} else {")) { const Token *elseStart = tok->linkAt(1)->tokAt(2); const Result &result2 = checkRecursive(expr, elseStart, elseStart->link(), exprVarIds, local, inInnerClass, depth); if (mWhat == What::ValueFlow && result2.type == Result::Type::WRITE) mValueFlowKnown = false; if (result2.type == Result::Type::READ || result2.type == Result::Type::BAILOUT) return result2; if (result1.type == Result::Type::WRITE && result2.type == Result::Type::WRITE) return result1; tok = elseStart->link(); } else { tok = tok->linkAt(1); } } } return Result(Result::Type::NONE); } std::set<nonneg int> FwdAnalysis::getExprVarIds(const Token* expr, bool* localOut, bool* unknownVarIdOut) const { // all variable ids in expr. std::set<nonneg int> exprVarIds; bool local = true; bool unknownVarId = false; visitAstNodes(expr, [&](const Token *tok) { if (tok->str() == "[" && mWhat == What::UnusedValue) return ChildrenToVisit::op1; if (tok->varId() == 0 && tok->isName() && tok->strAt(-1) != ".") { // unknown variable unknownVarId = true; return ChildrenToVisit::none; } if (tok->varId() > 0) { exprVarIds.insert(tok->varId()); if (!Token::simpleMatch(tok->previous(), ".")) { const Variable *var = tok->variable(); if (var && var->isReference() && var->isLocal() && Token::Match(var->nameToken(), "%var% [=(]") && !isGlobalData(var->nameToken()->next()->astOperand2())) return ChildrenToVisit::none; const bool deref = tok->astParent() && (tok->astParent()->isUnaryOp("*") || (tok->astParent()->str() == "[" && tok == tok->astParent()->astOperand1())); local &= !nonLocal(tok->variable(), deref); } } return ChildrenToVisit::op1_and_op2; }); if (localOut) *localOut = local; if (unknownVarIdOut) *unknownVarIdOut = unknownVarId; return exprVarIds; } FwdAnalysis::Result FwdAnalysis::check(const Token* expr, const Token* startToken, const Token* endToken) { // all variable ids in expr. bool local = true; bool unknownVarId = false; std::set<nonneg int> exprVarIds = getExprVarIds(expr, &local, &unknownVarId); if (unknownVarId) return Result(FwdAnalysis::Result::Type::BAILOUT); if (mWhat == What::Reassign && isGlobalData(expr)) local = false; // In unused values checking we do not want to check assignments to // global data. if (mWhat == What::UnusedValue && isGlobalData(expr)) return Result(FwdAnalysis::Result::Type::BAILOUT); Result result = checkRecursive(expr, startToken, endToken, exprVarIds, local, false); // Break => continue checking in outer scope while (mWhat!=What::ValueFlow && result.type == FwdAnalysis::Result::Type::BREAK) { const Token *scopeEndToken = findNextTokenFromBreak(result.token); if (!scopeEndToken) break; result = checkRecursive(expr, scopeEndToken->next(), endToken, exprVarIds, local, false); } return result; } bool FwdAnalysis::hasOperand(const Token *tok, const Token *lhs) const { if (!tok) return false; if (isSameExpression(false, tok, lhs, mSettings, false, false, nullptr)) return true; return hasOperand(tok->astOperand1(), lhs) || hasOperand(tok->astOperand2(), lhs); } const Token *FwdAnalysis::reassign(const Token *expr, const Token *startToken, const Token *endToken) { if (hasVolatileCastOrVar(expr)) return nullptr; mWhat = What::Reassign; Result result = check(expr, startToken, endToken); return result.type == FwdAnalysis::Result::Type::WRITE ? result.token : nullptr; } bool FwdAnalysis::unusedValue(const Token *expr, const Token *startToken, const Token *endToken) { if (isEscapedAlias(expr)) return false; if (hasVolatileCastOrVar(expr)) return false; if (Token::simpleMatch(expr, "[") && astIsContainerView(expr->astOperand1())) return false; mWhat = What::UnusedValue; Result result = check(expr, startToken, endToken); return (result.type == FwdAnalysis::Result::Type::NONE || result.type == FwdAnalysis::Result::Type::RETURN) && !possiblyAliased(expr, startToken); } bool FwdAnalysis::possiblyAliased(const Token *expr, const Token *startToken) const { if (expr->isUnaryOp("*") && !expr->astOperand1()->isUnaryOp("&")) return true; if (Token::simpleMatch(expr, ". *")) return true; if (expr->str() == "(" && Token::simpleMatch(expr->astOperand1(), ".")) return true; const bool macro = false; const bool pure = false; const bool followVar = false; for (const Token *tok = startToken; tok; tok = tok->previous()) { if (Token::Match(tok, "%name% (") && !Token::Match(tok, "if|while|for")) { // Is argument passed by reference? const std::vector<const Token*> args = getArguments(tok); for (int argnr = 0; argnr < args.size(); ++argnr) { if (!Token::Match(args[argnr], "%name%|.|::")) continue; if (tok->function() && tok->function()->getArgumentVar(argnr) && !tok->function()->getArgumentVar(argnr)->isReference() && !tok->function()->isConst()) continue; for (const Token *subexpr = expr; subexpr; subexpr = subexpr->astOperand1()) { if (isSameExpression(macro, subexpr, args[argnr], mSettings, pure, followVar)) { const Scope* scope = expr->scope(); // if there is no other variable, assume no aliasing if (scope->varlist.size() > 1) return true; } } } continue; } const Token *addrOf = nullptr; if (Token::Match(tok, "& %name% =")) addrOf = tok->tokAt(2)->astOperand2(); else if (tok->isUnaryOp("&")) addrOf = tok->astOperand1(); else if (Token::simpleMatch(tok, "std :: ref (")) addrOf = tok->tokAt(3)->astOperand2(); else if (tok->valueType() && tok->valueType()->pointer && (Token::Match(tok, "%var% = %var% ;") || Token::Match(tok, "%var% {|( %var% }|)")) && Token::Match(expr->previous(), "%varid% [", tok->tokAt(2)->varId())) addrOf = tok->tokAt(2); else continue; for (const Token *subexpr = expr; subexpr; subexpr = subexpr->astOperand1()) { if (subexpr != addrOf && isSameExpression(macro, subexpr, addrOf, mSettings, pure, followVar)) return true; } } return false; } bool FwdAnalysis::isEscapedAlias(const Token* expr) { for (const Token *subexpr = expr; subexpr; subexpr = subexpr->astOperand1()) { for (const ValueFlow::Value &val : subexpr->values()) { if (!val.isLocalLifetimeValue()) continue; const Variable* var = val.tokvalue->variable(); if (!var) continue; if (!var->isLocal()) return true; if (var->isArgument()) return true; } } return false; }
26,551
C++
.cpp
524
38.314885
215
0.550037
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,142
checkers.cpp
danmar_cppcheck/lib/checkers.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // This file is auto-generated by tools/get_checkers.py: // python3 tools/get_checkers.py > lib/checkers.cpp #include "checkers.h" namespace checkers { const std::map<std::string, std::string> allCheckers{ {"CheckBool::checkIncrementBoolean","style"}, {"CheckBool::checkBitwiseOnBoolean","style,inconclusive"}, {"CheckBool::checkComparisonOfBoolWithInt","warning,c++"}, {"CheckBool::checkComparisonOfFuncReturningBool","style,c++"}, {"CheckBool::checkComparisonOfBoolWithBool","style,c++"}, {"CheckBool::checkAssignBoolToPointer",""}, {"CheckBool::checkComparisonOfBoolExpressionWithInt","warning"}, {"CheckBool::pointerArithBool",""}, {"CheckBool::checkAssignBoolToFloat","style,c++"}, {"CheckBool::returnValueOfFunctionReturningBool","style"}, {"CheckPostfixOperator::postfixOperator","performance"}, {"CheckSizeof::checkSizeofForNumericParameter","warning"}, {"CheckSizeof::checkSizeofForArrayParameter","warning"}, {"CheckSizeof::checkSizeofForPointerSize","warning"}, {"CheckSizeof::sizeofsizeof","warning"}, {"CheckSizeof::sizeofCalculation","warning"}, {"CheckSizeof::sizeofFunction","warning"}, {"CheckSizeof::suspiciousSizeofCalculation","warning,inconclusive"}, {"CheckSizeof::sizeofVoid","portability"}, {"Check64BitPortability::pointerassignment","portability"}, {"CheckStl::outOfBounds",""}, {"CheckStl::outOfBoundsIndexExpression",""}, {"CheckStl::iterators",""}, {"CheckStl::misMatchingContainers",""}, {"CheckStl::misMatchingContainerIterator",""}, {"CheckStl::invalidContainer",""}, {"CheckStl::stlOutOfBounds",""}, {"CheckStl::negativeIndex",""}, {"CheckStl::erase",""}, {"CheckStl::stlBoundaries",""}, {"CheckStl::if_find","warning,performance"}, {"CheckStl::checkFindInsert","performance"}, {"CheckStl::size","performance,c++03"}, {"CheckStl::redundantCondition","style"}, {"CheckStl::missingComparison","warning"}, {"CheckStl::string_c_str",""}, {"CheckStl::uselessCalls","performance,warning"}, {"CheckStl::checkDereferenceInvalidIterator","warning"}, {"CheckStl::checkDereferenceInvalidIterator2",""}, {"CheckStl::useStlAlgorithm","style"}, {"CheckStl::knownEmptyContainer","style"}, {"CheckStl::eraseIteratorOutOfBounds",""}, {"CheckStl::checkMutexes","warning"}, {"CheckBoost::checkBoostForeachModification",""}, {"CheckNullPointer::nullPointer",""}, {"CheckNullPointer::nullConstantDereference",""}, {"CheckNullPointer::arithmetic",""}, {"CheckNullPointer::analyseWholeProgram","unusedfunctions"}, {"CheckBufferOverrun::arrayIndex",""}, {"CheckBufferOverrun::pointerArithmetic","portability"}, {"CheckBufferOverrun::bufferOverflow",""}, {"CheckBufferOverrun::arrayIndexThenCheck",""}, {"CheckBufferOverrun::stringNotZeroTerminated","warning,inconclusive"}, {"CheckBufferOverrun::argumentSize","warning"}, {"CheckBufferOverrun::analyseWholeProgram",""}, {"CheckBufferOverrun::objectIndex",""}, {"CheckBufferOverrun::negativeArraySize",""}, {"CheckUninitVar::check",""}, {"CheckUninitVar::valueFlowUninit",""}, {"CheckOther::checkCastIntToCharAndBack","warning"}, {"CheckOther::clarifyCalculation","style"}, {"CheckOther::clarifyStatement","warning"}, {"CheckOther::checkSuspiciousSemicolon","warning,inconclusive"}, {"CheckOther::warningOldStylePointerCast","style,c++"}, {"CheckOther::suspiciousFloatingPointCast","style"}, {"CheckOther::invalidPointerCast","portability"}, {"CheckOther::checkRedundantAssignment","style"}, {"CheckOther::redundantBitwiseOperationInSwitch","warning"}, {"CheckOther::checkSuspiciousCaseInSwitch","warning,inconclusive"}, {"CheckOther::checkUnreachableCode","style"}, {"CheckOther::checkVariableScope","style,notclang"}, {"CheckOther::checkPassByReference","performance,c++"}, {"CheckOther::checkConstVariable","style,c++"}, {"CheckOther::checkConstPointer","style"}, {"CheckOther::checkCharVariable","warning,portability"}, {"CheckOther::checkIncompleteStatement","warning"}, {"CheckOther::checkZeroDivision",""}, {"CheckOther::checkNanInArithmeticExpression","style"}, {"CheckOther::checkMisusedScopedObject","style,c++"}, {"CheckOther::checkDuplicateBranch","style,inconclusive"}, {"CheckOther::checkInvalidFree",""}, {"CheckOther::checkDuplicateExpression","style,warning"}, {"CheckOther::checkComparisonFunctionIsAlwaysTrueOrFalse","warning"}, {"CheckOther::checkSignOfUnsignedVariable","style"}, {"CheckOther::checkRedundantCopy","c++,performance,inconclusive"}, {"CheckOther::checkNegativeBitwiseShift",""}, {"CheckOther::checkIncompleteArrayFill","warning,portability,inconclusive"}, {"CheckOther::checkVarFuncNullUB","portability"}, {"CheckOther::checkRedundantPointerOp","style"}, {"CheckOther::checkInterlockedDecrement","windows-platform"}, {"CheckOther::checkUnusedLabel","style,warning"}, {"CheckOther::checkEvaluationOrder",""}, {"CheckOther::checkAccessOfMovedVariable","c++11,warning"}, {"CheckOther::checkFuncArgNamesDifferent","style,warning,inconclusive"}, {"CheckOther::checkShadowVariables","style"}, {"CheckOther::checkKnownArgument","style"}, {"CheckOther::checkKnownPointerToBool","style"}, {"CheckOther::checkComparePointers",""}, {"CheckOther::checkModuloOfOne","style"}, {"CheckOther::checkOverlappingWrite",""}, {"CheckClass::checkConstructors","style,warning"}, {"CheckClass::checkExplicitConstructors","style"}, {"CheckClass::checkCopyConstructors","warning"}, {"CheckClass::initializationListUsage","performance"}, {"CheckClass::privateFunctions","style"}, {"CheckClass::checkMemset",""}, {"CheckClass::operatorEqRetRefThis","style"}, {"CheckClass::operatorEqToSelf","warning"}, {"CheckClass::virtualDestructor",""}, {"CheckClass::thisSubtraction","warning"}, {"CheckClass::checkConst","style,inconclusive"}, {"CheckClass::initializerListOrder","style,inconclusive"}, {"CheckClass::checkSelfInitialization",""}, {"CheckClass::checkVirtualFunctionCallInConstructor","warning"}, {"CheckClass::checkDuplInheritedMembers","warning"}, {"CheckClass::checkMissingOverride","style,c++03"}, {"CheckClass::checkUselessOverride","style"}, {"CheckClass::checkReturnByReference","performance"}, {"CheckClass::checkThisUseAfterFree","warning"}, {"CheckClass::checkUnsafeClassRefMember","warning,safeChecks"}, {"CheckClass::analyseWholeProgram",""}, {"CheckUnusedVar::checkFunctionVariableUsage","style"}, {"CheckUnusedVar::checkStructMemberUsage","style"}, {"CheckIO::checkCoutCerrMisusage","c"}, {"CheckIO::checkFileUsage",""}, {"CheckIO::invalidScanf",""}, {"CheckIO::checkWrongPrintfScanfArguments",""}, {"CheckCondition::assignIf","style"}, {"CheckCondition::checkBadBitmaskCheck","style"}, {"CheckCondition::comparison","style"}, {"CheckCondition::duplicateCondition","style"}, {"CheckCondition::multiCondition","style"}, {"CheckCondition::multiCondition2","warning"}, {"CheckCondition::checkIncorrectLogicOperator","style,warning"}, {"CheckCondition::checkModuloAlwaysTrueFalse","warning"}, {"CheckCondition::clarifyCondition","style"}, {"CheckCondition::alwaysTrueFalse","style"}, {"CheckCondition::checkInvalidTestForOverflow","warning"}, {"CheckCondition::checkPointerAdditionResultNotNull","warning"}, {"CheckCondition::checkDuplicateConditionalAssign","style"}, {"CheckCondition::checkAssignmentInCondition","style"}, {"CheckCondition::checkCompareValueOutOfTypeRange","style,platform"}, {"CheckFunctions::checkProhibitedFunctions",""}, {"CheckFunctions::invalidFunctionUsage",""}, {"CheckFunctions::checkIgnoredReturnValue","style,warning"}, {"CheckFunctions::checkMissingReturn",""}, {"CheckFunctions::checkMathFunctions","style,warning,c99,c++11"}, {"CheckFunctions::memsetZeroBytes","warning"}, {"CheckFunctions::memsetInvalid2ndParam","warning,portability"}, {"CheckFunctions::returnLocalStdMove","performance,c++11"}, {"CheckFunctions::useStandardLibrary","style"}, {"CheckVaarg::va_start_argument",""}, {"CheckVaarg::va_list_usage","notclang"}, {"CheckUnusedFunctions::check","unusedFunction"}, {"CheckType::checkTooBigBitwiseShift","platform"}, {"CheckType::checkIntegerOverflow","platform"}, {"CheckType::checkSignConversion","warning"}, {"CheckType::checkLongCast","style"}, {"CheckType::checkFloatToIntegerOverflow",""}, {"CheckString::stringLiteralWrite",""}, {"CheckString::checkAlwaysTrueOrFalseStringCompare","warning"}, {"CheckString::checkSuspiciousStringCompare","warning"}, {"CheckString::strPlusChar",""}, {"CheckString::checkIncorrectStringCompare","warning"}, {"CheckString::overlappingStrcmp","warning"}, {"CheckString::sprintfOverlappingData",""}, {"CheckAssert::assertWithSideEffects","warning"}, {"CheckExceptionSafety::destructors","warning"}, {"CheckExceptionSafety::deallocThrow","warning"}, {"CheckExceptionSafety::checkRethrowCopy","style"}, {"CheckExceptionSafety::checkCatchExceptionByValue","style"}, {"CheckExceptionSafety::nothrowThrows",""}, {"CheckExceptionSafety::unhandledExceptionSpecification","style,inconclusive"}, {"CheckExceptionSafety::rethrowNoCurrentException",""}, {"CheckAutoVariables::assignFunctionArg","style,warning"}, {"CheckAutoVariables::autoVariables",""}, {"CheckAutoVariables::checkVarLifetime",""}, {"CheckLeakAutoVar::check","notclang"}, {"CheckMemoryLeakInFunction::checkReallocUsage",""}, {"CheckMemoryLeakInClass::check",""}, {"CheckMemoryLeakStructMember::check",""}, {"CheckMemoryLeakNoVar::check",""}, {"CheckMemoryLeakNoVar::checkForUnsafeArgAlloc",""}, }; const std::map<std::string, std::string> premiumCheckers{ {"Autosar: A0-1-3",""}, {"Autosar: A0-1-4",""}, {"Autosar: A0-1-5",""}, {"Autosar: A0-1-6",""}, {"Autosar: A0-4-2",""}, {"Autosar: A0-4-4",""}, {"Autosar: A10-1-1",""}, {"Autosar: A11-0-2",""}, {"Autosar: A11-3-1",""}, {"Autosar: A13-2-1",""}, {"Autosar: A13-2-3",""}, {"Autosar: A13-5-2",""}, {"Autosar: A13-5-5",""}, {"Autosar: A15-1-2",""}, {"Autosar: A15-3-5",""}, {"Autosar: A16-6-1",""}, {"Autosar: A16-7-1",""}, {"Autosar: A18-0-3",""}, {"Autosar: A18-1-1",""}, {"Autosar: A18-1-2",""}, {"Autosar: A18-1-3",""}, {"Autosar: A18-5-1",""}, {"Autosar: A18-9-1",""}, {"Autosar: A2-11-1",""}, {"Autosar: A2-13-1",""}, {"Autosar: A2-13-3",""}, {"Autosar: A2-13-5",""}, {"Autosar: A2-5-2",""}, {"Autosar: A2-7-1",""}, {"Autosar: A20-8-2","warning"}, {"Autosar: A20-8-3","warning"}, {"Autosar: A20-8-4",""}, {"Autosar: A20-8-5",""}, {"Autosar: A20-8-6",""}, {"Autosar: A21-8-1","warning"}, {"Autosar: A23-0-1",""}, {"Autosar: A25-1-1","warning"}, {"Autosar: A25-4-1","warning"}, {"Autosar: A26-5-1",""}, {"Autosar: A26-5-2",""}, {"Autosar: A27-0-1","warning"}, {"Autosar: A27-0-2",""}, {"Autosar: A27-0-4",""}, {"Autosar: A3-1-3",""}, {"Autosar: A3-1-4",""}, {"Autosar: A3-3-1",""}, {"Autosar: A3-9-1",""}, {"Autosar: A4-10-1",""}, {"Autosar: A4-7-1",""}, {"Autosar: A5-0-2",""}, {"Autosar: A5-0-3",""}, {"Autosar: A5-0-4",""}, {"Autosar: A5-1-1",""}, {"Autosar: A5-1-2",""}, {"Autosar: A5-1-3",""}, {"Autosar: A5-1-6",""}, {"Autosar: A5-1-7",""}, {"Autosar: A5-16-1",""}, {"Autosar: A5-2-1",""}, {"Autosar: A5-2-3",""}, {"Autosar: A5-2-4",""}, {"Autosar: A5-3-3",""}, {"Autosar: A6-5-3",""}, {"Autosar: A7-1-4",""}, {"Autosar: A7-1-6",""}, {"Autosar: A7-1-7",""}, {"Autosar: A7-2-1",""}, {"Autosar: A7-2-2",""}, {"Autosar: A7-6-1",""}, {"Autosar: A8-4-1",""}, {"Autosar: A8-5-3",""}, {"Autosar: A9-3-1",""}, {"Cert C++: CON50-CPP",""}, {"Cert C++: CON51-CPP",""}, {"Cert C++: CON52-CPP",""}, {"Cert C++: CON53-CPP",""}, {"Cert C++: CON54-CPP",""}, {"Cert C++: CON55-CPP",""}, {"Cert C++: CON56-CPP",""}, {"Cert C++: CTR50-CPP",""}, {"Cert C++: CTR52-CPP",""}, {"Cert C++: CTR53-CPP",""}, {"Cert C++: CTR56-CPP",""}, {"Cert C++: CTR57-CPP","warning"}, {"Cert C++: CTR58-CPP","warning"}, {"Cert C++: DCL50-CPP",""}, {"Cert C++: DCL51-CPP",""}, {"Cert C++: DCL52-CPP",""}, {"Cert C++: DCL53-CPP",""}, {"Cert C++: DCL54-CPP",""}, {"Cert C++: DCL56-CPP",""}, {"Cert C++: DCL58-CPP",""}, {"Cert C++: DCL59-CPP",""}, {"Cert C++: ERR50-CPP",""}, {"Cert C++: ERR51-CPP",""}, {"Cert C++: ERR52-CPP",""}, {"Cert C++: ERR53-CPP",""}, {"Cert C++: ERR54-CPP",""}, {"Cert C++: ERR55-CPP",""}, {"Cert C++: ERR56-CPP",""}, {"Cert C++: ERR58-CPP",""}, {"Cert C++: ERR59-CPP","warning"}, {"Cert C++: ERR60-CPP","warning"}, {"Cert C++: ERR61-CPP",""}, {"Cert C++: ERR62-CPP",""}, {"Cert C++: EXP50-CPP",""}, {"Cert C++: EXP51-CPP",""}, {"Cert C++: EXP55-CPP",""}, {"Cert C++: EXP56-CPP",""}, {"Cert C++: EXP57-CPP",""}, {"Cert C++: EXP58-CPP",""}, {"Cert C++: EXP59-CPP",""}, {"Cert C++: EXP60-CPP",""}, {"Cert C++: FIO51-CPP",""}, {"Cert C++: INT50-CPP",""}, {"Cert C++: MEM52-CPP",""}, {"Cert C++: MEM53-CPP",""}, {"Cert C++: MEM54-CPP",""}, {"Cert C++: MEM55-CPP",""}, {"Cert C++: MEM57-CPP",""}, {"Cert C++: MSC50-CPP",""}, {"Cert C++: MSC51-CPP",""}, {"Cert C++: MSC53-CPP",""}, {"Cert C++: MSC54-CPP",""}, {"Cert C++: OOP51-CPP",""}, {"Cert C++: OOP55-CPP",""}, {"Cert C++: OOP56-CPP",""}, {"Cert C++: OOP57-CPP",""}, {"Cert C++: OOP58-CPP",""}, {"Cert C++: STR50-CPP",""}, {"Cert C++: STR53-CPP",""}, {"Cert C: ARR30-C",""}, {"Cert C: ARR32-C",""}, {"Cert C: ARR37-C",""}, {"Cert C: ARR38-C",""}, {"Cert C: ARR39-C",""}, {"Cert C: CON30-C",""}, {"Cert C: CON31-C",""}, {"Cert C: CON32-C",""}, {"Cert C: CON33-C",""}, {"Cert C: CON34-C",""}, {"Cert C: CON35-C",""}, {"Cert C: CON36-C",""}, {"Cert C: CON37-C",""}, {"Cert C: CON38-C",""}, {"Cert C: CON39-C",""}, {"Cert C: CON40-C",""}, {"Cert C: CON41-C",""}, {"Cert C: DCL31-C",""}, {"Cert C: DCL36-C",""}, {"Cert C: DCL37-C",""}, {"Cert C: DCL38-C",""}, {"Cert C: DCL39-C",""}, {"Cert C: DCL40-C",""}, {"Cert C: DCL41-C",""}, {"Cert C: ENV30-C",""}, {"Cert C: ENV31-C",""}, {"Cert C: ENV32-C",""}, {"Cert C: ENV33-C",""}, {"Cert C: ENV34-C",""}, {"Cert C: ERR30-C",""}, {"Cert C: ERR32-C",""}, {"Cert C: ERR33-C",""}, {"Cert C: EXP03-C",""}, {"Cert C: EXP05-C",""}, {"Cert C: EXP09-C",""}, {"Cert C: EXP13-C",""}, {"Cert C: EXP15-C",""}, {"Cert C: EXP19-C",""}, {"Cert C: EXP32-C",""}, {"Cert C: EXP35-C",""}, {"Cert C: EXP36-C",""}, {"Cert C: EXP37-C",""}, {"Cert C: EXP39-C",""}, {"Cert C: EXP40-C",""}, {"Cert C: EXP42-C",""}, {"Cert C: EXP43-C",""}, {"Cert C: EXP45-C",""}, {"Cert C: FIO30-C",""}, {"Cert C: FIO32-C",""}, {"Cert C: FIO34-C",""}, {"Cert C: FIO37-C",""}, {"Cert C: FIO38-C",""}, {"Cert C: FIO40-C",""}, {"Cert C: FIO41-C",""}, {"Cert C: FIO44-C",""}, {"Cert C: FIO45-C",""}, {"Cert C: FLP30-C",""}, {"Cert C: FLP36-C","portability"}, {"Cert C: FLP37-C",""}, {"Cert C: INT30-C",""}, {"Cert C: INT31-C",""}, {"Cert C: INT32-C",""}, {"Cert C: INT33-C",""}, {"Cert C: INT34-C",""}, {"Cert C: INT35-C",""}, {"Cert C: INT36-C",""}, {"Cert C: MEM33-C",""}, {"Cert C: MEM35-C",""}, {"Cert C: MEM36-C",""}, {"Cert C: MSC30-C",""}, {"Cert C: MSC32-C",""}, {"Cert C: MSC33-C",""}, {"Cert C: MSC38-C",""}, {"Cert C: MSC39-C",""}, {"Cert C: MSC40-C",""}, {"Cert C: PRE31-C",""}, {"Cert C: SIG30-C",""}, {"Cert C: SIG31-C",""}, {"Cert C: SIG34-C",""}, {"Cert C: SIG35-C",""}, {"Cert C: STR31-C",""}, {"Cert C: STR32-C",""}, {"Cert C: STR34-C",""}, {"Cert C: STR38-C",""}, {"Misra C++ 2008: 3-2-3",""}, {"Misra C++ 2008: 3-2-4",""}, {"Misra C++ 2008: 7-5-4",""}, {"Misra C++ 2008: M0-1-11",""}, {"Misra C++ 2008: M0-1-12",""}, {"Misra C++ 2008: M0-1-4",""}, {"Misra C++ 2008: M0-1-5",""}, {"Misra C++ 2008: M0-1-7",""}, {"Misra C++ 2008: M0-1-8",""}, {"Misra C++ 2008: M0-3-2",""}, {"Misra C++ 2008: M1-0-1","portability"}, {"Misra C++ 2008: M10-1-1",""}, {"Misra C++ 2008: M10-1-2",""}, {"Misra C++ 2008: M10-1-3",""}, {"Misra C++ 2008: M10-2-1",""}, {"Misra C++ 2008: M10-3-1",""}, {"Misra C++ 2008: M10-3-2",""}, {"Misra C++ 2008: M10-3-3",""}, {"Misra C++ 2008: M11-0-1",""}, {"Misra C++ 2008: M12-1-2",""}, {"Misra C++ 2008: M12-8-1",""}, {"Misra C++ 2008: M12-8-2",""}, {"Misra C++ 2008: M14-5-1","warning"}, {"Misra C++ 2008: M14-5-2","warning"}, {"Misra C++ 2008: M14-5-3","warning"}, {"Misra C++ 2008: M14-6-1","warning"}, {"Misra C++ 2008: M14-6-2","warning"}, {"Misra C++ 2008: M14-7-1",""}, {"Misra C++ 2008: M14-7-2",""}, {"Misra C++ 2008: M14-7-3",""}, {"Misra C++ 2008: M14-8-1",""}, {"Misra C++ 2008: M14-8-2",""}, {"Misra C++ 2008: M15-0-3",""}, {"Misra C++ 2008: M15-1-1",""}, {"Misra C++ 2008: M15-1-2",""}, {"Misra C++ 2008: M15-1-3",""}, {"Misra C++ 2008: M15-3-2","warning"}, {"Misra C++ 2008: M15-3-3",""}, {"Misra C++ 2008: M15-3-4",""}, {"Misra C++ 2008: M15-3-6",""}, {"Misra C++ 2008: M15-3-7",""}, {"Misra C++ 2008: M15-4-1",""}, {"Misra C++ 2008: M15-5-2",""}, {"Misra C++ 2008: M16-0-1",""}, {"Misra C++ 2008: M16-0-2",""}, {"Misra C++ 2008: M16-0-3",""}, {"Misra C++ 2008: M16-0-4",""}, {"Misra C++ 2008: M16-0-6",""}, {"Misra C++ 2008: M16-0-7",""}, {"Misra C++ 2008: M16-0-8",""}, {"Misra C++ 2008: M16-1-1",""}, {"Misra C++ 2008: M16-1-2",""}, {"Misra C++ 2008: M16-2-1",""}, {"Misra C++ 2008: M16-2-2",""}, {"Misra C++ 2008: M16-2-3",""}, {"Misra C++ 2008: M16-2-4",""}, {"Misra C++ 2008: M16-2-5",""}, {"Misra C++ 2008: M16-2-6",""}, {"Misra C++ 2008: M16-3-1",""}, {"Misra C++ 2008: M16-3-2",""}, {"Misra C++ 2008: M17-0-1",""}, {"Misra C++ 2008: M17-0-2",""}, {"Misra C++ 2008: M17-0-3",""}, {"Misra C++ 2008: M17-0-5",""}, {"Misra C++ 2008: M18-0-1",""}, {"Misra C++ 2008: M18-0-2",""}, {"Misra C++ 2008: M18-0-3",""}, {"Misra C++ 2008: M18-0-4",""}, {"Misra C++ 2008: M18-0-5",""}, {"Misra C++ 2008: M18-2-1",""}, {"Misra C++ 2008: M18-4-1",""}, {"Misra C++ 2008: M18-7-1",""}, {"Misra C++ 2008: M19-3-1",""}, {"Misra C++ 2008: M2-10-1",""}, {"Misra C++ 2008: M2-10-3",""}, {"Misra C++ 2008: M2-10-4",""}, {"Misra C++ 2008: M2-10-5",""}, {"Misra C++ 2008: M2-10-6",""}, {"Misra C++ 2008: M2-13-2",""}, {"Misra C++ 2008: M2-13-3",""}, {"Misra C++ 2008: M2-13-4",""}, {"Misra C++ 2008: M2-13-5",""}, {"Misra C++ 2008: M2-3-1",""}, {"Misra C++ 2008: M2-7-1",""}, {"Misra C++ 2008: M2-7-2",""}, {"Misra C++ 2008: M2-7-3",""}, {"Misra C++ 2008: M27-0-1",""}, {"Misra C++ 2008: M3-1-1",""}, {"Misra C++ 2008: M3-1-2",""}, {"Misra C++ 2008: M3-1-3",""}, {"Misra C++ 2008: M3-2-1",""}, {"Misra C++ 2008: M3-3-1",""}, {"Misra C++ 2008: M3-3-2",""}, {"Misra C++ 2008: M3-9-1",""}, {"Misra C++ 2008: M3-9-2",""}, {"Misra C++ 2008: M3-9-3",""}, {"Misra C++ 2008: M4-10-1",""}, {"Misra C++ 2008: M4-10-2",""}, {"Misra C++ 2008: M4-5-1",""}, {"Misra C++ 2008: M4-5-2",""}, {"Misra C++ 2008: M4-5-3",""}, {"Misra C++ 2008: M5-0-10",""}, {"Misra C++ 2008: M5-0-11",""}, {"Misra C++ 2008: M5-0-12",""}, {"Misra C++ 2008: M5-0-14",""}, {"Misra C++ 2008: M5-0-15",""}, {"Misra C++ 2008: M5-0-2",""}, {"Misra C++ 2008: M5-0-20",""}, {"Misra C++ 2008: M5-0-21",""}, {"Misra C++ 2008: M5-0-3",""}, {"Misra C++ 2008: M5-0-4",""}, {"Misra C++ 2008: M5-0-5",""}, {"Misra C++ 2008: M5-0-6",""}, {"Misra C++ 2008: M5-0-7",""}, {"Misra C++ 2008: M5-0-8",""}, {"Misra C++ 2008: M5-0-9",""}, {"Misra C++ 2008: M5-14-1",""}, {"Misra C++ 2008: M5-17-1",""}, {"Misra C++ 2008: M5-18-1",""}, {"Misra C++ 2008: M5-19-1",""}, {"Misra C++ 2008: M5-2-1",""}, {"Misra C++ 2008: M5-2-10",""}, {"Misra C++ 2008: M5-2-11",""}, {"Misra C++ 2008: M5-2-12",""}, {"Misra C++ 2008: M5-2-2",""}, {"Misra C++ 2008: M5-2-3",""}, {"Misra C++ 2008: M5-2-5",""}, {"Misra C++ 2008: M5-2-6",""}, {"Misra C++ 2008: M5-2-7",""}, {"Misra C++ 2008: M5-2-8",""}, {"Misra C++ 2008: M5-2-9",""}, {"Misra C++ 2008: M5-3-1",""}, {"Misra C++ 2008: M5-3-2",""}, {"Misra C++ 2008: M5-3-3",""}, {"Misra C++ 2008: M6-2-1",""}, {"Misra C++ 2008: M6-2-2",""}, {"Misra C++ 2008: M6-2-3",""}, {"Misra C++ 2008: M6-3-1",""}, {"Misra C++ 2008: M6-4-1",""}, {"Misra C++ 2008: M6-4-2",""}, {"Misra C++ 2008: M6-4-3",""}, {"Misra C++ 2008: M6-4-4",""}, {"Misra C++ 2008: M6-4-5",""}, {"Misra C++ 2008: M6-4-6",""}, {"Misra C++ 2008: M6-4-7",""}, {"Misra C++ 2008: M6-4-8",""}, {"Misra C++ 2008: M6-5-1",""}, {"Misra C++ 2008: M6-5-2",""}, {"Misra C++ 2008: M6-5-3",""}, {"Misra C++ 2008: M6-5-4",""}, {"Misra C++ 2008: M6-5-5",""}, {"Misra C++ 2008: M6-5-6",""}, {"Misra C++ 2008: M6-6-1",""}, {"Misra C++ 2008: M6-6-2",""}, {"Misra C++ 2008: M6-6-3",""}, {"Misra C++ 2008: M6-6-4",""}, {"Misra C++ 2008: M6-6-5",""}, {"Misra C++ 2008: M7-2-1",""}, {"Misra C++ 2008: M7-3-1",""}, {"Misra C++ 2008: M7-3-2",""}, {"Misra C++ 2008: M7-3-3",""}, {"Misra C++ 2008: M7-3-4",""}, {"Misra C++ 2008: M7-3-5",""}, {"Misra C++ 2008: M7-3-6",""}, {"Misra C++ 2008: M7-4-2",""}, {"Misra C++ 2008: M7-4-3",""}, {"Misra C++ 2008: M7-5-3",""}, {"Misra C++ 2008: M8-0-1",""}, {"Misra C++ 2008: M8-3-1",""}, {"Misra C++ 2008: M8-4-4",""}, {"Misra C++ 2008: M8-5-2",""}, {"Misra C++ 2008: M8-5-3",""}, {"Misra C++ 2008: M9-3-1",""}, {"Misra C++ 2008: M9-5-1",""}, {"Misra C++ 2008: M9-6-2",""}, {"Misra C++ 2008: M9-6-3",""}, {"Misra C++ 2008: M9-6-4",""}, {"Misra C++ 2023: 0.1.2",""}, {"Misra C++ 2023: 0.2.1",""}, {"Misra C++ 2023: 0.2.2",""}, {"Misra C++ 2023: 0.2.3",""}, {"Misra C++ 2023: 0.2.4",""}, {"Misra C++ 2023: 10.0.1",""}, {"Misra C++ 2023: 10.1.2",""}, {"Misra C++ 2023: 10.2.1",""}, {"Misra C++ 2023: 10.2.2",""}, {"Misra C++ 2023: 10.2.3",""}, {"Misra C++ 2023: 10.3.1",""}, {"Misra C++ 2023: 10.4.1",""}, {"Misra C++ 2023: 11.3.1",""}, {"Misra C++ 2023: 11.3.2",""}, {"Misra C++ 2023: 11.6.1",""}, {"Misra C++ 2023: 11.6.3",""}, {"Misra C++ 2023: 12.2.1",""}, {"Misra C++ 2023: 12.2.2",""}, {"Misra C++ 2023: 12.2.3",""}, {"Misra C++ 2023: 12.3.1",""}, {"Misra C++ 2023: 13.1.1",""}, {"Misra C++ 2023: 13.1.2",""}, {"Misra C++ 2023: 13.3.1",""}, {"Misra C++ 2023: 13.3.2",""}, {"Misra C++ 2023: 13.3.3",""}, {"Misra C++ 2023: 13.3.4",""}, {"Misra C++ 2023: 14.1.1",""}, {"Misra C++ 2023: 15.0.1",""}, {"Misra C++ 2023: 15.0.2",""}, {"Misra C++ 2023: 15.1.2",""}, {"Misra C++ 2023: 15.1.3",""}, {"Misra C++ 2023: 15.1.5",""}, {"Misra C++ 2023: 16.5.1",""}, {"Misra C++ 2023: 16.5.2",""}, {"Misra C++ 2023: 16.6.1",""}, {"Misra C++ 2023: 17.8.1",""}, {"Misra C++ 2023: 18.1.1",""}, {"Misra C++ 2023: 18.1.2",""}, {"Misra C++ 2023: 18.3.1",""}, {"Misra C++ 2023: 18.3.2",""}, {"Misra C++ 2023: 18.3.3",""}, {"Misra C++ 2023: 18.4.1",""}, {"Misra C++ 2023: 18.5.1",""}, {"Misra C++ 2023: 18.5.2",""}, {"Misra C++ 2023: 19.0.1",""}, {"Misra C++ 2023: 19.0.2",""}, {"Misra C++ 2023: 19.0.3",""}, {"Misra C++ 2023: 19.0.4",""}, {"Misra C++ 2023: 19.1.1",""}, {"Misra C++ 2023: 19.1.2",""}, {"Misra C++ 2023: 19.1.3",""}, {"Misra C++ 2023: 19.2.1",""}, {"Misra C++ 2023: 19.2.2",""}, {"Misra C++ 2023: 19.2.3",""}, {"Misra C++ 2023: 19.3.1",""}, {"Misra C++ 2023: 19.3.2",""}, {"Misra C++ 2023: 19.3.3",""}, {"Misra C++ 2023: 19.3.4",""}, {"Misra C++ 2023: 19.6.1",""}, {"Misra C++ 2023: 21.10.1",""}, {"Misra C++ 2023: 21.10.2",""}, {"Misra C++ 2023: 21.10.3",""}, {"Misra C++ 2023: 21.2.1",""}, {"Misra C++ 2023: 21.2.2",""}, {"Misra C++ 2023: 21.2.3",""}, {"Misra C++ 2023: 21.2.4",""}, {"Misra C++ 2023: 21.6.1",""}, {"Misra C++ 2023: 21.6.2",""}, {"Misra C++ 2023: 21.6.3",""}, {"Misra C++ 2023: 21.6.4",""}, {"Misra C++ 2023: 21.6.5",""}, {"Misra C++ 2023: 22.3.1",""}, {"Misra C++ 2023: 22.4.1",""}, {"Misra C++ 2023: 23.11.1",""}, {"Misra C++ 2023: 24.5.1",""}, {"Misra C++ 2023: 24.5.2",""}, {"Misra C++ 2023: 25.5.1",""}, {"Misra C++ 2023: 25.5.2",""}, {"Misra C++ 2023: 25.5.3",""}, {"Misra C++ 2023: 26.3.1",""}, {"Misra C++ 2023: 28.3.1",""}, {"Misra C++ 2023: 28.6.1",""}, {"Misra C++ 2023: 28.6.2",""}, {"Misra C++ 2023: 30.0.1",""}, {"Misra C++ 2023: 30.0.2",""}, {"Misra C++ 2023: 4.1.1",""}, {"Misra C++ 2023: 4.1.2",""}, {"Misra C++ 2023: 5.0.1",""}, {"Misra C++ 2023: 5.10.1",""}, {"Misra C++ 2023: 5.13.1",""}, {"Misra C++ 2023: 5.13.2",""}, {"Misra C++ 2023: 5.13.3",""}, {"Misra C++ 2023: 5.13.4",""}, {"Misra C++ 2023: 5.13.5",""}, {"Misra C++ 2023: 5.13.6",""}, {"Misra C++ 2023: 5.13.7",""}, {"Misra C++ 2023: 5.7.1",""}, {"Misra C++ 2023: 5.7.2",""}, {"Misra C++ 2023: 5.7.3",""}, {"Misra C++ 2023: 6.0.1",""}, {"Misra C++ 2023: 6.0.2",""}, {"Misra C++ 2023: 6.0.3",""}, {"Misra C++ 2023: 6.0.4",""}, {"Misra C++ 2023: 6.2.2",""}, {"Misra C++ 2023: 6.2.3",""}, {"Misra C++ 2023: 6.2.4",""}, {"Misra C++ 2023: 6.4.2",""}, {"Misra C++ 2023: 6.4.3",""}, {"Misra C++ 2023: 6.5.1",""}, {"Misra C++ 2023: 6.5.2",""}, {"Misra C++ 2023: 6.7.1",""}, {"Misra C++ 2023: 6.7.2",""}, {"Misra C++ 2023: 6.8.3",""}, {"Misra C++ 2023: 6.8.4",""}, {"Misra C++ 2023: 6.9.1",""}, {"Misra C++ 2023: 6.9.2",""}, {"Misra C++ 2023: 7.0.1",""}, {"Misra C++ 2023: 7.0.2",""}, {"Misra C++ 2023: 7.0.3",""}, {"Misra C++ 2023: 7.0.4",""}, {"Misra C++ 2023: 7.0.5",""}, {"Misra C++ 2023: 7.0.6",""}, {"Misra C++ 2023: 7.11.1",""}, {"Misra C++ 2023: 7.11.2",""}, {"Misra C++ 2023: 7.11.3",""}, {"Misra C++ 2023: 8.0.1",""}, {"Misra C++ 2023: 8.1.1",""}, {"Misra C++ 2023: 8.1.2",""}, {"Misra C++ 2023: 8.14.1",""}, {"Misra C++ 2023: 8.18.2",""}, {"Misra C++ 2023: 8.19.1",""}, {"Misra C++ 2023: 8.2.1",""}, {"Misra C++ 2023: 8.2.10",""}, {"Misra C++ 2023: 8.2.11",""}, {"Misra C++ 2023: 8.2.2",""}, {"Misra C++ 2023: 8.2.3",""}, {"Misra C++ 2023: 8.2.4",""}, {"Misra C++ 2023: 8.2.5",""}, {"Misra C++ 2023: 8.2.6",""}, {"Misra C++ 2023: 8.2.7",""}, {"Misra C++ 2023: 8.2.8",""}, {"Misra C++ 2023: 8.2.9",""}, {"Misra C++ 2023: 8.20.1",""}, {"Misra C++ 2023: 8.3.1",""}, {"Misra C++ 2023: 8.3.2",""}, {"Misra C++ 2023: 9.2.1",""}, {"Misra C++ 2023: 9.3.1",""}, {"Misra C++ 2023: 9.4.1",""}, {"Misra C++ 2023: 9.4.2",""}, {"Misra C++ 2023: 9.5.1",""}, {"Misra C++ 2023: 9.5.2",""}, {"Misra C++ 2023: 9.6.1",""}, {"Misra C++ 2023: 9.6.2",""}, {"Misra C++ 2023: 9.6.3",""}, {"Misra C++ 2023: 9.6.4",""}, {"Misra C: 1.4",""}, {"Misra C: 1.5",""}, {"Misra C: 10.1",""}, {"Misra C: 10.2",""}, {"Misra C: 10.3",""}, {"Misra C: 10.4",""}, {"Misra C: 10.5",""}, {"Misra C: 10.6",""}, {"Misra C: 10.7",""}, {"Misra C: 10.8",""}, {"Misra C: 11.1",""}, {"Misra C: 11.10",""}, {"Misra C: 11.2",""}, {"Misra C: 11.3",""}, {"Misra C: 11.4",""}, {"Misra C: 11.8",""}, {"Misra C: 12.3",""}, {"Misra C: 12.6",""}, {"Misra C: 13.1",""}, {"Misra C: 13.2",""}, {"Misra C: 13.3",""}, {"Misra C: 13.4",""}, {"Misra C: 13.5",""}, {"Misra C: 13.6",""}, {"Misra C: 15.5",""}, {"Misra C: 16.3",""}, {"Misra C: 17.10",""}, {"Misra C: 17.11",""}, {"Misra C: 17.12",""}, {"Misra C: 17.13",""}, {"Misra C: 17.2",""}, {"Misra C: 17.3",""}, {"Misra C: 17.4",""}, {"Misra C: 17.9",""}, {"Misra C: 18.10",""}, {"Misra C: 18.5",""}, {"Misra C: 18.8",""}, {"Misra C: 18.9",""}, {"Misra C: 20.3",""}, {"Misra C: 21.1",""}, {"Misra C: 21.12",""}, {"Misra C: 21.16",""}, {"Misra C: 21.2",""}, {"Misra C: 21.20",""}, {"Misra C: 21.22",""}, {"Misra C: 21.23",""}, {"Misra C: 21.24",""}, {"Misra C: 21.25","warning"}, {"Misra C: 21.26","warning"}, {"Misra C: 22.11",""}, {"Misra C: 22.12",""}, {"Misra C: 22.13",""}, {"Misra C: 22.14",""}, {"Misra C: 22.15",""}, {"Misra C: 22.16","warning"}, {"Misra C: 22.17","warning"}, {"Misra C: 22.18","warning"}, {"Misra C: 22.19","warning"}, {"Misra C: 22.20",""}, {"Misra C: 23.1",""}, {"Misra C: 23.2",""}, {"Misra C: 23.3",""}, {"Misra C: 23.4",""}, {"Misra C: 23.5",""}, {"Misra C: 23.6",""}, {"Misra C: 23.7",""}, {"Misra C: 23.8",""}, {"Misra C: 5.1",""}, {"Misra C: 5.2",""}, {"Misra C: 6.1",""}, {"Misra C: 6.3",""}, {"Misra C: 7.4","style"}, {"Misra C: 7.5",""}, {"Misra C: 7.6",""}, {"Misra C: 8.1",""}, {"Misra C: 8.10",""}, {"Misra C: 8.15",""}, {"Misra C: 8.15",""}, {"Misra C: 8.16",""}, {"Misra C: 8.17",""}, {"Misra C: 8.3",""}, {"Misra C: 8.4",""}, {"Misra C: 8.6",""}, {"Misra C: 8.7",""}, {"Misra C: 8.8",""}, {"Misra C: 9.6",""}, {"Misra C: 9.7",""}, {"Misra C: Dir 4.3",""}, {"Misra C: Dir 4.4",""}, {"Misra C: Dir 4.5",""}, {"Misra C: Dir 4.6",""}, {"Misra C: Dir 4.9",""}, {"PremiumCheckBufferOverrun::addressOfPointerArithmetic","warning"}, {"PremiumCheckBufferOverrun::negativeBufferSizeCheckedNonZero","warning"}, {"PremiumCheckBufferOverrun::negativeBufferSizeCheckedNonZero","warning"}, {"PremiumCheckHang::infiniteLoop",""}, {"PremiumCheckHang::infiniteLoopContinue",""}, {"PremiumCheckOther::arrayPointerComparison","style"}, {"PremiumCheckOther::knownResult","style"}, {"PremiumCheckOther::lossOfPrecision","style"}, {"PremiumCheckOther::pointerCast","style"}, {"PremiumCheckOther::reassignInLoop","style"}, {"PremiumCheckOther::unreachableCode","style"}, {"PremiumCheckStrictAlias::strictAliasCondition","warning"}, {"PremiumCheckUninitVar::uninitmember",""}, {"PremiumCheckUninitVar::uninitvar",""}, {"PremiumCheckUnusedVar::unreadVariable","style"}, {"PremiumCheckUnusedVar::unusedPrivateMember","style"} }; const char Req[] = "Required"; const char Adv[] = "Advisory"; const char Man[] = "Mandatory"; const char Doc[] = "Document"; const std::vector<MisraInfo> misraC2012Directives = { {1,1,Req,0}, {2,1,Req,0}, {3,1,Req,0}, {4,1,Req,0}, {4,2,Adv,0}, {4,3,Req,0}, {4,4,Adv,0}, {4,5,Adv,0}, {4,6,Adv,3}, {4,7,Req,0}, {4,8,Adv,0}, {4,9,Adv,3}, {4,10,Req,0}, {4,11,Req,3}, {4,12,Req,0}, {4,13,Adv,0}, {4,14,Req,2}, {4,15,Req,3}, {5,1,Req,4}, {5,2,Req,4}, {5,3,Req,4}, }; const std::vector<MisraInfo> misraC2012Rules = { {1,1,Req,0}, {1,2,Adv,0}, {1,3,Req,0}, {1,4,Req,2}, // amendment 2 {1,5,Req,3}, // Amendment 3 {2,1,Req,0}, {2,2,Req,0}, {2,3,Adv,0}, {2,4,Adv,0}, {2,5,Adv,0}, {2,6,Adv,0}, {2,7,Adv,0}, {2,8,Adv,0}, {3,1,Req,0}, {3,2,Req,0}, {4,1,Req,0}, {4,2,Adv,0}, {5,1,Req,0}, {5,2,Req,0}, {5,3,Req,0}, {5,4,Req,0}, {5,5,Req,0}, {5,6,Req,0}, {5,7,Req,0}, {5,8,Req,0}, {5,9,Adv,0}, {6,1,Req,0}, {6,2,Req,0}, {6,3,Req,0}, {7,1,Req,0}, {7,2,Req,0}, {7,3,Req,0}, {7,4,Req,0}, {7,5,Man,0}, {7,6,Req,0}, {8,1,Req,0}, {8,2,Req,0}, {8,3,Req,0}, {8,4,Req,0}, {8,5,Req,0}, {8,6,Req,0}, {8,7,Adv,0}, {8,8,Req,0}, {8,9,Adv,0}, {8,10,Req,0}, {8,11,Adv,0}, {8,12,Req,0}, {8,13,Adv,0}, {8,14,Req,0}, {8,15,Req,0}, {8,16,Adv,0}, {8,17,Adv,0}, {9,1,Man,0}, {9,2,Req,0}, {9,3,Req,0}, {9,4,Req,0}, {9,5,Req,0}, {9,6,Req,0}, {9,7,Man,0}, {10,1,Req,0}, {10,2,Req,0}, {10,3,Req,0}, {10,4,Req,0}, {10,5,Adv,0}, {10,6,Req,0}, {10,7,Req,0}, {10,8,Req,0}, {11,1,Req,0}, {11,2,Req,0}, {11,3,Req,0}, {11,4,Adv,0}, {11,5,Adv,0}, {11,6,Req,0}, {11,7,Req,0}, {11,8,Req,0}, {11,9,Req,0}, {11,10,Req,0}, {12,1,Adv,0}, {12,2,Req,0}, {12,3,Adv,0}, {12,4,Adv,0}, {12,5,Man,1}, // amendment 1 {12,6,Req,4}, // amendment 4 {13,1,Req,0}, {13,2,Req,0}, {13,3,Adv,0}, {13,4,Adv,0}, {13,5,Req,0}, {13,6,Man,0}, {14,1,Req,0}, {14,2,Req,0}, {14,3,Req,0}, {14,4,Req,0}, {15,1,Adv,0}, {15,2,Req,0}, {15,3,Req,0}, {15,4,Adv,0}, {15,5,Adv,0}, {15,6,Req,0}, {15,7,Req,0}, {16,1,Req,0}, {16,2,Req,0}, {16,3,Req,0}, {16,4,Req,0}, {16,5,Req,0}, {16,6,Req,0}, {16,7,Req,0}, {17,1,Req,0}, {17,2,Req,0}, {17,3,Man,0}, {17,4,Man,0}, {17,5,Adv,0}, {17,6,Man,0}, {17,7,Req,0}, {17,8,Adv,0}, {17,9,Man,0}, {17,10,Req,0}, {17,11,Adv,0}, {17,12,Adv,0}, {17,13,Req,0}, {18,1,Req,0}, {18,2,Req,0}, {18,3,Req,0}, {18,4,Adv,0}, {18,5,Adv,0}, {18,6,Req,0}, {18,7,Req,0}, {18,8,Req,0}, {18,9,Req,0}, {18,10,Man,0}, {19,1,Man,0}, {19,2,Adv,0}, {20,1,Adv,0}, {20,2,Req,0}, {20,3,Req,0}, {20,4,Req,0}, {20,5,Adv,0}, {20,6,Req,0}, {20,7,Req,0}, {20,8,Req,0}, {20,9,Req,0}, {20,10,Adv,0}, {20,11,Req,0}, {20,12,Req,0}, {20,13,Req,0}, {20,14,Req,0}, {21,1,Req,0}, {21,2,Req,0}, {21,3,Req,0}, {21,4,Req,0}, {21,5,Req,0}, {21,6,Req,0}, {21,7,Req,0}, {21,8,Req,0}, {21,9,Req,0}, {21,10,Req,0}, {21,11,Req,0}, {21,12,Adv,0}, {21,13,Man,1}, // Amendment 1 {21,14,Req,1}, // Amendment 1 {21,15,Req,1}, // Amendment 1 {21,16,Req,1}, // Amendment 1 {21,17,Req,1}, // Amendment 1 {21,18,Man,1}, // Amendment 1 {21,19,Man,1}, // Amendment 1 {21,20,Man,1}, // Amendment 1 {21,21,Req,3}, // Amendment 3 {21,22,Man,3}, // Amendment 3 {21,23,Req,3}, // Amendment 3 {21,24,Req,3}, // Amendment 3 {21,25,Req,4}, // Amendment 4 {21,26,Req,4}, // Amendment 4 {22,1,Req,0}, {22,2,Man,0}, {22,3,Req,0}, {22,4,Man,0}, {22,5,Man,0}, {22,6,Man,0}, {22,7,Req,1}, // Amendment 1 {22,8,Req,1}, // Amendment 1 {22,9,Req,1}, // Amendment 1 {22,10,Req,1}, // Amendment 1 {22,11,Req,4}, // Amendment 4 {22,12,Man,4}, // Amendment 4 {22,13,Req,4}, // Amendment 4 {22,14,Man,4}, // Amendment 4 {22,15,Req,4}, // Amendment 4 {22,16,Req,4}, // Amendment 4 {22,17,Req,4}, // Amendment 4 {22,18,Req,4}, // Amendment 4 {22,19,Req,4}, // Amendment 4 {22,20,Man,4}, // Amendment 4 {23,1,Adv,3}, // Amendment 3 {23,2,Req,3}, // Amendment 3 {23,3,Adv,3}, // Amendment 3 {23,4,Req,3}, // Amendment 3 {23,5,Adv,3}, // Amendment 3 {23,6,Req,3}, // Amendment 3 {23,7,Adv,3}, // Amendment 3 {23,8,Req,3}, // Amendment 3 }; const std::map<std::string, std::string> misraRuleSeverity{ {"1.1", "error"}, //{"syntaxError", "unknownMacro"}}, {"1.3", "error"}, //most "error" {"2.1", "style"}, //{"alwaysFalse", "duplicateBreak"}}, {"2.2", "style"}, //{"alwaysTrue", "redundantCondition", "redundantAssignment", "redundantAssignInSwitch", "unreadVariable"}}, {"2.6", "style"}, //{"unusedLabel"}}, {"2.8", "style"}, //{"unusedVariable"}}, {"5.3", "style"}, //{"shadowVariable"}}, {"8.3", "style"}, //{"funcArgNamesDifferent"}}, // inconclusive {"8.13", "style"}, //{"constPointer"}}, {"9.1", "error"}, //{"uninitvar"}}, {"14.3", "style"}, //{"alwaysTrue", "alwaysFalse", "compareValueOutOfTypeRangeError", "knownConditionTrueFalse"}}, {"13.2", "error"}, //{"unknownEvaluationOrder"}}, {"13.6", "style"}, //{"sizeofCalculation"}}, {"17.4", "error"}, //{"missingReturn"}}, {"17.5", "warning"}, //{"argumentSize"}}, {"18.1", "error"}, //{"pointerOutOfBounds"}}, {"18.2", "error"}, //{"comparePointers"}}, {"18.3", "error"}, //{"comparePointers"}}, {"18.6", "error"}, //{"danglingLifetime"}}, {"19.1", "error"}, //{"overlappingWriteUnion", "overlappingWriteFunction"}}, {"20.6", "error"}, //{"preprocessorErrorDirective"}}, {"21.13", "error"}, //{"invalidFunctionArg"}}, {"21.17", "error"}, //{"bufferAccessOutOfBounds"}}, {"21.18", "error"}, //{"bufferAccessOutOfBounds"}}, {"22.1", "error"}, //{"memleak", "resourceLeak", "memleakOnRealloc", "leakReturnValNotUsed", "leakNoVarFunctionCall"}}, {"22.2", "error"}, //{"autovarInvalidDeallocation"}}, {"22.3", "error"}, //{"incompatibleFileOpen"}}, {"22.4", "error"}, //{"writeReadOnlyFile"}}, {"22.6", "error"}, //{"useClosedFile"}} }; const std::vector<MisraCppInfo> misraCpp2008Rules = { {0,1,1,Req}, {0,1,2,Req}, {0,1,3,Req}, {0,1,4,Req}, {0,1,5,Req}, {0,1,6,Req}, {0,1,7,Req}, {0,1,8,Req}, {0,1,9,Req}, {0,1,10,Req}, {0,1,11,Req}, {0,1,12,Req}, {0,2,1,Req}, {0,3,1,Doc}, {0,3,2,Req}, {0,4,1,Doc}, {0,4,2,Doc}, {0,4,3,Doc}, {1,0,1,Req}, {1,0,2,Doc}, {1,0,3,Doc}, {2,2,1,Doc}, {2,3,1,Req}, {2,5,1,Adv}, {2,7,1,Req}, {2,7,2,Req}, {2,7,3,Adv}, {2,10,1,Req}, {2,10,2,Req}, {2,10,3,Req}, {2,10,4,Req}, {2,10,5,Adv}, {2,10,6,Req}, {2,13,1,Req}, {2,13,2,Req}, {2,13,3,Req}, {2,13,4,Req}, {2,13,5,Req}, {3,1,1,Req}, {3,1,2,Req}, {3,1,3,Req}, {3,2,1,Req}, {3,2,2,Req}, {3,2,3,Req}, {3,2,4,Req}, {3,3,1,Req}, {3,3,2,Req}, {3,4,1,Req}, {3,9,1,Req}, {3,9,2,Adv}, {3,9,3,Req}, {4,5,1,Req}, {4,5,2,Req}, {4,5,3,Req}, {4,10,1,Req}, {4,10,2,Req}, {5,0,1,Req}, {5,0,2,Adv}, {5,0,3,Req}, {5,0,4,Req}, {5,0,5,Req}, {5,0,6,Req}, {5,0,7,Req}, {5,0,8,Req}, {5,0,9,Req}, {5,0,10,Req}, {5,0,11,Req}, {5,0,12,Req}, {5,0,13,Req}, {5,0,14,Req}, {5,0,15,Req}, {5,0,16,Req}, {5,0,17,Req}, {5,0,18,Req}, {5,0,19,Req}, {5,0,20,Req}, {5,0,21,Req}, {5,2,1,Req}, {5,2,2,Req}, {5,2,3,Adv}, {5,2,4,Req}, {5,2,5,Req}, {5,2,6,Req}, {5,2,7,Req}, {5,2,8,Req}, {5,2,9,Adv}, {5,2,10,Adv}, {5,2,11,Req}, {5,2,12,Req}, {5,3,1,Req}, {5,3,2,Req}, {5,3,3,Req}, {5,3,4,Req}, {5,8,1,Req}, {5,14,1,Req}, {5,17,1,Req}, {5,18,1,Req}, {5,19,1,Adv}, {6,2,1,Req}, {6,2,2,Req}, {6,2,3,Req}, {6,3,1,Req}, {6,4,1,Req}, {6,4,2,Req}, {6,4,3,Req}, {6,4,4,Req}, {6,4,5,Req}, {6,4,6,Req}, {6,4,7,Req}, {6,4,8,Req}, {6,5,1,Req}, {6,5,2,Req}, {6,5,3,Req}, {6,5,4,Req}, {6,5,5,Req}, {6,5,6,Req}, {6,6,1,Req}, {6,6,2,Req}, {6,6,3,Req}, {6,6,4,Req}, {6,6,5,Req}, {7,1,1,Req}, {7,1,2,Req}, {7,2,1,Req}, {7,3,1,Req}, {7,3,2,Req}, {7,3,3,Req}, {7,3,4,Req}, {7,3,5,Req}, {7,3,6,Req}, {7,4,1,Doc}, {7,4,2,Req}, {7,4,3,Req}, {7,5,1,Req}, {7,5,2,Req}, {7,5,3,Req}, {7,5,4,Adv}, {8,4,1,Req}, {8,4,2,Req}, {8,4,3,Req}, {8,4,4,Req}, {8,5,1,Req}, {8,5,2,Req}, {8,5,3,Req}, {9,3,1,Req}, {9,3,2,Req}, {9,3,3,Req}, {9,5,1,Req}, {9,6,1,Doc}, {9,6,2,Req}, {9,6,3,Req}, {9,6,4,Req}, {10,1,1,Adv}, {10,1,2,Req}, {10,1,3,Req}, {10,2,1,Adv}, {10,3,1,Req}, {10,3,2,Req}, {10,3,3,Req}, {11,0,1,Req}, {12,1,1,Req}, {12,1,2,Adv}, {12,1,3,Req}, {12,8,1,Req}, {12,8,2,Req}, {14,5,1,Req}, {14,5,2,Req}, {14,5,3,Req}, {14,6,1,Req}, {14,6,2,Req}, {14,7,1,Req}, {14,7,2,Req}, {14,7,3,Req}, {14,8,1,Req}, {14,8,2,Req}, {15,0,1,Req}, {15,0,2,Req}, {15,0,3,Req}, {15,1,1,Req}, {15,1,2,Req}, {15,1,3,Req}, {15,3,1,Req}, {15,3,2,Adv}, {15,3,3,Req}, {15,3,4,Req}, {15,3,5,Req}, {15,3,6,Req}, {15,3,7,Req}, {15,4,1,Req}, {15,5,1,Req}, {15,5,2,Req}, {15,5,3,Req}, {16,0,1,Req}, {16,0,2,Req}, {16,0,3,Req}, {16,0,4,Req}, {16,0,5,Req}, {16,0,6,Req}, {16,0,7,Req}, {16,0,8,Req}, {16,1,1,Req}, {16,1,2,Req}, {16,2,1,Req}, {16,2,2,Req}, {16,2,3,Req}, {16,2,4,Req}, {16,2,5,Adv}, {16,2,6,Req}, {16,3,1,Req}, {16,3,2,Adv}, {16,6,1,Doc}, {17,0,1,Req}, {17,0,2,Req}, {17,0,3,Req}, {17,0,4,Doc}, {17,0,5,Req}, {18,0,1,Req}, {18,0,2,Req}, {18,0,3,Req}, {18,0,4,Req}, {18,0,5,Req}, {18,2,1,Req}, {18,4,1,Req}, {18,7,1,Req}, {19,3,1,Req}, {27,0,1,Req} }; const std::vector<MisraCppInfo> misraCpp2023Rules = { {0,0,1,Req}, {0,0,2,Adv}, {0,1,1,Adv}, {0,1,2,Req}, {0,2,1,Adv}, {0,2,2,Req}, {0,2,3,Adv}, {0,2,4,Adv}, {0,3,1,Adv}, {0,3,2,Req}, {4,1,1,Req}, {4,1,2,Adv}, {4,1,3,Req}, {4,6,1,Req}, {5,0,1,Adv}, {5,7,1,Req}, {5,7,2,Adv}, {5,7,3,Req}, {5,10,1,Req}, {5,13,1,Req}, {5,13,2,Req}, {5,13,3,Req}, {5,13,4,Req}, {5,13,5,Req}, {5,13,6,Req}, {5,13,7,Req}, {6,0,1,Req}, {6,0,2,Adv}, {6,0,3,Adv}, {6,0,4,Req}, {6,2,1,Req}, {6,2,2,Req}, {6,2,3,Req}, {6,2,4,Req}, {6,4,1,Req}, {6,4,2,Req}, {6,4,3,Req}, {6,5,1,Adv}, {6,5,2,Adv}, {6,7,1,Req}, {6,7,2,Req}, {6,8,1,Req}, {6,8,2,Man}, {6,8,3,Req}, {6,8,4,Adv}, {6,9,1,Req}, {6,9,2,Adv}, {7,0,1,Req}, {7,0,2,Req}, {7,0,3,Req}, {7,0,4,Req}, {7,0,5,Req}, {7,0,6,Req}, {7,11,1,Req}, {7,11,2,Req}, {7,11,3,Req}, {8,0,1,Adv}, {8,1,1,Req}, {8,1,2,Adv}, {8,2,1,Req}, {8,2,2,Req}, {8,2,3,Req}, {8,2,4,Req}, {8,2,5,Req}, {8,2,6,Req}, {8,2,7,Adv}, {8,2,8,Req}, {8,2,9,Req}, {8,2,10,Req}, {8,2,11,Req}, {8,3,1,Adv}, {8,3,2,Adv}, {8,7,1,Req}, {8,7,2,Req}, {8,9,1,Req}, {8,14,1,Adv}, {8,18,1,Man}, {8,18,2,Adv}, {8,19,1,Adv}, {8,20,1,Adv}, {9,2,1,Req}, {9,3,1,Req}, {9,4,1,Req}, {9,4,2,Req}, {9,5,2,Adv}, {9,5,3,Req}, {9,6,1,Adv}, {9,6,2,Req}, {9,6,3,Req}, {9,6,4,Req}, {9,6,5,Req}, {10,0,1,Adv}, {10,1,1,Adv}, {10,1,2,Req}, {10,2,1,Req}, {10,2,2,Adv}, {10,2,3,Req}, {10,3,1,Adv}, {10,4,1,Req}, {11,3,1,Adv}, {11,3,2,Adv}, {11,6,1,Adv}, {11,6,2,Man}, {11,6,3,Req}, {12,2,1,Adv}, {12,2,2,Req}, {12,2,3,Req}, {12,3,1,Req}, {13,1,1,Adv}, {13,1,2,Req}, {13,3,1,Req}, {13,3,2,Req}, {13,3,3,Req}, {13,3,4,Req}, {14,1,1,Adv}, {15,0,1,Req}, {15,0,2,Adv}, {15,1,1,Req}, {15,1,2,Adv}, {15,1,3,Req}, {15,1,4,Adv}, {15,1,5,Req}, {15,8,1,Req}, {16,5,2,Req}, {16,6,1,Adv}, {17,8,1,Req}, {18,1,1,Req}, {18,1,2,Req}, {18,3,1,Adv}, {18,3,2,Req}, {18,3,3,Req}, {18,4,1,Req}, {18,5,1,Adv}, {18,5,2,Adv}, {19,0,1,Req}, {19,0,2,Req}, {19,0,3,Adv}, {19,0,4,Adv}, {19,1,1,Req}, {19,1,2,Req}, {19,1,3,Req}, {19,2,1,Req}, {19,2,2,Req}, {19,2,3,Req}, {19,3,1,Adv}, {19,3,2,Req}, {19,3,3,Req}, {19,3,4,Req}, {19,3,5,Req}, {19,6,1,Adv}, {21,2,1,Req}, {21,2,2,Req}, {21,2,3,Req}, {21,2,4,Req}, {21,6,1,Adv}, {21,6,2,Req}, {21,6,3,Req}, {21,6,4,Req}, {21,6,5,Req}, {21,10,1,Req}, {21,10,2,Req}, {21,10,3,Req}, {22,3,1,Req}, {22,4,1,Req}, {23,11,1,Adv}, {24,5,1,Req}, {24,5,2,Req}, {25,5,1,Req}, {25,5,2,Man}, {25,5,3,Man}, {26,3,1,Adv}, {28,3,1,Req}, {28,6,1,Req}, {28,6,2,Req}, {28,6,3,Req}, {28,6,4,Req}, {30,0,1,Req}, {30,0,2,Req} }; } std::vector<checkers::Info> checkers::autosarInfo{ {"m0-1-1", checkers::Req}, {"m0-1-2", checkers::Req}, {"m0-1-3", checkers::Req}, {"m0-1-4", checkers::Req}, {"a0-1-1", checkers::Req}, {"a0-1-2", checkers::Req}, {"m0-1-8", checkers::Req}, {"m0-1-9", checkers::Req}, {"m0-1-10", checkers::Adv}, {"a0-1-3", checkers::Req}, {"a0-1-4", checkers::Req}, {"a0-1-5", checkers::Req}, {"a0-1-6", checkers::Adv}, {"m0-2-1", checkers::Req}, {"a0-4-2", checkers::Req}, {"a0-4-3", checkers::Req}, {"a0-4-4", checkers::Req}, {"a1-1-1", checkers::Req}, {"a1-4-3", checkers::Adv}, {"a2-3-1", checkers::Req}, {"a2-5-1", checkers::Req}, {"a2-5-2", checkers::Req}, {"m2-7-1", checkers::Req}, {"a2-7-1", checkers::Req}, {"a2-7-3", checkers::Req}, {"a2-8-2", checkers::Adv}, {"m2-10-1", checkers::Req}, {"a2-10-1", checkers::Req}, {"a2-10-6", checkers::Req}, {"a2-10-4", checkers::Req}, {"a2-10-5", checkers::Adv}, {"a2-11-1", checkers::Req}, {"a2-13-1", checkers::Req}, {"a2-13-6", checkers::Req}, {"a2-13-5", checkers::Adv}, {"m2-13-2", checkers::Req}, {"m2-13-3", checkers::Req}, {"m2-13-4", checkers::Req}, {"a2-13-2", checkers::Req}, {"a2-13-3", checkers::Req}, {"a2-13-4", checkers::Req}, {"a3-1-1", checkers::Req}, {"a3-1-2", checkers::Req}, {"a3-1-3", checkers::Adv}, {"m3-1-2", checkers::Req}, {"a3-1-4", checkers::Req}, {"a3-1-6", checkers::Adv}, {"m3-2-1", checkers::Req}, {"m3-2-2", checkers::Req}, {"m3-2-3", checkers::Req}, {"m3-2-4", checkers::Req}, {"a3-3-1", checkers::Req}, {"a3-3-2", checkers::Req}, {"m3-3-2", checkers::Req}, {"m3-4-1", checkers::Req}, {"m3-9-1", checkers::Req}, {"a3-9-1", checkers::Req}, {"m3-9-3", checkers::Req}, {"m4-5-1", checkers::Req}, {"a4-5-1", checkers::Req}, {"m4-5-3", checkers::Req}, {"a4-7-1", checkers::Req}, {"m4-10-1", checkers::Req}, {"a4-10-1", checkers::Req}, {"m4-10-2", checkers::Req}, {"a5-0-1", checkers::Req}, {"m5-0-2", checkers::Adv}, {"m5-0-3", checkers::Req}, {"m5-0-4", checkers::Req}, {"m5-0-5", checkers::Req}, {"m5-0-6", checkers::Req}, {"m5-0-7", checkers::Req}, {"m5-0-8", checkers::Req}, {"m5-0-9", checkers::Req}, {"m5-0-10", checkers::Req}, {"m5-0-11", checkers::Req}, {"m5-0-12", checkers::Req}, {"a5-0-2", checkers::Req}, {"m5-0-14", checkers::Req}, {"m5-0-15", checkers::Req}, {"m5-0-16", checkers::Req}, {"m5-0-17", checkers::Req}, {"a5-0-4", checkers::Req}, {"m5-0-18", checkers::Req}, {"a5-0-3", checkers::Req}, {"m5-0-20", checkers::Req}, {"m5-0-21", checkers::Req}, {"a5-1-1", checkers::Req}, {"a5-1-2", checkers::Req}, {"a5-1-3", checkers::Req}, {"a5-1-4", checkers::Req}, {"a5-1-6", checkers::Adv}, {"a5-1-7", checkers::Req}, {"a5-1-8", checkers::Adv}, {"a5-1-9", checkers::Adv}, {"m5-2-2", checkers::Req}, {"m5-2-3", checkers::Adv}, {"a5-2-1", checkers::Adv}, {"a5-2-2", checkers::Req}, {"a5-2-3", checkers::Req}, {"m5-2-6", checkers::Req}, {"a5-2-4", checkers::Req}, {"a5-2-6", checkers::Req}, {"m5-2-8", checkers::Req}, {"m5-2-9", checkers::Req}, {"m5-2-10", checkers::Req}, {"m5-2-11", checkers::Req}, {"a5-2-5", checkers::Req}, {"m5-2-12", checkers::Req}, {"m5-3-1", checkers::Req}, {"m5-3-2", checkers::Req}, {"m5-3-3", checkers::Req}, {"m5-3-4", checkers::Req}, {"a5-3-1", checkers::Req}, {"a5-3-2", checkers::Req}, {"a5-3-3", checkers::Req}, {"a5-5-1", checkers::Req}, {"a5-6-1", checkers::Req}, {"m5-8-1", checkers::Req}, {"a5-10-1", checkers::Req}, {"m5-14-1", checkers::Req}, {"a5-16-1", checkers::Req}, {"m5-18-1", checkers::Req}, {"m5-19-1", checkers::Req}, {"m6-2-1", checkers::Req}, {"a6-2-1", checkers::Req}, {"a6-2-2", checkers::Req}, {"m6-2-2", checkers::Req}, {"m6-2-3", checkers::Req}, {"m6-3-1", checkers::Req}, {"m6-4-1", checkers::Req}, {"m6-4-2", checkers::Req}, {"m6-4-3", checkers::Req}, {"m6-4-4", checkers::Req}, {"m6-4-5", checkers::Req}, {"m6-4-6", checkers::Req}, {"m6-4-7", checkers::Req}, {"a6-4-1", checkers::Req}, {"a6-5-1", checkers::Req}, {"a6-5-2", checkers::Req}, {"m6-5-2", checkers::Req}, {"m6-5-3", checkers::Req}, {"m6-5-4", checkers::Req}, {"m6-5-5", checkers::Req}, {"m6-5-6", checkers::Req}, {"a6-5-3", checkers::Adv}, {"a6-5-4", checkers::Adv}, {"a6-6-1", checkers::Req}, {"m6-6-1", checkers::Req}, {"m6-6-2", checkers::Req}, {"m6-6-3", checkers::Req}, {"a7-1-1", checkers::Req}, {"a7-1-2", checkers::Req}, {"m7-1-2", checkers::Req}, {"a7-1-3", checkers::Req}, {"a7-1-4", checkers::Req}, {"a7-1-5", checkers::Req}, {"a7-1-6", checkers::Req}, {"a7-1-7", checkers::Req}, {"a7-1-8", checkers::Req}, {"a7-1-9", checkers::Req}, {"a7-2-1", checkers::Req}, {"a7-2-2", checkers::Req}, {"a7-2-3", checkers::Req}, {"a7-2-4", checkers::Req}, {"m7-3-1", checkers::Req}, {"m7-3-2", checkers::Req}, {"m7-3-3", checkers::Req}, {"m7-3-4", checkers::Req}, {"a7-3-1", checkers::Req}, {"m7-3-6", checkers::Req}, {"a7-4-1", checkers::Req}, {"m7-4-2", checkers::Req}, {"m7-4-3", checkers::Req}, {"a7-5-1", checkers::Req}, {"a7-5-2", checkers::Req}, {"a7-6-1", checkers::Req}, {"m8-0-1", checkers::Req}, {"a8-2-1", checkers::Req}, {"m8-3-1", checkers::Req}, {"a8-4-1", checkers::Req}, {"m8-4-2", checkers::Req}, {"a8-4-2", checkers::Req}, {"m8-4-4", checkers::Req}, {"a8-4-4", checkers::Adv}, {"a8-4-5", checkers::Req}, {"a8-4-6", checkers::Req}, {"a8-4-7", checkers::Req}, {"a8-4-8", checkers::Req}, {"a8-4-9", checkers::Req}, {"a8-4-10", checkers::Req}, {"a8-4-11", checkers::Req}, {"a8-4-12", checkers::Req}, {"a8-4-13", checkers::Req}, {"a8-4-14", checkers::Req}, {"a8-5-0", checkers::Req}, {"a8-5-1", checkers::Req}, {"m8-5-2", checkers::Req}, {"a8-5-2", checkers::Req}, {"a8-5-3", checkers::Req}, {"a8-5-4", checkers::Adv}, {"m9-3-1", checkers::Req}, {"a9-3-1", checkers::Req}, {"m9-3-3", checkers::Req}, {"a9-5-1", checkers::Req}, {"a9-6-1", checkers::Req}, {"m9-6-4", checkers::Req}, {"a10-1-1", checkers::Req}, {"m10-1-1", checkers::Adv}, {"m10-1-2", checkers::Req}, {"m10-1-3", checkers::Req}, {"m10-2-1", checkers::Adv}, {"a10-2-1", checkers::Req}, {"a10-3-1", checkers::Req}, {"a10-3-2", checkers::Req}, {"a10-3-3", checkers::Req}, {"a10-3-5", checkers::Req}, {"m10-3-3", checkers::Req}, {"a10-4-1", checkers::Req}, {"m11-0-1", checkers::Req}, {"a11-0-1", checkers::Adv}, {"a11-0-2", checkers::Req}, {"a11-3-1", checkers::Req}, {"a12-0-1", checkers::Req}, {"a12-0-2", checkers::Req}, {"a12-1-1", checkers::Req}, {"m12-1-1", checkers::Req}, {"a12-1-2", checkers::Req}, {"a12-1-3", checkers::Req}, {"a12-1-4", checkers::Req}, {"a12-1-5", checkers::Req}, {"a12-1-6", checkers::Req}, {"a12-4-1", checkers::Req}, {"a12-4-2", checkers::Adv}, {"a12-6-1", checkers::Req}, {"a12-7-1", checkers::Req}, {"a12-8-1", checkers::Req}, {"a12-8-2", checkers::Adv}, {"a12-8-3", checkers::Req}, {"a12-8-4", checkers::Req}, {"a12-8-5", checkers::Req}, {"a12-8-6", checkers::Req}, {"a12-8-7", checkers::Adv}, {"a13-1-2", checkers::Req}, {"a13-1-3", checkers::Req}, {"a13-2-1", checkers::Req}, {"a13-2-2", checkers::Req}, {"a13-2-3", checkers::Req}, {"a13-3-1", checkers::Req}, {"a13-5-1", checkers::Req}, {"a13-5-2", checkers::Req}, {"a13-5-3", checkers::Adv}, {"a13-5-4", checkers::Req}, {"a13-5-5", checkers::Req}, {"a13-6-1", checkers::Req}, {"a14-1-1", checkers::Adv}, {"a14-5-1", checkers::Req}, {"a14-5-2", checkers::Req}, {"a14-5-3", checkers::Req}, {"m14-5-3", checkers::Req}, {"m14-6-1", checkers::Req}, {"a14-7-1", checkers::Req}, {"a14-7-2", checkers::Req}, {"a14-8-2", checkers::Req}, {"a15-0-2", checkers::Req}, {"a15-1-2", checkers::Req}, {"m15-0-3", checkers::Req}, {"m15-1-1", checkers::Req}, {"m15-1-2", checkers::Req}, {"m15-1-3", checkers::Req}, {"a15-1-3", checkers::Adv}, {"a15-1-4", checkers::Req}, {"a15-2-1", checkers::Req}, {"a15-2-2", checkers::Req}, {"m15-3-1", checkers::Req}, {"a15-3-2", checkers::Req}, {"a15-3-3", checkers::Req}, {"m15-3-3", checkers::Req}, {"m15-3-4", checkers::Req}, {"a15-3-5", checkers::Req}, {"m15-3-6", checkers::Req}, {"m15-3-7", checkers::Req}, {"a15-4-1", checkers::Req}, {"a15-4-2", checkers::Req}, {"a15-4-3", checkers::Req}, {"a15-4-4", checkers::Req}, {"a15-4-5", checkers::Req}, {"a15-5-1", checkers::Req}, {"a15-5-2", checkers::Req}, {"a15-5-3", checkers::Req}, {"a16-0-1", checkers::Req}, {"m16-0-1", checkers::Req}, {"m16-0-2", checkers::Req}, {"m16-0-5", checkers::Req}, {"m16-0-6", checkers::Req}, {"m16-0-7", checkers::Req}, {"m16-0-8", checkers::Req}, {"m16-1-1", checkers::Req}, {"m16-1-2", checkers::Req}, {"m16-2-3", checkers::Req}, {"a16-2-1", checkers::Req}, {"a16-2-2", checkers::Req}, {"a16-2-3", checkers::Req}, {"m16-3-1", checkers::Req}, {"m16-3-2", checkers::Adv}, {"a16-6-1", checkers::Req}, {"a16-7-1", checkers::Req}, {"a17-0-1", checkers::Req}, {"m17-0-2", checkers::Req}, {"m17-0-3", checkers::Req}, {"m17-0-5", checkers::Req}, {"a17-1-1", checkers::Req}, {"a17-6-1", checkers::Req}, {"a18-0-1", checkers::Req}, {"a18-0-2", checkers::Req}, {"m18-0-3", checkers::Req}, {"m18-0-4", checkers::Req}, {"m18-0-5", checkers::Req}, {"a18-0-3", checkers::Req}, {"a18-1-1", checkers::Req}, {"a18-1-2", checkers::Req}, {"a18-1-3", checkers::Req}, {"a18-1-4", checkers::Req}, {"a18-1-6", checkers::Req}, {"m18-2-1", checkers::Req}, {"a18-5-1", checkers::Req}, {"a18-5-2", checkers::Req}, {"a18-5-3", checkers::Req}, {"a18-5-4", checkers::Req}, {"a18-5-5", checkers::Req}, {"a18-5-6", checkers::Req}, {"a18-5-7", checkers::Req}, {"a18-5-8", checkers::Req}, {"a18-5-9", checkers::Req}, {"a18-5-10", checkers::Req}, {"a18-5-11", checkers::Req}, {"m18-7-1", checkers::Req}, {"a18-9-1", checkers::Req}, {"a18-9-2", checkers::Req}, {"a18-9-3", checkers::Req}, {"a18-9-4", checkers::Req}, {"m19-3-1", checkers::Req}, {"a20-8-1", checkers::Req}, {"a20-8-2", checkers::Req}, {"a20-8-3", checkers::Req}, {"a20-8-4", checkers::Req}, {"a20-8-5", checkers::Req}, {"a20-8-6", checkers::Req}, {"a20-8-7", checkers::Req}, {"a21-8-1", checkers::Req}, {"a23-0-1", checkers::Req}, {"a23-0-2", checkers::Req}, {"a25-1-1", checkers::Req}, {"a25-4-1", checkers::Req}, {"a26-5-1", checkers::Req}, {"a26-5-2", checkers::Req}, {"m27-0-1", checkers::Req}, {"a27-0-1", checkers::Req}, {"a27-0-4", checkers::Req}, {"a27-0-2", checkers::Adv}, {"a27-0-3", checkers::Req}, }; std::vector<checkers::Info> checkers::certCInfo{ {"PRE30-C", "L3"}, {"PRE31-C", "L3"}, {"PRE32-C", "L3"}, {"DCL30-C", "L2"}, {"DCL31-C", "L3"}, {"DCL36-C", "L2"}, {"DCL37-C", "L3"}, {"DCL38-C", "L3"}, {"DCL39-C", "L3"}, {"DCL40-C", "L3"}, {"DCL41-C", "L3"}, {"EXP30-C", "L2"}, {"EXP32-C", "L2"}, {"EXP33-C", "L1"}, {"EXP34-C", "L1"}, {"EXP35-C", "L3"}, {"EXP36-C", "L3"}, {"EXP37-C", "L3"}, {"EXP39-C", "L3"}, {"EXP40-C", "L3"}, {"EXP42-C", "L2"}, {"EXP43-C", "L3"}, {"EXP44-C", "L3"}, {"EXP45-C", "L2"}, {"EXP46-C", "L2"}, {"INT30-C", "L2"}, {"INT31-C", "L2"}, {"INT32-C", "L2"}, {"INT33-C", "L2"}, {"INT34-C", "L3"}, {"INT35-C", "L3"}, {"INT36-C", "L3"}, {"FLP30-C", "L2"}, {"FLP32-C", "L2"}, {"FLP34-C", "L3"}, {"FLP36-C", "L3"}, {"FLP37-C", "L3"}, {"ARR30-C", "L2"}, {"ARR32-C", "L2"}, {"ARR36-C", "L2"}, {"ARR37-C", "L2"}, {"ARR38-C", "L1"}, {"ARR39-C", "L2"}, {"STR30-C", "L2"}, {"STR31-C", "L1"}, {"STR32-C", "L1"}, {"STR34-C", "L2"}, {"STR37-C", "L3"}, {"STR38-C", "L1"}, {"MEM30-C", "L1"}, {"MEM31-C", "L2"}, {"MEM33-C", "L3"}, {"MEM34-C", "L1"}, {"MEM35-C", "L2"}, {"MEM36-C", "L3"}, {"FIO30-C", "L1"}, {"FIO32-C", "L3"}, {"FIO34-C", "L1"}, {"FIO37-C", "L1"}, {"FIO38-C", "L3"}, {"FIO39-C", "L2"}, {"FIO40-C", "L3"}, {"FIO41-C", "L3"}, {"FIO42-C", "L3"}, {"FIO44-C", "L3"}, {"FIO45-C", "L2"}, {"FIO46-C", "L3"}, {"FIO47-C", "L2"}, {"ENV30-C", "L3"}, {"ENV31-C", "L3"}, {"ENV32-C", "L1"}, {"ENV33-C", "L1"}, {"ENV34-C", "L3"}, {"SIG30-C", "L1"}, {"SIG31-C", "L2"}, {"SIG34-C", "L3"}, {"SIG35-C", "L3"}, {"ERR30-C", "L2"}, {"ERR32-C", "L3"}, {"ERR33-C", "L1"}, {"CON30-C", "L3"}, {"CON31-C", "L3"}, {"CON32-C", "L2"}, {"CON33-C", "L3"}, {"CON34-C", "L3"}, {"CON35-C", "L3"}, {"CON36-C", "L3"}, {"CON37-C", "L2"}, {"CON38-C", "L3"}, {"CON39-C", "L2"}, {"CON40-C", "L2"}, {"CON41-C", "L3"}, {"MSC30-C", "L2"}, {"MSC32-C", "L1"}, {"MSC33-C", "L1"}, {"MSC37-C", "L2"}, {"MSC38-C", "L3"}, {"MSC39-C", "L3"}, {"MSC40-C", "L3"}, }; std::vector<checkers::Info> checkers::certCppInfo{ {"DCL50-CPP", "L1"}, {"DCL51-CPP", "L3"}, {"DCL52-CPP", "L3"}, {"DCL53-CPP", "L3"}, {"DCL54-CPP", "L2"}, {"DCL55-CPP", "L3"}, {"DCL56-CPP", "L3"}, {"DCL57-CPP", "L3"}, {"DCL58-CPP", "L3"}, {"DCL59-CPP", "L3"}, {"DCL60-CPP", "L3"}, {"EXP50-CPP", "L2"}, {"EXP51-CPP", "L3"}, {"EXP52-CPP", "L3"}, {"EXP53-CPP", "L1"}, {"EXP54-CPP", "L2"}, {"EXP55-CPP", "L2"}, {"EXP56-CPP", "L3"}, {"EXP57-CPP", "L3"}, {"EXP58-CPP", "L3"}, {"EXP59-CPP", "L3"}, {"EXP60-CPP", "L1"}, {"EXP61-CPP", "L2"}, {"EXP62-CPP", "L2"}, {"EXP63-CPP", "L2"}, {"INT50-CPP", "L3"}, {"CTR50-CPP", "L2"}, {"CTR51-CPP", "L2"}, {"CTR52-CPP", "L1"}, {"CTR53-CPP", "L2"}, {"CTR54-CPP", "L2"}, {"CTR55-CPP", "L1"}, {"CTR56-CPP", "L2"}, {"CTR57-CPP", "L3"}, {"CTR58-CPP", "L3"}, {"STR50-CPP", "L1"}, {"STR51-CPP", "L1"}, {"STR52-CPP", "L2"}, {"STR53-CPP", "L2"}, {"MEM50-CPP", "L1"}, {"MEM51-CPP", "L1"}, {"MEM52-CPP", "L1"}, {"MEM53-CPP", "L1"}, {"MEM54-CPP", "L1"}, {"MEM55-CPP", "L1"}, {"MEM56-CPP", "L1"}, {"MEM57-CPP", "L2"}, {"FIO50-CPP", "L2"}, {"FIO51-CPP", "L3"}, {"ERR50-CPP", "L3"}, {"ERR51-CPP", "L3"}, {"ERR52-CPP", "L3"}, {"ERR53-CPP", "L3"}, {"ERR54-CPP", "L1"}, {"ERR55-CPP", "L2"}, {"ERR56-CPP", "L2"}, {"ERR57-CPP", "L3"}, {"ERR58-CPP", "L2"}, {"ERR59-CPP", "L1"}, {"ERR60-CPP", "L3"}, {"ERR61-CPP", "L3"}, {"ERR62-CPP", "L3"}, {"OOP50-CPP", "L3"}, {"OOP51-CPP", "L3"}, {"OOP52-CPP", "L2"}, {"OOP53-CPP", "L3"}, {"OOP54-CPP", "L3"}, {"OOP55-CPP", "L2"}, {"OOP56-CPP", "L3"}, {"OOP57-CPP", "L2"}, {"OOP58-CPP", "L2"}, {"CON50-CPP", "L3"}, {"CON51-CPP", "L2"}, {"CON52-CPP", "L2"}, {"CON53-CPP", "L3"}, {"CON54-CPP", "L3"}, {"CON55-CPP", "L3"}, {"CON56-CPP", "L3"}, {"MSC50-CPP", "L2"}, {"MSC51-CPP", "L1"}, {"MSC52-CPP", "L3"}, {"MSC53-CPP", "L2"}, {"MSC54-CPP", "L2"}, };
67,926
C++
.cpp
2,085
24.755875
134
0.451464
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,143
library.cpp
danmar_cppcheck/lib/library.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "library.h" #include "astutils.h" #include "errortypes.h" #include "mathlib.h" #include "path.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "utils.h" #include "vfvalue.h" #include <algorithm> #include <cctype> #include <climits> #include <cstring> #include <iostream> #include <list> #include <memory> #include <sstream> #include <stdexcept> #include <string> #include <unordered_set> #include "xml.h" struct Library::LibraryData { struct Platform { const PlatformType *platform_type(const std::string &name) const { const std::map<std::string, PlatformType>::const_iterator it = mPlatformTypes.find(name); return (it != mPlatformTypes.end()) ? &(it->second) : nullptr; } std::map<std::string, PlatformType> mPlatformTypes; }; class ExportedFunctions { public: void addPrefix(std::string prefix) { mPrefixes.insert(std::move(prefix)); } void addSuffix(std::string suffix) { mSuffixes.insert(std::move(suffix)); } bool isPrefix(const std::string& prefix) const { return (mPrefixes.find(prefix) != mPrefixes.end()); } bool isSuffix(const std::string& suffix) const { return (mSuffixes.find(suffix) != mSuffixes.end()); } private: std::set<std::string> mPrefixes; std::set<std::string> mSuffixes; }; class CodeBlock { public: CodeBlock() = default; void setStart(const char* s) { mStart = s; } void setEnd(const char* e) { mEnd = e; } void setOffset(const int o) { mOffset = o; } void addBlock(const char* blockName) { mBlocks.insert(blockName); } const std::string& start() const { return mStart; } const std::string& end() const { return mEnd; } int offset() const { return mOffset; } bool isBlock(const std::string& blockName) const { return mBlocks.find(blockName) != mBlocks.end(); } private: std::string mStart; std::string mEnd; int mOffset{}; std::set<std::string> mBlocks; }; enum class FalseTrueMaybe : std::uint8_t { False, True, Maybe }; std::map<std::string, WarnInfo> mFunctionwarn; std::set<std::string> mDefines; std::unordered_map<std::string, Container> mContainers; std::unordered_map<std::string, Function> mFunctions; std::unordered_map<std::string, SmartPointer> mSmartPointers; int mAllocId{}; std::set<std::string> mFiles; std::map<std::string, AllocFunc> mAlloc; // allocation functions std::map<std::string, AllocFunc> mDealloc; // deallocation functions std::map<std::string, AllocFunc> mRealloc; // reallocation functions std::unordered_map<std::string, FalseTrueMaybe> mNoReturn; // is function noreturn? std::map<std::string, std::string> mReturnValue; std::map<std::string, std::string> mReturnValueType; std::map<std::string, int> mReturnValueContainer; std::map<std::string, std::vector<MathLib::bigint>> mUnknownReturnValues; std::map<std::string, bool> mReportErrors; std::map<std::string, bool> mProcessAfterCode; std::set<std::string> mMarkupExtensions; // file extensions of markup files std::map<std::string, std::set<std::string>> mKeywords; // keywords for code in the library std::unordered_map<std::string, CodeBlock> mExecutableBlocks; // keywords for blocks of executable code std::map<std::string, ExportedFunctions> mExporters; // keywords that export variables/functions to libraries (meta-code/macros) std::map<std::string, std::set<std::string>> mImporters; // keywords that import variables/functions std::map<std::string, int> mReflection; // invocation of reflection std::unordered_map<std::string, struct PodType> mPodTypes; // pod types std::map<std::string, PlatformType> mPlatformTypes; // platform independent typedefs std::map<std::string, Platform> mPlatforms; // platform dependent typedefs std::map<std::pair<std::string,std::string>, TypeCheck> mTypeChecks; std::unordered_map<std::string, NonOverlappingData> mNonOverlappingData; std::unordered_set<std::string> mEntrypoints; }; Library::Library() : mData(new LibraryData()) {} Library::~Library() = default; Library::Library(const Library& other) : mData(new LibraryData(*other.mData)) {} Library& Library::operator=(const Library& other) & { mData.reset(new LibraryData(*other.mData)); return *this; } static std::vector<std::string> getnames(const char *names) { std::vector<std::string> ret; while (const char *p = std::strchr(names,',')) { ret.emplace_back(names, p-names); names = p + 1; } ret.emplace_back(names); return ret; } static void gettokenlistfromvalid(const std::string& valid, bool cpp, TokenList& tokenList) { std::istringstream istr(valid + ','); tokenList.createTokens(istr, cpp ? Standards::Language::CPP : Standards::Language::C); // TODO: check result? for (Token *tok = tokenList.front(); tok; tok = tok->next()) { if (Token::Match(tok,"- %num%")) { tok->str("-" + tok->strAt(1)); tok->deleteNext(); } } } Library::Error Library::load(const char exename[], const char path[], bool debug) { if (std::strchr(path,',') != nullptr) { throw std::runtime_error("handling of multiple libraries not supported"); } const bool is_abs_path = Path::isAbsolute(path); std::string absolute_path; // open file.. tinyxml2::XMLDocument doc; if (debug) std::cout << "looking for library '" + std::string(path) + "'" << std::endl; tinyxml2::XMLError error = xml_LoadFile(doc, path); if (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND) { // failed to open file.. is there no extension? std::string fullfilename(path); if (Path::getFilenameExtension(fullfilename).empty()) { fullfilename += ".cfg"; if (debug) std::cout << "looking for library '" + fullfilename + "'" << std::endl; error = xml_LoadFile(doc, fullfilename.c_str()); if (error != tinyxml2::XML_ERROR_FILE_NOT_FOUND) absolute_path = Path::getAbsoluteFilePath(fullfilename); } // only perform further lookups when the given path was not absolute if (!is_abs_path && error == tinyxml2::XML_ERROR_FILE_NOT_FOUND) { std::list<std::string> cfgfolders; #ifdef FILESDIR cfgfolders.emplace_back(FILESDIR "/cfg"); #endif if (exename) { const std::string exepath(Path::fromNativeSeparators(Path::getPathFromFilename(Path::getCurrentExecutablePath(exename)))); cfgfolders.push_back(exepath + "cfg"); cfgfolders.push_back(exepath); } while (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND && !cfgfolders.empty()) { const std::string cfgfolder(cfgfolders.back()); cfgfolders.pop_back(); const char *sep = (!cfgfolder.empty() && endsWith(cfgfolder,'/') ? "" : "/"); const std::string filename(cfgfolder + sep + fullfilename); if (debug) std::cout << "looking for library '" + std::string(filename) + "'" << std::endl; error = xml_LoadFile(doc, filename.c_str()); if (error != tinyxml2::XML_ERROR_FILE_NOT_FOUND) absolute_path = Path::getAbsoluteFilePath(filename); } } } else absolute_path = Path::getAbsoluteFilePath(path); if (error == tinyxml2::XML_SUCCESS) { if (mData->mFiles.find(absolute_path) == mData->mFiles.end()) { Error err = load(doc); if (err.errorcode == ErrorCode::OK) mData->mFiles.insert(absolute_path); return err; } return Error(ErrorCode::OK); // ignore duplicates } if (debug) std::cout << "library not found: '" + std::string(path) + "'" << std::endl; if (error == tinyxml2::XML_ERROR_FILE_NOT_FOUND) return Error(ErrorCode::FILE_NOT_FOUND); doc.PrintError(); // TODO: do not print stray messages return Error(ErrorCode::BAD_XML); } Library::Container::Yield Library::Container::yieldFrom(const std::string& yieldName) { if (yieldName == "at_index") return Container::Yield::AT_INDEX; if (yieldName == "item") return Container::Yield::ITEM; if (yieldName == "buffer") return Container::Yield::BUFFER; if (yieldName == "buffer-nt") return Container::Yield::BUFFER_NT; if (yieldName == "start-iterator") return Container::Yield::START_ITERATOR; if (yieldName == "end-iterator") return Container::Yield::END_ITERATOR; if (yieldName == "iterator") return Container::Yield::ITERATOR; if (yieldName == "size") return Container::Yield::SIZE; if (yieldName == "empty") return Container::Yield::EMPTY; return Container::Yield::NO_YIELD; } Library::Container::Action Library::Container::actionFrom(const std::string& actionName) { if (actionName == "resize") return Container::Action::RESIZE; if (actionName == "clear") return Container::Action::CLEAR; if (actionName == "push") return Container::Action::PUSH; if (actionName == "pop") return Container::Action::POP; if (actionName == "find") return Container::Action::FIND; if (actionName == "find-const") return Container::Action::FIND_CONST; if (actionName == "insert") return Container::Action::INSERT; if (actionName == "erase") return Container::Action::ERASE; if (actionName == "append") return Container::Action::APPEND; if (actionName == "change-content") return Container::Action::CHANGE_CONTENT; if (actionName == "change-internal") return Container::Action::CHANGE_INTERNAL; if (actionName == "change") return Container::Action::CHANGE; return Container::Action::NO_ACTION; } Library::Error Library::load(const tinyxml2::XMLDocument &doc) { const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement(); if (rootnode == nullptr) { doc.PrintError(); return Error(ErrorCode::BAD_XML); } if (strcmp(rootnode->Name(),"def") != 0) return Error(ErrorCode::UNSUPPORTED_FORMAT, rootnode->Name()); const int format = rootnode->IntAttribute("format", 1); // Assume format version 1 if nothing else is specified (very old .cfg files had no 'format' attribute) if (format > 2 || format <= 0) return Error(ErrorCode::UNSUPPORTED_FORMAT); std::set<std::string> unknown_elements; for (const tinyxml2::XMLElement *node = rootnode->FirstChildElement(); node; node = node->NextSiblingElement()) { const std::string nodename = node->Name(); if (nodename == "memory" || nodename == "resource") { // get allocationId to use.. int allocationId = 0; for (const tinyxml2::XMLElement *memorynode = node->FirstChildElement(); memorynode; memorynode = memorynode->NextSiblingElement()) { if (strcmp(memorynode->Name(),"dealloc")==0) { const auto names = getnames(memorynode->GetText()); for (const auto& n : names) { const std::map<std::string, AllocFunc>::const_iterator it = mData->mDealloc.find(n); if (it != mData->mDealloc.end()) { allocationId = it->second.groupId; break; } } if (allocationId != 0) break; } } if (allocationId == 0) { if (nodename == "memory") while (!ismemory(++mData->mAllocId)) {} else while (!isresource(++mData->mAllocId)) {} allocationId = mData->mAllocId; } // add alloc/dealloc/use functions.. for (const tinyxml2::XMLElement *memorynode = node->FirstChildElement(); memorynode; memorynode = memorynode->NextSiblingElement()) { const std::string memorynodename = memorynode->Name(); const auto names = getnames(memorynode->GetText()); if (memorynodename == "alloc" || memorynodename == "realloc") { AllocFunc temp; temp.groupId = allocationId; temp.initData = memorynode->BoolAttribute("init", true); temp.arg = memorynode->IntAttribute("arg", -1); const char *bufferSize = memorynode->Attribute("buffer-size"); if (!bufferSize) temp.bufferSize = AllocFunc::BufferSize::none; else { if (std::strncmp(bufferSize, "malloc", 6) == 0) temp.bufferSize = AllocFunc::BufferSize::malloc; else if (std::strncmp(bufferSize, "calloc", 6) == 0) temp.bufferSize = AllocFunc::BufferSize::calloc; else if (std::strncmp(bufferSize, "strdup", 6) == 0) temp.bufferSize = AllocFunc::BufferSize::strdup; else return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, bufferSize); temp.bufferSizeArg1 = 1; temp.bufferSizeArg2 = 2; if (bufferSize[6] == 0) { // use default values } else if (bufferSize[6] == ':' && bufferSize[7] >= '1' && bufferSize[7] <= '5') { temp.bufferSizeArg1 = bufferSize[7] - '0'; if (bufferSize[8] == ',' && bufferSize[9] >= '1' && bufferSize[9] <= '5') temp.bufferSizeArg2 = bufferSize[9] - '0'; } else return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, bufferSize); } if (memorynodename == "realloc") temp.reallocArg = memorynode->IntAttribute("realloc-arg", 1); auto& map = (memorynodename == "realloc") ? mData->mRealloc : mData->mAlloc; for (const auto& n : names) map[n] = temp; } else if (memorynodename == "dealloc") { AllocFunc temp; temp.groupId = allocationId; temp.arg = memorynode->IntAttribute("arg", 1); for (const auto& n : names) mData->mDealloc[n] = temp; } else if (memorynodename == "use") for (const auto& n : names) mData->mFunctions[n].use = true; else unknown_elements.insert(memorynodename); } } else if (nodename == "define") { const char *name = node->Attribute("name"); if (name == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "name"); const char *value = node->Attribute("value"); if (value == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "value"); auto result = mData->mDefines.insert(std::string(name) + " " + value); if (!result.second) return Error(ErrorCode::DUPLICATE_DEFINE, name); } else if (nodename == "function") { const char *name = node->Attribute("name"); if (name == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "name"); for (const std::string &s : getnames(name)) { const Error &err = loadFunction(node, s, unknown_elements); if (err.errorcode != ErrorCode::OK) return err; } } else if (nodename == "reflection") { for (const tinyxml2::XMLElement *reflectionnode = node->FirstChildElement(); reflectionnode; reflectionnode = reflectionnode->NextSiblingElement()) { if (strcmp(reflectionnode->Name(), "call") != 0) { unknown_elements.insert(reflectionnode->Name()); continue; } const char * const argString = reflectionnode->Attribute("arg"); if (!argString) return Error(ErrorCode::MISSING_ATTRIBUTE, "arg"); mData->mReflection[reflectionnode->GetText()] = strToInt<int>(argString); } } else if (nodename == "markup") { const char * const extension = node->Attribute("ext"); if (!extension) return Error(ErrorCode::MISSING_ATTRIBUTE, "ext"); mData->mMarkupExtensions.insert(extension); mData->mReportErrors[extension] = (node->Attribute("reporterrors", "true") != nullptr); mData->mProcessAfterCode[extension] = (node->Attribute("aftercode", "true") != nullptr); for (const tinyxml2::XMLElement *markupnode = node->FirstChildElement(); markupnode; markupnode = markupnode->NextSiblingElement()) { const std::string markupnodename = markupnode->Name(); if (markupnodename == "keywords") { for (const tinyxml2::XMLElement *librarynode = markupnode->FirstChildElement(); librarynode; librarynode = librarynode->NextSiblingElement()) { if (strcmp(librarynode->Name(), "keyword") == 0) { const char* nodeName = librarynode->Attribute("name"); if (nodeName == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "name"); mData->mKeywords[extension].insert(nodeName); } else unknown_elements.insert(librarynode->Name()); } } else if (markupnodename == "exported") { for (const tinyxml2::XMLElement *exporter = markupnode->FirstChildElement(); exporter; exporter = exporter->NextSiblingElement()) { if (strcmp(exporter->Name(), "exporter") != 0) { unknown_elements.insert(exporter->Name()); continue; } const char * const prefix = exporter->Attribute("prefix"); if (!prefix) return Error(ErrorCode::MISSING_ATTRIBUTE, "prefix"); for (const tinyxml2::XMLElement *e = exporter->FirstChildElement(); e; e = e->NextSiblingElement()) { const std::string ename = e->Name(); if (ename == "prefix") mData->mExporters[prefix].addPrefix(e->GetText()); else if (ename == "suffix") mData->mExporters[prefix].addSuffix(e->GetText()); else unknown_elements.insert(ename); } } } else if (markupnodename == "imported") { for (const tinyxml2::XMLElement *librarynode = markupnode->FirstChildElement(); librarynode; librarynode = librarynode->NextSiblingElement()) { if (strcmp(librarynode->Name(), "importer") == 0) mData->mImporters[extension].insert(librarynode->GetText()); else unknown_elements.insert(librarynode->Name()); } } else if (markupnodename == "codeblocks") { for (const tinyxml2::XMLElement *blocknode = markupnode->FirstChildElement(); blocknode; blocknode = blocknode->NextSiblingElement()) { const std::string blocknodename = blocknode->Name(); if (blocknodename == "block") { const char * blockName = blocknode->Attribute("name"); if (blockName) mData->mExecutableBlocks[extension].addBlock(blockName); } else if (blocknodename == "structure") { const char * start = blocknode->Attribute("start"); if (start) mData->mExecutableBlocks[extension].setStart(start); const char * end = blocknode->Attribute("end"); if (end) mData->mExecutableBlocks[extension].setEnd(end); const char * offset = blocknode->Attribute("offset"); if (offset) { // cppcheck-suppress templateInstantiation - TODO: fix this - see #11631 mData->mExecutableBlocks[extension].setOffset(strToInt<int>(offset)); } } else unknown_elements.insert(blocknodename); } } else unknown_elements.insert(markupnodename); } } else if (nodename == "container") { const char* const id = node->Attribute("id"); if (!id) return Error(ErrorCode::MISSING_ATTRIBUTE, "id"); Container& container = mData->mContainers[id]; const char* const inherits = node->Attribute("inherits"); if (inherits) { const std::unordered_map<std::string, Container>::const_iterator i = mData->mContainers.find(inherits); if (i != mData->mContainers.end()) container = i->second; // Take values from parent and overwrite them if necessary else return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, inherits); } const char* const startPattern = node->Attribute("startPattern"); if (startPattern) { container.startPattern = startPattern; container.startPattern2 = startPattern; if (!endsWith(container.startPattern, '<')) container.startPattern2 += " !!::"; } const char* const endPattern = node->Attribute("endPattern"); if (endPattern) container.endPattern = endPattern; const char* const itEndPattern = node->Attribute("itEndPattern"); if (itEndPattern) container.itEndPattern = itEndPattern; const char* const opLessAllowed = node->Attribute("opLessAllowed"); if (opLessAllowed) container.opLessAllowed = strcmp(opLessAllowed, "true") == 0; const char* const hasInitializerListConstructor = node->Attribute("hasInitializerListConstructor"); if (hasInitializerListConstructor) container.hasInitializerListConstructor = strcmp(hasInitializerListConstructor, "true") == 0; const char* const view = node->Attribute("view"); if (view) container.view = strcmp(view, "true") == 0; for (const tinyxml2::XMLElement *containerNode = node->FirstChildElement(); containerNode; containerNode = containerNode->NextSiblingElement()) { const std::string containerNodeName = containerNode->Name(); if (containerNodeName == "size" || containerNodeName == "access" || containerNodeName == "other") { for (const tinyxml2::XMLElement *functionNode = containerNode->FirstChildElement(); functionNode; functionNode = functionNode->NextSiblingElement()) { if (strcmp(functionNode->Name(), "function") != 0) { unknown_elements.insert(functionNode->Name()); continue; } const char* const functionName = functionNode->Attribute("name"); if (!functionName) return Error(ErrorCode::MISSING_ATTRIBUTE, "name"); const char* const action_ptr = functionNode->Attribute("action"); Container::Action action = Container::Action::NO_ACTION; if (action_ptr) { std::string actionName = action_ptr; action = Container::actionFrom(actionName); if (action == Container::Action::NO_ACTION) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, actionName); } const char* const yield_ptr = functionNode->Attribute("yields"); Container::Yield yield = Container::Yield::NO_YIELD; if (yield_ptr) { std::string yieldName = yield_ptr; yield = Container::yieldFrom(yieldName); if (yield == Container::Yield::NO_YIELD) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, yieldName); } const char* const returnType = functionNode->Attribute("returnType"); if (returnType) container.functions[functionName].returnType = returnType; container.functions[functionName].action = action; container.functions[functionName].yield = yield; } if (containerNodeName == "size") { const char* const templateArg = containerNode->Attribute("templateParameter"); if (templateArg) container.size_templateArgNo = strToInt<int>(templateArg); } else if (containerNodeName == "access") { const char* const indexArg = containerNode->Attribute("indexOperator"); if (indexArg) container.arrayLike_indexOp = strcmp(indexArg, "array-like") == 0; } } else if (containerNodeName == "type") { const char* const templateArg = containerNode->Attribute("templateParameter"); if (templateArg) container.type_templateArgNo = strToInt<int>(templateArg); const char* const string = containerNode->Attribute("string"); if (string) container.stdStringLike = strcmp(string, "std-like") == 0; const char* const associative = containerNode->Attribute("associative"); if (associative) container.stdAssociativeLike = strcmp(associative, "std-like") == 0; const char* const unstable = containerNode->Attribute("unstable"); if (unstable) { std::string unstableType = unstable; if (unstableType.find("erase") != std::string::npos) container.unstableErase = true; if (unstableType.find("insert") != std::string::npos) container.unstableInsert = true; } } else if (containerNodeName == "rangeItemRecordType") { for (const tinyxml2::XMLElement* memberNode = node->FirstChildElement(); memberNode; memberNode = memberNode->NextSiblingElement()) { const char *memberName = memberNode->Attribute("name"); const char *memberTemplateParameter = memberNode->Attribute("templateParameter"); Container::RangeItemRecordTypeItem member; member.name = memberName ? memberName : ""; member.templateParameter = memberTemplateParameter ? strToInt<int>(memberTemplateParameter) : -1; container.rangeItemRecordType.emplace_back(std::move(member)); } } else unknown_elements.insert(containerNodeName); } } else if (nodename == "smart-pointer") { const char *className = node->Attribute("class-name"); if (!className) return Error(ErrorCode::MISSING_ATTRIBUTE, "class-name"); SmartPointer& smartPointer = mData->mSmartPointers[className]; smartPointer.name = className; for (const tinyxml2::XMLElement* smartPointerNode = node->FirstChildElement(); smartPointerNode; smartPointerNode = smartPointerNode->NextSiblingElement()) { const std::string smartPointerNodeName = smartPointerNode->Name(); if (smartPointerNodeName == "unique") smartPointer.unique = true; } } else if (nodename == "type-checks") { for (const tinyxml2::XMLElement *checkNode = node->FirstChildElement(); checkNode; checkNode = checkNode->NextSiblingElement()) { const std::string &checkName = checkNode->Name(); for (const tinyxml2::XMLElement *checkTypeNode = checkNode->FirstChildElement(); checkTypeNode; checkTypeNode = checkTypeNode->NextSiblingElement()) { const std::string checkTypeName = checkTypeNode->Name(); const char *typeName = checkTypeNode->GetText(); if (!typeName) continue; if (checkTypeName == "check") mData->mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::check; else if (checkTypeName == "suppress") mData->mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::suppress; else if (checkTypeName == "checkFiniteLifetime") mData->mTypeChecks[std::pair<std::string,std::string>(checkName, typeName)] = TypeCheck::checkFiniteLifetime; } } } else if (nodename == "podtype") { const char * const name = node->Attribute("name"); if (!name) return Error(ErrorCode::MISSING_ATTRIBUTE, "name"); PodType podType; podType.stdtype = PodType::Type::NO; const char * const stdtype = node->Attribute("stdtype"); if (stdtype) { if (std::strcmp(stdtype, "bool") == 0) podType.stdtype = PodType::Type::BOOL; else if (std::strcmp(stdtype, "char") == 0) podType.stdtype = PodType::Type::CHAR; else if (std::strcmp(stdtype, "short") == 0) podType.stdtype = PodType::Type::SHORT; else if (std::strcmp(stdtype, "int") == 0) podType.stdtype = PodType::Type::INT; else if (std::strcmp(stdtype, "long") == 0) podType.stdtype = PodType::Type::LONG; else if (std::strcmp(stdtype, "long long") == 0) podType.stdtype = PodType::Type::LONGLONG; } const char * const size = node->Attribute("size"); if (size) podType.size = strToInt<unsigned int>(size); const char * const sign = node->Attribute("sign"); if (sign) podType.sign = *sign; for (const std::string &s : getnames(name)) mData->mPodTypes[s] = podType; } else if (nodename == "platformtype") { const char * const type_name = node->Attribute("name"); if (type_name == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "name"); const char *value = node->Attribute("value"); if (value == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "value"); PlatformType type; type.mType = value; std::set<std::string> platform; for (const tinyxml2::XMLElement *typenode = node->FirstChildElement(); typenode; typenode = typenode->NextSiblingElement()) { const std::string typenodename = typenode->Name(); if (typenodename == "platform") { const char * const type_attribute = typenode->Attribute("type"); if (type_attribute == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "type"); platform.insert(type_attribute); } else if (typenodename == "signed") type.mSigned = true; else if (typenodename == "unsigned") type.mUnsigned = true; else if (typenodename == "long") type.mLong = true; else if (typenodename == "pointer") type.mPointer= true; else if (typenodename == "ptr_ptr") type.mPtrPtr = true; else if (typenodename == "const_ptr") type.mConstPtr = true; else unknown_elements.insert(typenodename); } if (platform.empty()) { const PlatformType * const type_ptr = platform_type(type_name, emptyString); if (type_ptr) { if (*type_ptr == type) return Error(ErrorCode::DUPLICATE_PLATFORM_TYPE, type_name); return Error(ErrorCode::PLATFORM_TYPE_REDEFINED, type_name); } mData->mPlatformTypes[type_name] = std::move(type); } else { for (const std::string &p : platform) { const PlatformType * const type_ptr = platform_type(type_name, p); if (type_ptr) { if (*type_ptr == type) return Error(ErrorCode::DUPLICATE_PLATFORM_TYPE, type_name); return Error(ErrorCode::PLATFORM_TYPE_REDEFINED, type_name); } mData->mPlatforms[p].mPlatformTypes[type_name] = type; } } } else if (nodename == "entrypoint") { const char * const type_name = node->Attribute("name"); if (type_name == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "name"); mData->mEntrypoints.emplace(type_name); } else unknown_elements.insert(nodename); } if (!unknown_elements.empty()) { std::string str; for (std::set<std::string>::const_iterator i = unknown_elements.cbegin(); i != unknown_elements.cend();) { str += *i; if (++i != unknown_elements.end()) str += ", "; } return Error(ErrorCode::UNKNOWN_ELEMENT, str); } return Error(ErrorCode::OK); } Library::Error Library::loadFunction(const tinyxml2::XMLElement * const node, const std::string &name, std::set<std::string> &unknown_elements) { if (name.empty()) return Error(ErrorCode::OK); // TODO: write debug warning if we modify an existing entry Function& func = mData->mFunctions[name]; for (const tinyxml2::XMLElement *functionnode = node->FirstChildElement(); functionnode; functionnode = functionnode->NextSiblingElement()) { const std::string functionnodename = functionnode->Name(); if (functionnodename == "noreturn") { const char * const text = functionnode->GetText(); if (strcmp(text, "false") == 0) mData->mNoReturn[name] = LibraryData::FalseTrueMaybe::False; else if (strcmp(text, "maybe") == 0) mData->mNoReturn[name] = LibraryData::FalseTrueMaybe::Maybe; else mData->mNoReturn[name] = LibraryData::FalseTrueMaybe::True; // Safe } else if (functionnodename == "pure") func.ispure = true; else if (functionnodename == "const") { func.ispure = true; func.isconst = true; // a constant function is pure } else if (functionnodename == "leak-ignore") func.leakignore = true; else if (functionnodename == "not-overlapping-data") { NonOverlappingData nonOverlappingData; nonOverlappingData.ptr1Arg = functionnode->IntAttribute("ptr1-arg", -1); nonOverlappingData.ptr2Arg = functionnode->IntAttribute("ptr2-arg", -1); nonOverlappingData.sizeArg = functionnode->IntAttribute("size-arg", -1); nonOverlappingData.strlenArg = functionnode->IntAttribute("strlen-arg", -1); nonOverlappingData.countArg = functionnode->IntAttribute("count-arg", -1); mData->mNonOverlappingData[name] = nonOverlappingData; } else if (functionnodename == "use-retval") { func.useretval = Library::UseRetValType::DEFAULT; if (const char *type = functionnode->Attribute("type")) if (std::strcmp(type, "error-code") == 0) func.useretval = Library::UseRetValType::ERROR_CODE; } else if (functionnodename == "returnValue") { if (const char *expr = functionnode->GetText()) mData->mReturnValue[name] = expr; if (const char *type = functionnode->Attribute("type")) mData->mReturnValueType[name] = type; if (const char *container = functionnode->Attribute("container")) mData->mReturnValueContainer[name] = strToInt<int>(container); // cppcheck-suppress shadowFunction - TODO: fix this if (const char *unknownReturnValues = functionnode->Attribute("unknownValues")) { if (std::strcmp(unknownReturnValues, "all") == 0) { std::vector<MathLib::bigint> values{LLONG_MIN, LLONG_MAX}; mData->mUnknownReturnValues[name] = std::move(values); } } } else if (functionnodename == "arg") { const char* argNrString = functionnode->Attribute("nr"); if (!argNrString) return Error(ErrorCode::MISSING_ATTRIBUTE, "nr"); const bool bAnyArg = strcmp(argNrString, "any") == 0; const bool bVariadicArg = strcmp(argNrString, "variadic") == 0; const int nr = (bAnyArg || bVariadicArg) ? -1 : strToInt<int>(argNrString); ArgumentChecks &ac = func.argumentChecks[nr]; ac.optional = functionnode->Attribute("default") != nullptr; ac.variadic = bVariadicArg; const char * const argDirection = functionnode->Attribute("direction"); if (argDirection) { const size_t argDirLen = strlen(argDirection); ArgumentChecks::Direction dir = ArgumentChecks::Direction::DIR_UNKNOWN; if (!strncmp(argDirection, "in", argDirLen)) { dir = ArgumentChecks::Direction::DIR_IN; } else if (!strncmp(argDirection, "out", argDirLen)) { dir = ArgumentChecks::Direction::DIR_OUT; } else if (!strncmp(argDirection, "inout", argDirLen)) { dir = ArgumentChecks::Direction::DIR_INOUT; } if (const char* const argIndirect = functionnode->Attribute("indirect")) { const int indirect = strToInt<int>(argIndirect); ac.direction[indirect] = dir; // TODO: handle multiple directions/indirect levels } else ac.direction.fill(dir); } for (const tinyxml2::XMLElement *argnode = functionnode->FirstChildElement(); argnode; argnode = argnode->NextSiblingElement()) { const std::string argnodename = argnode->Name(); int indirect = 0; const char * const indirectStr = argnode->Attribute("indirect"); if (indirectStr) indirect = strToInt<int>(indirectStr); if (argnodename == "not-bool") ac.notbool = true; else if (argnodename == "not-null") ac.notnull = true; else if (argnodename == "not-uninit") ac.notuninit = indirect; else if (argnodename == "formatstr") ac.formatstr = true; else if (argnodename == "strz") ac.strz = true; else if (argnodename == "valid") { // Validate the validation expression const char *p = argnode->GetText(); if (!isCompliantValidationExpression(p)) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, (!p ? "\"\"" : p)); // Set validation expression ac.valid = p; } else if (argnodename == "minsize") { const char *typeattr = argnode->Attribute("type"); if (!typeattr) return Error(ErrorCode::MISSING_ATTRIBUTE, "type"); ArgumentChecks::MinSize::Type type; if (strcmp(typeattr,"strlen")==0) type = ArgumentChecks::MinSize::Type::STRLEN; else if (strcmp(typeattr,"argvalue")==0) type = ArgumentChecks::MinSize::Type::ARGVALUE; else if (strcmp(typeattr,"sizeof")==0) type = ArgumentChecks::MinSize::Type::SIZEOF; else if (strcmp(typeattr,"mul")==0) type = ArgumentChecks::MinSize::Type::MUL; else if (strcmp(typeattr,"value")==0) type = ArgumentChecks::MinSize::Type::VALUE; else return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, typeattr); if (type == ArgumentChecks::MinSize::Type::VALUE) { const char *valueattr = argnode->Attribute("value"); if (!valueattr) return Error(ErrorCode::MISSING_ATTRIBUTE, "value"); long long minsizevalue = 0; try { minsizevalue = strToInt<long long>(valueattr); } catch (const std::runtime_error&) { return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, valueattr); } if (minsizevalue <= 0) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, valueattr); ac.minsizes.emplace_back(type, 0); ac.minsizes.back().value = minsizevalue; } else { const char *argattr = argnode->Attribute("arg"); if (!argattr) return Error(ErrorCode::MISSING_ATTRIBUTE, "arg"); if (strlen(argattr) != 1 || argattr[0]<'0' || argattr[0]>'9') return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, argattr); ac.minsizes.reserve(type == ArgumentChecks::MinSize::Type::MUL ? 2 : 1); ac.minsizes.emplace_back(type, argattr[0] - '0'); if (type == ArgumentChecks::MinSize::Type::MUL) { const char *arg2attr = argnode->Attribute("arg2"); if (!arg2attr) return Error(ErrorCode::MISSING_ATTRIBUTE, "arg2"); if (strlen(arg2attr) != 1 || arg2attr[0]<'0' || arg2attr[0]>'9') return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, arg2attr); ac.minsizes.back().arg2 = arg2attr[0] - '0'; } } const char* baseTypeAttr = argnode->Attribute("baseType"); // used by VALUE, ARGVALUE if (baseTypeAttr) ac.minsizes.back().baseType = baseTypeAttr; } else if (argnodename == "iterator") { ac.iteratorInfo.it = true; const char* str = argnode->Attribute("type"); ac.iteratorInfo.first = (str && std::strcmp(str, "first") == 0); ac.iteratorInfo.last = (str && std::strcmp(str, "last") == 0); ac.iteratorInfo.container = argnode->IntAttribute("container", 0); } else unknown_elements.insert(argnodename); } if (ac.notuninit == 0) ac.notuninit = ac.notnull ? 1 : 0; } else if (functionnodename == "ignorefunction") { func.ignore = true; } else if (functionnodename == "formatstr") { func.formatstr = true; const tinyxml2::XMLAttribute* scan = functionnode->FindAttribute("scan"); const tinyxml2::XMLAttribute* secure = functionnode->FindAttribute("secure"); func.formatstr_scan = scan && scan->BoolValue(); func.formatstr_secure = secure && secure->BoolValue(); } else if (functionnodename == "warn") { WarnInfo wi; const char* const severity = functionnode->Attribute("severity"); if (severity == nullptr) return Error(ErrorCode::MISSING_ATTRIBUTE, "severity"); wi.severity = severityFromString(severity); const char* const cstd = functionnode->Attribute("cstd"); if (cstd) { if (!wi.standards.setC(cstd)) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, cstd); } else wi.standards.c = Standards::C89; const char* const cppstd = functionnode->Attribute("cppstd"); if (cppstd) { if (!wi.standards.setCPP(cppstd)) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, cppstd); } else wi.standards.cpp = Standards::CPP03; const char* const reason = functionnode->Attribute("reason"); const char* const alternatives = functionnode->Attribute("alternatives"); if (reason && alternatives) { // Construct message wi.message = std::string(reason) + " function '" + name + "' called. It is recommended to use "; std::vector<std::string> alt = getnames(alternatives); for (std::size_t i = 0; i < alt.size(); ++i) { wi.message += "'" + alt[i] + "'"; if (i == alt.size() - 1) wi.message += " instead."; else if (i == alt.size() - 2) wi.message += " or "; else wi.message += ", "; } } else { const char * const message = functionnode->GetText(); if (!message) return Error(ErrorCode::MISSING_ATTRIBUTE, "\"reason\" and \"alternatives\" or some text."); wi.message = message; } mData->mFunctionwarn[name] = std::move(wi); } else if (functionnodename == "container") { const char* const action_ptr = functionnode->Attribute("action"); Container::Action action = Container::Action::NO_ACTION; if (action_ptr) { std::string actionName = action_ptr; action = Container::actionFrom(actionName); if (action == Container::Action::NO_ACTION) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, actionName); } func.containerAction = action; const char* const yield_ptr = functionnode->Attribute("yields"); Container::Yield yield = Container::Yield::NO_YIELD; if (yield_ptr) { std::string yieldName = yield_ptr; yield = Container::yieldFrom(yieldName); if (yield == Container::Yield::NO_YIELD) return Error(ErrorCode::BAD_ATTRIBUTE_VALUE, yieldName); } func.containerYield = yield; const char* const returnType = functionnode->Attribute("returnType"); if (returnType) func.returnType = returnType; } else unknown_elements.insert(functionnodename); } return Error(ErrorCode::OK); } bool Library::isIntArgValid(const Token *ftok, int argnr, const MathLib::bigint argvalue) const { const ArgumentChecks *ac = getarg(ftok, argnr); if (!ac || ac->valid.empty()) return true; if (ac->valid.find('.') != std::string::npos) return isFloatArgValid(ftok, argnr, argvalue); TokenList tokenList(nullptr); gettokenlistfromvalid(ac->valid, ftok->isCpp(), tokenList); for (const Token *tok = tokenList.front(); tok; tok = tok->next()) { if (tok->isNumber() && argvalue == MathLib::toBigNumber(tok->str())) return true; if (Token::Match(tok, "%num% : %num%") && argvalue >= MathLib::toBigNumber(tok->str()) && argvalue <= MathLib::toBigNumber(tok->strAt(2))) return true; if (Token::Match(tok, "%num% : ,") && argvalue >= MathLib::toBigNumber(tok->str())) return true; if ((!tok->previous() || tok->strAt(-1) == ",") && Token::Match(tok,": %num%") && argvalue <= MathLib::toBigNumber(tok->strAt(1))) return true; } return false; } bool Library::isFloatArgValid(const Token *ftok, int argnr, double argvalue) const { const ArgumentChecks *ac = getarg(ftok, argnr); if (!ac || ac->valid.empty()) return true; TokenList tokenList(nullptr); gettokenlistfromvalid(ac->valid, ftok->isCpp(), tokenList); for (const Token *tok = tokenList.front(); tok; tok = tok->next()) { if (Token::Match(tok, "%num% : %num%") && argvalue >= MathLib::toDoubleNumber(tok->str()) && argvalue <= MathLib::toDoubleNumber(tok->strAt(2))) return true; if (Token::Match(tok, "%num% : ,") && argvalue >= MathLib::toDoubleNumber(tok->str())) return true; if ((!tok->previous() || tok->strAt(-1) == ",") && Token::Match(tok,": %num%") && argvalue <= MathLib::toDoubleNumber(tok->strAt(1))) return true; if (Token::Match(tok, "%num%") && MathLib::isFloat(tok->str()) && MathLib::isEqual(tok->str(), MathLib::toString(argvalue))) return true; if (Token::Match(tok, "! %num%") && MathLib::isFloat(tok->strAt(1))) return MathLib::isNotEqual(tok->strAt(1), MathLib::toString(argvalue)); } return false; } std::string Library::getFunctionName(const Token *ftok, bool &error) const { if (!ftok) { error = true; return ""; } if (ftok->isName()) { if (Token::simpleMatch(ftok->astParent(), "::")) return ftok->str(); for (const Scope *scope = ftok->scope(); scope; scope = scope->nestedIn) { if (!scope->isClassOrStruct()) continue; const std::vector<Type::BaseInfo> &derivedFrom = scope->definedType->derivedFrom; for (const Type::BaseInfo & baseInfo : derivedFrom) { std::string name; const Token* tok = baseInfo.nameTok; // baseInfo.name still contains template parameters, but is missing namespaces if (tok->str() == "::") tok = tok->next(); while (Token::Match(tok, "%name%|::")) { name += tok->str(); tok = tok->next(); } name += "::" + ftok->str(); if (mData->mFunctions.find(name) != mData->mFunctions.end() && matchArguments(ftok, name)) return name; } } return ftok->str(); } if (ftok->str() == "::") { if (!ftok->astOperand2()) return getFunctionName(ftok->astOperand1(), error); return getFunctionName(ftok->astOperand1(),error) + "::" + getFunctionName(ftok->astOperand2(),error); } if (ftok->str() == "." && ftok->astOperand1()) { const std::string type = astCanonicalType(ftok->astOperand1(), ftok->originalName() == "->"); if (type.empty()) { error = true; return ""; } return type + "::" + getFunctionName(ftok->astOperand2(),error); } error = true; return ""; } std::string Library::getFunctionName(const Token *ftok) const { if (!Token::Match(ftok, "%name% )| (") && (ftok->strAt(-1) != "&" || ftok->previous()->astOperand2())) return ""; // Lookup function name using AST.. if (ftok->astParent()) { bool error = false; const Token * tok = ftok->astParent()->isUnaryOp("&") ? ftok->astParent()->astOperand1() : ftok->next()->astOperand1(); std::string ret = getFunctionName(tok, error); if (error) return {}; if (startsWith(ret, "::")) ret.erase(0, 2); return ret; } // Lookup function name without using AST.. if (Token::simpleMatch(ftok->previous(), ".")) return ""; if (!Token::Match(ftok->tokAt(-2), "%name% ::")) return ftok->str(); std::string ret(ftok->str()); ftok = ftok->tokAt(-2); while (Token::Match(ftok, "%name% ::")) { ret = ftok->str() + "::" + ret; ftok = ftok->tokAt(-2); } return ret; } bool Library::isnullargbad(const Token *ftok, int argnr) const { const ArgumentChecks *arg = getarg(ftok, argnr); if (!arg) { // scan format string argument should not be null const std::string funcname = getFunctionName(ftok); const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(funcname); if (it != mData->mFunctions.cend() && it->second.formatstr && it->second.formatstr_scan) return true; } return arg && arg->notnull; } bool Library::isuninitargbad(const Token *ftok, int argnr, int indirect, bool *hasIndirect) const { const ArgumentChecks *arg = getarg(ftok, argnr); if (!arg) { // non-scan format string argument should not be uninitialized const std::string funcname = getFunctionName(ftok); const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(funcname); if (it != mData->mFunctions.cend() && it->second.formatstr && !it->second.formatstr_scan) return true; } if (hasIndirect && arg && arg->notuninit >= 1) *hasIndirect = true; return arg && arg->notuninit >= indirect; } /** get allocation info for function */ const Library::AllocFunc* Library::getAllocFuncInfo(const Token *tok) const { while (Token::simpleMatch(tok, "::")) tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1(); const std::string funcname = getFunctionName(tok); return isNotLibraryFunction(tok) && mData->mFunctions.find(funcname) != mData->mFunctions.end() ? nullptr : getAllocDealloc(mData->mAlloc, funcname); } /** get deallocation info for function */ const Library::AllocFunc* Library::getDeallocFuncInfo(const Token *tok) const { while (Token::simpleMatch(tok, "::")) tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1(); const std::string funcname = getFunctionName(tok); return isNotLibraryFunction(tok) && mData->mFunctions.find(funcname) != mData->mFunctions.end() ? nullptr : getAllocDealloc(mData->mDealloc, funcname); } /** get reallocation info for function */ const Library::AllocFunc* Library::getReallocFuncInfo(const Token *tok) const { while (Token::simpleMatch(tok, "::")) tok = tok->astOperand2() ? tok->astOperand2() : tok->astOperand1(); const std::string funcname = getFunctionName(tok); return isNotLibraryFunction(tok) && mData->mFunctions.find(funcname) != mData->mFunctions.end() ? nullptr : getAllocDealloc(mData->mRealloc, funcname); } /** get allocation id for function */ int Library::getAllocId(const Token *tok, int arg) const { const Library::AllocFunc* af = getAllocFuncInfo(tok); return (af && af->arg == arg) ? af->groupId : 0; } /** get deallocation id for function */ int Library::getDeallocId(const Token *tok, int arg) const { const Library::AllocFunc* af = getDeallocFuncInfo(tok); return (af && af->arg == arg) ? af->groupId : 0; } /** get reallocation id for function */ int Library::getReallocId(const Token *tok, int arg) const { const Library::AllocFunc* af = getReallocFuncInfo(tok); return (af && af->arg == arg) ? af->groupId : 0; } const Library::ArgumentChecks * Library::getarg(const Token *ftok, int argnr) const { const Function* func = nullptr; if (isNotLibraryFunction(ftok, &func)) return nullptr; const std::map<int,ArgumentChecks>::const_iterator it2 = func->argumentChecks.find(argnr); if (it2 != func->argumentChecks.cend()) return &it2->second; const std::map<int,ArgumentChecks>::const_iterator it3 = func->argumentChecks.find(-1); if (it3 != func->argumentChecks.cend()) return &it3->second; return nullptr; } bool Library::isScopeNoReturn(const Token *end, std::string *unknownFunc) const { if (unknownFunc) unknownFunc->clear(); if (Token::Match(end->tokAt(-2), "!!{ ; }")) { const Token *lastTop = end->tokAt(-2)->astTop(); if (Token::simpleMatch(lastTop, "<<") && Token::simpleMatch(lastTop->astOperand1(), "(") && Token::Match(lastTop->astOperand1()->previous(), "%name% (")) return isnoreturn(lastTop->astOperand1()->previous()); } if (!Token::simpleMatch(end->tokAt(-2), ") ; }")) return false; const Token *funcname = end->linkAt(-2)->previous(); if (funcname->isCpp() && funcname->astTop()->str() == "throw") return true; const Token *start = funcname; if (Token::Match(funcname->tokAt(-3),"( * %name% )")) { funcname = funcname->previous(); start = funcname->tokAt(-3); } else if (funcname->isName()) { while (Token::Match(start, "%name%|.|::")) start = start->previous(); } else { return false; } if (Token::Match(start,"[;{}]") && Token::Match(funcname, "%name% )| (")) { if (funcname->isKeyword()) return false; if (funcname->str() == "exit") return true; if (!isnotnoreturn(funcname)) { if (unknownFunc && !isnoreturn(funcname)) *unknownFunc = funcname->str(); return true; } } return false; } // cppcheck-suppress unusedFunction - used in tests only const std::unordered_map<std::string, Library::Container>& Library::containers() const { return mData->mContainers; } const Library::Container* Library::detectContainerInternal(const Token* const typeStart, DetectContainer detect, bool* isIterator, bool withoutStd) const { if (!typeStart) return nullptr; const Token* firstLinkedTok = nullptr; for (const Token* tok = typeStart; tok && !tok->varId(); tok = tok->next()) { if (!tok->link()) continue; firstLinkedTok = tok; break; } for (const std::pair<const std::string, Library::Container> & c : mData->mContainers) { const Container& container = c.second; if (container.startPattern.empty()) continue; const int offset = (withoutStd && startsWith(container.startPattern2, "std :: ")) ? 7 : 0; // If endPattern is undefined, it will always match, but itEndPattern has to be defined. if (detect != IteratorOnly && container.endPattern.empty()) { if (!Token::Match(typeStart, container.startPattern2.c_str() + offset)) continue; if (isIterator) *isIterator = false; return &container; } if (!firstLinkedTok) continue; const bool matchedStartPattern = Token::Match(typeStart, container.startPattern2.c_str() + offset); if (!matchedStartPattern) continue; if (detect != ContainerOnly && Token::Match(firstLinkedTok->link(), container.itEndPattern.c_str())) { if (isIterator) *isIterator = true; return &container; } if (detect != IteratorOnly && Token::Match(firstLinkedTok->link(), container.endPattern.c_str())) { if (isIterator) *isIterator = false; return &container; } } return nullptr; } const Library::Container* Library::detectContainer(const Token* typeStart) const { return detectContainerInternal(typeStart, ContainerOnly); } const Library::Container* Library::detectIterator(const Token* typeStart) const { return detectContainerInternal(typeStart, IteratorOnly); } const Library::Container* Library::detectContainerOrIterator(const Token* typeStart, bool* isIterator, bool withoutStd) const { bool res; const Library::Container* c = detectContainerInternal(typeStart, Both, &res, withoutStd); if (c && isIterator) *isIterator = res; return c; } bool Library::isContainerYield(const Token * const cond, Library::Container::Yield y, const std::string& fallback) { if (!cond) return false; if (cond->str() == "(") { const Token* tok = cond->astOperand1(); if (tok && tok->str() == ".") { if (tok->astOperand1() && tok->astOperand1()->valueType()) { if (const Library::Container *container = tok->astOperand1()->valueType()->container) { return tok->astOperand2() && y == container->getYield(tok->astOperand2()->str()); } } else if (!fallback.empty()) { return Token::simpleMatch(cond, "( )") && cond->strAt(-1) == fallback; } } } return false; } Library::Container::Yield Library::getContainerYield(const Token* const cond) { if (Token::simpleMatch(cond, "(")) { const Token* tok = cond->astOperand1(); if (tok && tok->str() == ".") { if (tok->astOperand1() && tok->astOperand1()->valueType()) { if (const Library::Container *container = tok->astOperand1()->valueType()->container) { if (tok->astOperand2()) return container->getYield(tok->astOperand2()->str()); } } } } return Library::Container::Yield::NO_YIELD; } // returns true if ftok is not a library function bool Library::isNotLibraryFunction(const Token *ftok, const Function **func) const { if (ftok->isKeyword() || ftok->isStandardType()) return true; if (ftok->function() && ftok->function()->nestedIn && ftok->function()->nestedIn->type != Scope::eGlobal) return true; // variables are not library functions. if (ftok->varId()) return true; return !matchArguments(ftok, getFunctionName(ftok), func); } bool Library::matchArguments(const Token *ftok, const std::string &functionName, const Function **func) const { if (functionName.empty()) return false; const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName); if (it == mData->mFunctions.cend()) return false; const int callargs = numberOfArgumentsWithoutAst(ftok); int args = 0; int firstOptionalArg = -1; for (const std::pair<const int, Library::ArgumentChecks> & argCheck : it->second.argumentChecks) { args = std::max(argCheck.first, args); if (argCheck.second.optional && (firstOptionalArg == -1 || firstOptionalArg > argCheck.first)) firstOptionalArg = argCheck.first; if (argCheck.second.formatstr || argCheck.second.variadic) { const bool b = args <= callargs; if (b && func) *func = &it->second; return b; } } const bool b = (firstOptionalArg < 0) ? args == callargs : (callargs >= firstOptionalArg-1 && callargs <= args); if (b && func) *func = &it->second; return b; } const std::map<std::string, Library::WarnInfo>& Library::functionwarn() const { return mData->mFunctionwarn; } const Library::WarnInfo* Library::getWarnInfo(const Token* ftok) const { if (isNotLibraryFunction(ftok)) return nullptr; const std::map<std::string, WarnInfo>::const_iterator i = mData->mFunctionwarn.find(getFunctionName(ftok)); if (i == mData->mFunctionwarn.cend()) return nullptr; return &i->second; } bool Library::isCompliantValidationExpression(const char* p) { if (!p || !*p) return false; bool error = false; bool range = false; bool has_dot = false; bool has_E = false; error = *p == '.'; for (; *p; p++) { if (std::isdigit(*p)) { error |= (*(p + 1) == '-'); } else if (*p == ':') { // cppcheck-suppress bitwiseOnBoolean - TODO: fix this error |= range | (*(p + 1) == '.'); range = true; has_dot = false; has_E = false; } else if ((*p == '-') || (*p == '+')) { error |= (!std::isdigit(*(p + 1))); } else if (*p == ',') { range = false; error |= *(p + 1) == '.'; has_dot = false; has_E = false; } else if (*p == '.') { // cppcheck-suppress bitwiseOnBoolean - TODO: fix this error |= has_dot | (!std::isdigit(*(p + 1))); has_dot = true; } else if (*p == 'E' || *p == 'e') { error |= has_E; has_E = true; } else if (*p == '!') { error |= !((*(p+1) == '-') || (*(p+1) == '+') || (std::isdigit(*(p + 1)))); } else return false; } return !error; } bool Library::formatstr_function(const Token* ftok) const { if (isNotLibraryFunction(ftok)) return false; const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok)); if (it != mData->mFunctions.cend()) return it->second.formatstr; return false; } int Library::formatstr_argno(const Token* ftok) const { const std::map<int, Library::ArgumentChecks>& argumentChecksFunc = mData->mFunctions.at(getFunctionName(ftok)).argumentChecks; auto it = std::find_if(argumentChecksFunc.cbegin(), argumentChecksFunc.cend(), [](const std::pair<const int, Library::ArgumentChecks>& a) { return a.second.formatstr; }); return it == argumentChecksFunc.cend() ? -1 : it->first - 1; } bool Library::formatstr_scan(const Token* ftok) const { return mData->mFunctions.at(getFunctionName(ftok)).formatstr_scan; } bool Library::formatstr_secure(const Token* ftok) const { return mData->mFunctions.at(getFunctionName(ftok)).formatstr_secure; } const Library::NonOverlappingData* Library::getNonOverlappingData(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return nullptr; const std::unordered_map<std::string, NonOverlappingData>::const_iterator it = mData->mNonOverlappingData.find(getFunctionName(ftok)); return (it != mData->mNonOverlappingData.cend()) ? &it->second : nullptr; } Library::UseRetValType Library::getUseRetValType(const Token *ftok) const { if (isNotLibraryFunction(ftok)) { if (Token::simpleMatch(ftok->astParent(), ".")) { const Token* contTok = ftok->astParent()->astOperand1(); using Yield = Library::Container::Yield; const Yield yield = astContainerYield(contTok); if (yield == Yield::START_ITERATOR || yield == Yield::END_ITERATOR || yield == Yield::AT_INDEX || yield == Yield::SIZE || yield == Yield::EMPTY || yield == Yield::BUFFER || yield == Yield::BUFFER_NT || ((yield == Yield::ITEM || yield == Yield::ITERATOR) && astContainerAction(contTok) == Library::Container::Action::NO_ACTION)) return Library::UseRetValType::DEFAULT; } return Library::UseRetValType::NONE; } const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok)); if (it != mData->mFunctions.cend()) return it->second.useretval; return Library::UseRetValType::NONE; } const std::string& Library::returnValue(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return emptyString; const std::map<std::string, std::string>::const_iterator it = mData->mReturnValue.find(getFunctionName(ftok)); return it != mData->mReturnValue.cend() ? it->second : emptyString; } const std::string& Library::returnValueType(const Token *ftok) const { if (isNotLibraryFunction(ftok)) { if (Token::simpleMatch(ftok->astParent(), ".") && ftok->astParent()->astOperand1()) { const Token* contTok = ftok->astParent()->astOperand1(); if (contTok->valueType() && contTok->valueType()->container) return contTok->valueType()->container->getReturnType(ftok->str()); } return emptyString; } const std::map<std::string, std::string>::const_iterator it = mData->mReturnValueType.find(getFunctionName(ftok)); return it != mData->mReturnValueType.cend() ? it->second : emptyString; } int Library::returnValueContainer(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return -1; const std::map<std::string, int>::const_iterator it = mData->mReturnValueContainer.find(getFunctionName(ftok)); return it != mData->mReturnValueContainer.cend() ? it->second : -1; } std::vector<MathLib::bigint> Library::unknownReturnValues(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return std::vector<MathLib::bigint>(); const std::map<std::string, std::vector<MathLib::bigint>>::const_iterator it = mData->mUnknownReturnValues.find(getFunctionName(ftok)); return (it == mData->mUnknownReturnValues.cend()) ? std::vector<MathLib::bigint>() : it->second; } const Library::Function *Library::getFunction(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return nullptr; const std::unordered_map<std::string, Function>::const_iterator it1 = mData->mFunctions.find(getFunctionName(ftok)); if (it1 == mData->mFunctions.cend()) return nullptr; return &it1->second; } bool Library::hasminsize(const Token *ftok) const { if (isNotLibraryFunction(ftok)) return false; const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok)); if (it == mData->mFunctions.cend()) return false; return std::any_of(it->second.argumentChecks.cbegin(), it->second.argumentChecks.cend(), [](const std::pair<const int, Library::ArgumentChecks>& a) { return !a.second.minsizes.empty(); }); } Library::ArgumentChecks::Direction Library::getArgDirection(const Token* ftok, int argnr, int indirect) const { const ArgumentChecks* arg = getarg(ftok, argnr); if (arg) { if (indirect < 0 || indirect >= arg->direction.size()) return ArgumentChecks::Direction::DIR_UNKNOWN; // TODO: don't generate bad indirect values return arg->direction[indirect]; } if (formatstr_function(ftok)) { const int fs_argno = formatstr_argno(ftok); if (fs_argno >= 0 && argnr >= fs_argno) { if (formatstr_scan(ftok)) return ArgumentChecks::Direction::DIR_OUT; return ArgumentChecks::Direction::DIR_IN; } } return ArgumentChecks::Direction::DIR_UNKNOWN; } bool Library::ignorefunction(const std::string& functionName) const { const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName); if (it != mData->mFunctions.cend()) return it->second.ignore; return false; } const std::unordered_map<std::string, Library::Function>& Library::functions() const { return mData->mFunctions; } bool Library::isUse(const std::string& functionName) const { const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName); if (it != mData->mFunctions.cend()) return it->second.use; return false; } bool Library::isLeakIgnore(const std::string& functionName) const { const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName); if (it != mData->mFunctions.cend()) return it->second.leakignore; return false; } bool Library::isFunctionConst(const std::string& functionName, bool pure) const { const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(functionName); if (it != mData->mFunctions.cend()) return pure ? it->second.ispure : it->second.isconst; return false; } bool Library::isFunctionConst(const Token *ftok) const { if (ftok->function() && ftok->function()->isConst()) return true; if (isNotLibraryFunction(ftok)) { if (Token::simpleMatch(ftok->astParent(), ".")) { using Yield = Library::Container::Yield; const Yield yield = astContainerYield(ftok->astParent()->astOperand1()); if (yield == Yield::EMPTY || yield == Yield::SIZE || yield == Yield::BUFFER_NT) return true; } return false; } const std::unordered_map<std::string, Function>::const_iterator it = mData->mFunctions.find(getFunctionName(ftok)); return (it != mData->mFunctions.cend() && it->second.isconst); } bool Library::isnoreturn(const Token *ftok) const { if (ftok->function() && ftok->function()->isAttributeNoreturn()) return true; if (ftok->variable() && ftok->variable()->nameToken()->isAttributeNoreturn()) return true; if (isNotLibraryFunction(ftok)) { if (Token::simpleMatch(ftok->astParent(), ".")) { const Token* contTok = ftok->astParent()->astOperand1(); if (astContainerAction(contTok) != Library::Container::Action::NO_ACTION || astContainerYield(contTok) != Library::Container::Yield::NO_YIELD) return false; } return false; } const std::unordered_map<std::string, LibraryData::FalseTrueMaybe>::const_iterator it = mData->mNoReturn.find(getFunctionName(ftok)); if (it == mData->mNoReturn.end()) return false; if (it->second == LibraryData::FalseTrueMaybe::Maybe) return true; return it->second == LibraryData::FalseTrueMaybe::True; } bool Library::isnotnoreturn(const Token *ftok) const { if (ftok->function() && ftok->function()->isAttributeNoreturn()) return false; if (isNotLibraryFunction(ftok)) return hasAnyTypeCheck(getFunctionName(ftok)); const std::unordered_map<std::string, LibraryData::FalseTrueMaybe>::const_iterator it = mData->mNoReturn.find(getFunctionName(ftok)); if (it == mData->mNoReturn.end()) return false; if (it->second == LibraryData::FalseTrueMaybe::Maybe) return false; return it->second == LibraryData::FalseTrueMaybe::False; } bool Library::markupFile(const std::string &path) const { return mData->mMarkupExtensions.find(Path::getFilenameExtensionInLowerCase(path)) != mData->mMarkupExtensions.end(); } bool Library::processMarkupAfterCode(const std::string &path) const { const std::map<std::string, bool>::const_iterator it = mData->mProcessAfterCode.find(Path::getFilenameExtensionInLowerCase(path)); return (it == mData->mProcessAfterCode.cend() || it->second); } bool Library::reportErrors(const std::string &path) const { const std::map<std::string, bool>::const_iterator it = mData->mReportErrors.find(Path::getFilenameExtensionInLowerCase(path)); return (it == mData->mReportErrors.cend() || it->second); } bool Library::isexecutableblock(const std::string &file, const std::string &token) const { const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator it = mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file)); return (it != mData->mExecutableBlocks.cend() && it->second.isBlock(token)); } int Library::blockstartoffset(const std::string &file) const { int offset = -1; const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator map_it = mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file)); if (map_it != mData->mExecutableBlocks.end()) { offset = map_it->second.offset(); } return offset; } const std::string& Library::blockstart(const std::string &file) const { const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator map_it = mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file)); if (map_it != mData->mExecutableBlocks.end()) { return map_it->second.start(); } return emptyString; } const std::string& Library::blockend(const std::string &file) const { const std::unordered_map<std::string, LibraryData::CodeBlock>::const_iterator map_it = mData->mExecutableBlocks.find(Path::getFilenameExtensionInLowerCase(file)); if (map_it != mData->mExecutableBlocks.end()) { return map_it->second.end(); } return emptyString; } bool Library::iskeyword(const std::string &file, const std::string &keyword) const { const std::map<std::string, std::set<std::string>>::const_iterator it = mData->mKeywords.find(Path::getFilenameExtensionInLowerCase(file)); return (it != mData->mKeywords.end() && it->second.count(keyword)); } bool Library::isimporter(const std::string& file, const std::string &importer) const { const std::map<std::string, std::set<std::string>>::const_iterator it = mData->mImporters.find(Path::getFilenameExtensionInLowerCase(file)); return (it != mData->mImporters.end() && it->second.count(importer) > 0); } const Token* Library::getContainerFromYield(const Token* tok, Library::Container::Yield yield) const { if (!tok) return nullptr; if (Token::Match(tok->tokAt(-2), ". %name% (")) { const Token* containerTok = tok->tokAt(-2)->astOperand1(); if (!astIsContainer(containerTok)) return nullptr; if (containerTok->valueType()->container && containerTok->valueType()->container->getYield(tok->strAt(-1)) == yield) return containerTok; if (yield == Library::Container::Yield::EMPTY && Token::simpleMatch(tok->tokAt(-1), "empty ( )")) return containerTok; if (yield == Library::Container::Yield::SIZE && Token::Match(tok->tokAt(-1), "size|length ( )")) return containerTok; } else if (Token::Match(tok->previous(), "%name% (")) { if (const Library::Function* f = this->getFunction(tok->previous())) { if (f->containerYield == yield) { return tok->astOperand2(); } } } return nullptr; } // cppcheck-suppress unusedFunction const Token* Library::getContainerFromAction(const Token* tok, Library::Container::Action action) const { if (!tok) return nullptr; if (Token::Match(tok->tokAt(-2), ". %name% (")) { const Token* containerTok = tok->tokAt(-2)->astOperand1(); if (!astIsContainer(containerTok)) return nullptr; if (containerTok->valueType()->container && containerTok->valueType()->container->getAction(tok->strAt(-1)) == action) return containerTok; if (Token::simpleMatch(tok->tokAt(-1), "empty ( )")) return containerTok; } else if (Token::Match(tok->previous(), "%name% (")) { if (const Library::Function* f = this->getFunction(tok->previous())) { if (f->containerAction == action) { return tok->astOperand2(); } } } return nullptr; } const std::unordered_map<std::string, Library::SmartPointer>& Library::smartPointers() const { return mData->mSmartPointers; } bool Library::isSmartPointer(const Token* tok) const { return detectSmartPointer(tok); } const Library::SmartPointer* Library::detectSmartPointer(const Token* tok, bool withoutStd) const { std::string typestr = withoutStd ? "std::" : ""; while (Token::Match(tok, "%name%|::")) { typestr += tok->str(); tok = tok->next(); } auto it = mData->mSmartPointers.find(typestr); if (it == mData->mSmartPointers.end()) return nullptr; return &it->second; } const Library::Container * getLibraryContainer(const Token * tok) { if (!tok) return nullptr; // TODO: Support dereferencing iterators // TODO: Support dereferencing with -> if (tok->isUnaryOp("*") && astIsPointer(tok->astOperand1())) { for (const ValueFlow::Value& v:tok->astOperand1()->values()) { if (!v.isLocalLifetimeValue()) continue; if (v.lifetimeKind != ValueFlow::Value::LifetimeKind::Address) continue; return getLibraryContainer(v.tokvalue); } } if (!tok->valueType()) return nullptr; return tok->valueType()->container; } Library::TypeCheck Library::getTypeCheck(std::string check, std::string typeName) const { auto it = mData->mTypeChecks.find(std::pair<std::string, std::string>(std::move(check), std::move(typeName))); return it == mData->mTypeChecks.end() ? TypeCheck::def : it->second; } bool Library::hasAnyTypeCheck(const std::string& typeName) const { return std::any_of(mData->mTypeChecks.begin(), mData->mTypeChecks.end(), [&](const std::pair<std::pair<std::string, std::string>, Library::TypeCheck>& tc) { return tc.first.second == typeName; }); } const Library::AllocFunc* Library::getAllocFuncInfo(const char name[]) const { return getAllocDealloc(mData->mAlloc, name); } const Library::AllocFunc* Library::getDeallocFuncInfo(const char name[]) const { return getAllocDealloc(mData->mDealloc, name); } // cppcheck-suppress unusedFunction int Library::allocId(const char name[]) const { const AllocFunc* af = getAllocDealloc(mData->mAlloc, name); return af ? af->groupId : 0; } int Library::deallocId(const char name[]) const { const AllocFunc* af = getAllocDealloc(mData->mDealloc, name); return af ? af->groupId : 0; } const std::set<std::string> &Library::markupExtensions() const { return mData->mMarkupExtensions; } bool Library::isexporter(const std::string &prefix) const { return mData->mExporters.find(prefix) != mData->mExporters.end(); } bool Library::isexportedprefix(const std::string &prefix, const std::string &token) const { const std::map<std::string, LibraryData::ExportedFunctions>::const_iterator it = mData->mExporters.find(prefix); return (it != mData->mExporters.end() && it->second.isPrefix(token)); } bool Library::isexportedsuffix(const std::string &prefix, const std::string &token) const { const std::map<std::string, LibraryData::ExportedFunctions>::const_iterator it = mData->mExporters.find(prefix); return (it != mData->mExporters.end() && it->second.isSuffix(token)); } bool Library::isreflection(const std::string &token) const { return mData->mReflection.find(token) != mData->mReflection.end(); } int Library::reflectionArgument(const std::string &token) const { const std::map<std::string, int>::const_iterator it = mData->mReflection.find(token); if (it != mData->mReflection.end()) return it->second; return -1; } bool Library::isentrypoint(const std::string &func) const { return func == "main" || mData->mEntrypoints.find(func) != mData->mEntrypoints.end(); } const std::set<std::string>& Library::defines() const { return mData->mDefines; } const Library::PodType *Library::podtype(const std::string &name) const { const std::unordered_map<std::string, struct PodType>::const_iterator it = mData->mPodTypes.find(name); return (it != mData->mPodTypes.end()) ? &(it->second) : nullptr; } const Library::PlatformType *Library::platform_type(const std::string &name, const std::string & platform) const { const std::map<std::string, LibraryData::Platform>::const_iterator it = mData->mPlatforms.find(platform); if (it != mData->mPlatforms.end()) { const PlatformType * const type = it->second.platform_type(name); if (type) return type; } const std::map<std::string, PlatformType>::const_iterator it2 = mData->mPlatformTypes.find(name); return (it2 != mData->mPlatformTypes.end()) ? &(it2->second) : nullptr; }
86,794
C++
.cpp
1,815
36.865014
170
0.585385
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,144
checkio.cpp
danmar_cppcheck/lib/checkio.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkio.h" #include "astutils.h" #include "errortypes.h" #include "library.h" #include "mathlib.h" #include "platform.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "utils.h" #include "vfvalue.h" #include <algorithm> #include <cctype> #include <cstdlib> #include <functional> #include <list> #include <map> #include <set> #include <sstream> #include <unordered_set> #include <utility> #include <vector> //--------------------------------------------------------------------------- // Register CheckIO.. namespace { CheckIO instance; } // CVE ID used: static const CWE CWE119(119U); // Improper Restriction of Operations within the Bounds of a Memory Buffer static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE664(664U); // Improper Control of a Resource Through its Lifetime static const CWE CWE685(685U); // Function Call With Incorrect Number of Arguments static const CWE CWE686(686U); // Function Call With Incorrect Argument Type static const CWE CWE687(687U); // Function Call With Incorrectly Specified Argument Value static const CWE CWE704(704U); // Incorrect Type Conversion or Cast static const CWE CWE910(910U); // Use of Expired File Descriptor //--------------------------------------------------------------------------- // std::cout << std::cout; //--------------------------------------------------------------------------- void CheckIO::checkCoutCerrMisusage() { if (mTokenizer->isC()) return; logChecker("CheckIO::checkCoutCerrMisusage"); // c const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "std :: cout|cerr !!.") && tok->next()->astParent() && tok->next()->astParent()->astOperand1() == tok->next()) { const Token* tok2 = tok->next(); while (tok2->astParent() && tok2->astParent()->str() == "<<") { tok2 = tok2->astParent(); if (tok2->astOperand2() && Token::Match(tok2->astOperand2()->previous(), "std :: cout|cerr")) coutCerrMisusageError(tok, tok2->astOperand2()->strAt(1)); } } } } } void CheckIO::coutCerrMisusageError(const Token* tok, const std::string& streamName) { reportError(tok, Severity::error, "coutCerrMisusage", "Invalid usage of output stream: '<< std::" + streamName + "'.", CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // fflush(stdin) <- fflush only applies to output streams in ANSI C // fread(); fwrite(); <- consecutive read/write statements require repositioning in between // fopen("","r"); fwrite(); <- write to read-only file (or vice versa) // fclose(); fread(); <- Use closed file //--------------------------------------------------------------------------- enum class OpenMode : std::uint8_t { CLOSED, READ_MODE, WRITE_MODE, RW_MODE, UNKNOWN_OM }; static OpenMode getMode(const std::string& str) { if (str.find('+', 1) != std::string::npos) return OpenMode::RW_MODE; if (str.find('w') != std::string::npos || str.find('a') != std::string::npos) return OpenMode::WRITE_MODE; if (str.find('r') != std::string::npos) return OpenMode::READ_MODE; return OpenMode::UNKNOWN_OM; } namespace { struct Filepointer { OpenMode mode; nonneg int mode_indent{}; enum class Operation : std::uint8_t {NONE, UNIMPORTANT, READ, WRITE, POSITIONING, OPEN, CLOSE, UNKNOWN_OP} lastOperation = Operation::NONE; nonneg int op_indent{}; enum class AppendMode : std::uint8_t { UNKNOWN_AM, APPEND, APPEND_EX }; AppendMode append_mode = AppendMode::UNKNOWN_AM; std::string filename; explicit Filepointer(OpenMode mode_ = OpenMode::UNKNOWN_OM) : mode(mode_) {} }; const std::unordered_set<std::string> whitelist = { "clearerr", "feof", "ferror", "fgetpos", "ftell", "setbuf", "setvbuf", "ungetc", "ungetwc" }; } void CheckIO::checkFileUsage() { const bool windows = mSettings->platform.isWindows(); const bool printPortability = mSettings->severity.isEnabled(Severity::portability); const bool printWarnings = mSettings->severity.isEnabled(Severity::warning); std::map<int, Filepointer> filepointers; logChecker("CheckIO::checkFileUsage"); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Variable* var : symbolDatabase->variableList()) { if (!var || !var->declarationId() || var->isArray() || !Token::simpleMatch(var->typeStartToken(), "FILE *")) continue; if (var->isLocal()) { if (var->nameToken()->strAt(1) == "(") // initialize by calling "ctor" filepointers.insert(std::make_pair(var->declarationId(), Filepointer(OpenMode::UNKNOWN_OM))); else filepointers.insert(std::make_pair(var->declarationId(), Filepointer(OpenMode::CLOSED))); } else { filepointers.insert(std::make_pair(var->declarationId(), Filepointer(OpenMode::UNKNOWN_OM))); // TODO: If all fopen calls we find open the file in the same type, we can set Filepointer::mode } } for (const Scope * scope : symbolDatabase->functionScopes) { int indent = 0; for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "%name% (") && isUnevaluated(tok)) { tok = tok->linkAt(1); continue; } if (tok->str() == "{") indent++; else if (tok->str() == "}") { indent--; for (std::pair<const int, Filepointer>& filepointer : filepointers) { if (indent < filepointer.second.mode_indent) { filepointer.second.mode_indent = 0; filepointer.second.mode = OpenMode::UNKNOWN_OM; } if (indent < filepointer.second.op_indent) { filepointer.second.op_indent = 0; filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP; } } } else if (tok->str() == "return" || tok->str() == "continue" || tok->str() == "break" || mSettings->library.isnoreturn(tok)) { // Reset upon return, continue or break for (std::pair<const int, Filepointer>& filepointer : filepointers) { filepointer.second.mode_indent = 0; filepointer.second.mode = OpenMode::UNKNOWN_OM; filepointer.second.op_indent = 0; filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP; } } else if (Token::Match(tok, "%var% =") && (tok->strAt(2) != "fopen" && tok->strAt(2) != "freopen" && tok->strAt(2) != "tmpfile" && (windows ? (tok->str() != "_wfopen" && tok->str() != "_wfreopen") : true))) { const std::map<int, Filepointer>::iterator i = filepointers.find(tok->varId()); if (i != filepointers.end()) { i->second.mode = OpenMode::UNKNOWN_OM; i->second.lastOperation = Filepointer::Operation::UNKNOWN_OP; } } else if (Token::Match(tok, "%name% (") && tok->previous() && (!tok->previous()->isName() || Token::Match(tok->previous(), "return|throw"))) { std::string mode; const Token* fileTok = nullptr; const Token* fileNameTok = nullptr; Filepointer::Operation operation = Filepointer::Operation::NONE; if ((tok->str() == "fopen" || tok->str() == "freopen" || tok->str() == "tmpfile" || (windows && (tok->str() == "_wfopen" || tok->str() == "_wfreopen"))) && tok->strAt(-1) == "=") { if (tok->str() != "tmpfile") { const Token* modeTok = tok->tokAt(2)->nextArgument(); if (modeTok && modeTok->tokType() == Token::eString) mode = modeTok->strValue(); } else mode = "wb+"; fileTok = tok->tokAt(-2); operation = Filepointer::Operation::OPEN; if (Token::Match(tok, "fopen ( %str% ,")) fileNameTok = tok->tokAt(2); } else if (windows && Token::Match(tok, "fopen_s|freopen_s|_wfopen_s|_wfreopen_s ( & %name%")) { const Token* modeTok = tok->tokAt(2)->nextArgument()->nextArgument(); if (modeTok && modeTok->tokType() == Token::eString) mode = modeTok->strValue(); fileTok = tok->tokAt(3); operation = Filepointer::Operation::OPEN; } else if ((tok->str() == "rewind" || tok->str() == "fseek" || tok->str() == "fsetpos" || tok->str() == "fflush") || (windows && tok->str() == "_fseeki64")) { fileTok = tok->tokAt(2); if (printPortability && fileTok && tok->str() == "fflush") { if (fileTok->str() == "stdin") fflushOnInputStreamError(tok, fileTok->str()); else { const Filepointer& f = filepointers[fileTok->varId()]; if (f.mode == OpenMode::READ_MODE) fflushOnInputStreamError(tok, fileTok->str()); } } operation = Filepointer::Operation::POSITIONING; } else if (tok->str() == "fgetc" || tok->str() == "fgetwc" || tok->str() == "fgets" || tok->str() == "fgetws" || tok->str() == "fread" || tok->str() == "fscanf" || tok->str() == "fwscanf" || tok->str() == "getc" || (windows && (tok->str() == "fscanf_s" || tok->str() == "fwscanf_s"))) { if (tok->str().find("scanf") != std::string::npos) fileTok = tok->tokAt(2); else fileTok = tok->linkAt(1)->previous(); operation = Filepointer::Operation::READ; } else if (tok->str() == "fputc" || tok->str() == "fputwc" || tok->str() == "fputs" || tok->str() == "fputws" || tok->str() == "fwrite" || tok->str() == "fprintf" || tok->str() == "fwprintf" || tok->str() == "putcc" || (windows && (tok->str() == "fprintf_s" || tok->str() == "fwprintf_s"))) { if (tok->str().find("printf") != std::string::npos) fileTok = tok->tokAt(2); else fileTok = tok->linkAt(1)->previous(); operation = Filepointer::Operation::WRITE; } else if (tok->str() == "fclose") { fileTok = tok->tokAt(2); operation = Filepointer::Operation::CLOSE; } else if (whitelist.find(tok->str()) != whitelist.end()) { fileTok = tok->tokAt(2); if ((tok->str() == "ungetc" || tok->str() == "ungetwc") && fileTok) fileTok = fileTok->nextArgument(); operation = Filepointer::Operation::UNIMPORTANT; } else if (!Token::Match(tok, "if|for|while|catch|switch") && !mSettings->library.isFunctionConst(tok->str(), true)) { const Token* const end2 = tok->linkAt(1); if (scope->functionOf && scope->functionOf->isClassOrStruct() && !scope->function->isStatic() && ((tok->strAt(-1) != "::" && tok->strAt(-1) != ".") || tok->strAt(-2) == "this")) { if (!tok->function() || (tok->function()->nestedIn && tok->function()->nestedIn->isClassOrStruct())) { for (std::pair<const int, Filepointer>& filepointer : filepointers) { const Variable* var = symbolDatabase->getVariableFromVarId(filepointer.first); if (!var || !(var->isLocal() || var->isGlobal() || var->isStatic())) { filepointer.second.mode = OpenMode::UNKNOWN_OM; filepointer.second.mode_indent = 0; filepointer.second.op_indent = indent; filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP; } } continue; } } for (const Token* tok2 = tok->tokAt(2); tok2 != end2; tok2 = tok2->next()) { if (tok2->varId() && filepointers.find(tok2->varId()) != filepointers.end()) { fileTok = tok2; operation = Filepointer::Operation::UNKNOWN_OP; // Assume that repositioning was last operation and that the file is opened now break; } } } while (Token::Match(fileTok, "%name% .")) fileTok = fileTok->tokAt(2); if (!fileTok || !fileTok->varId() || fileTok->strAt(1) == "[") continue; if (filepointers.find(fileTok->varId()) == filepointers.end()) { // function call indicates: Its a File filepointers.insert(std::make_pair(fileTok->varId(), Filepointer(OpenMode::UNKNOWN_OM))); } Filepointer& f = filepointers[fileTok->varId()]; switch (operation) { case Filepointer::Operation::OPEN: if (fileNameTok) { for (std::map<int, Filepointer>::const_iterator it = filepointers.cbegin(); it != filepointers.cend(); ++it) { const Filepointer &fptr = it->second; if (fptr.filename == fileNameTok->str() && (fptr.mode == OpenMode::RW_MODE || fptr.mode == OpenMode::WRITE_MODE)) incompatibleFileOpenError(tok, fileNameTok->str()); } f.filename = fileNameTok->str(); } f.mode = getMode(mode); if (mode.find('a') != std::string::npos) { if (f.mode == OpenMode::RW_MODE) f.append_mode = Filepointer::AppendMode::APPEND_EX; else f.append_mode = Filepointer::AppendMode::APPEND; } else f.append_mode = Filepointer::AppendMode::UNKNOWN_AM; f.mode_indent = indent; break; case Filepointer::Operation::POSITIONING: if (f.mode == OpenMode::CLOSED) useClosedFileError(tok); else if (f.append_mode == Filepointer::AppendMode::APPEND && tok->str() != "fflush" && printWarnings) seekOnAppendedFileError(tok); break; case Filepointer::Operation::READ: if (f.mode == OpenMode::CLOSED) useClosedFileError(tok); else if (f.mode == OpenMode::WRITE_MODE) readWriteOnlyFileError(tok); else if (f.lastOperation == Filepointer::Operation::WRITE) ioWithoutPositioningError(tok); break; case Filepointer::Operation::WRITE: if (f.mode == OpenMode::CLOSED) useClosedFileError(tok); else if (f.mode == OpenMode::READ_MODE) writeReadOnlyFileError(tok); else if (f.lastOperation == Filepointer::Operation::READ) ioWithoutPositioningError(tok); break; case Filepointer::Operation::CLOSE: if (f.mode == OpenMode::CLOSED) useClosedFileError(tok); else f.mode = OpenMode::CLOSED; f.mode_indent = indent; break; case Filepointer::Operation::UNIMPORTANT: if (f.mode == OpenMode::CLOSED) useClosedFileError(tok); break; case Filepointer::Operation::UNKNOWN_OP: f.mode = OpenMode::UNKNOWN_OM; f.mode_indent = 0; break; default: break; } if (operation != Filepointer::Operation::NONE && operation != Filepointer::Operation::UNIMPORTANT) { f.op_indent = indent; f.lastOperation = operation; } } } for (std::pair<const int, Filepointer>& filepointer : filepointers) { filepointer.second.op_indent = 0; filepointer.second.mode = OpenMode::UNKNOWN_OM; filepointer.second.lastOperation = Filepointer::Operation::UNKNOWN_OP; } } } void CheckIO::fflushOnInputStreamError(const Token *tok, const std::string &varname) { reportError(tok, Severity::portability, "fflushOnInputStream", "fflush() called on input stream '" + varname + "' may result in undefined behaviour on non-linux systems.", CWE398, Certainty::normal); } void CheckIO::ioWithoutPositioningError(const Token *tok) { reportError(tok, Severity::error, "IOWithoutPositioning", "Read and write operations without a call to a positioning function (fseek, fsetpos or rewind) or fflush in between result in undefined behaviour.", CWE664, Certainty::normal); } void CheckIO::readWriteOnlyFileError(const Token *tok) { reportError(tok, Severity::error, "readWriteOnlyFile", "Read operation on a file that was opened only for writing.", CWE664, Certainty::normal); } void CheckIO::writeReadOnlyFileError(const Token *tok) { reportError(tok, Severity::error, "writeReadOnlyFile", "Write operation on a file that was opened only for reading.", CWE664, Certainty::normal); } void CheckIO::useClosedFileError(const Token *tok) { reportError(tok, Severity::error, "useClosedFile", "Used file that is not opened.", CWE910, Certainty::normal); } void CheckIO::seekOnAppendedFileError(const Token *tok) { reportError(tok, Severity::warning, "seekOnAppendedFile", "Repositioning operation performed on a file opened in append mode has no effect.", CWE398, Certainty::normal); } void CheckIO::incompatibleFileOpenError(const Token *tok, const std::string &filename) { reportError(tok, Severity::warning, "incompatibleFileOpen", "The file '" + filename + "' is opened for read and write access at the same time on different streams", CWE664, Certainty::normal); } //--------------------------------------------------------------------------- // scanf without field width limits can crash with huge input data //--------------------------------------------------------------------------- void CheckIO::invalidScanf() { if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("invalidscanf")) return; logChecker("CheckIO::invalidScanf"); const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { const Token *formatToken = nullptr; if (Token::Match(tok, "scanf|vscanf ( %str% ,")) formatToken = tok->tokAt(2); else if (Token::Match(tok, "sscanf|vsscanf|fscanf|vfscanf (")) { const Token* nextArg = tok->tokAt(2)->nextArgument(); if (nextArg && nextArg->tokType() == Token::eString) formatToken = nextArg; else continue; } else continue; bool format = false; // scan the string backwards, so we do not need to keep states const std::string &formatstr(formatToken->str()); for (std::size_t i = 1; i < formatstr.length(); i++) { if (formatstr[i] == '%') format = !format; else if (!format) continue; else if (std::isdigit(formatstr[i]) || formatstr[i] == '*') { format = false; } else if (std::isalpha((unsigned char)formatstr[i]) || formatstr[i] == '[') { if (formatstr[i] == 's' || formatstr[i] == '[' || formatstr[i] == 'S' || (formatstr[i] == 'l' && formatstr[i+1] == 's')) // #3490 - field width limits are only necessary for string input invalidScanfError(tok); format = false; } } } } } void CheckIO::invalidScanfError(const Token *tok) { const std::string fname = (tok ? tok->str() : std::string("scanf")); reportError(tok, Severity::warning, "invalidscanf", fname + "() without field width limits can crash with huge input data.\n" + fname + "() without field width limits can crash with huge input data. Add a field width " "specifier to fix this problem.\n" "\n" "Sample program that can crash:\n" "\n" "#include <stdio.h>\n" "int main()\n" "{\n" " char c[5];\n" " scanf(\"%s\", c);\n" " return 0;\n" "}\n" "\n" "Typing in 5 or more characters may make the program crash. The correct usage " "here is 'scanf(\"%4s\", c);', as the maximum field width does not include the " "terminating null byte.\n" "Source: http://linux.die.net/man/3/scanf\n" "Source: http://www.opensource.apple.com/source/xnu/xnu-1456.1.26/libkern/stdio/scanf.c", CWE119, Certainty::normal); } //--------------------------------------------------------------------------- // printf("%u", "xyz"); // Wrong argument type // printf("%u%s", 1); // Too few arguments // printf("", 1); // Too much arguments //--------------------------------------------------------------------------- static bool findFormat(nonneg int arg, const Token *firstArg, const Token *&formatStringTok, const Token *&formatArgTok) { const Token* argTok = firstArg; for (int i = 0; i < arg && argTok; ++i) argTok = argTok->nextArgument(); if (Token::Match(argTok, "%str% [,)]")) { formatArgTok = argTok->nextArgument(); formatStringTok = argTok; return true; } if (Token::Match(argTok, "%var% [,)]") && argTok->variable() && Token::Match(argTok->variable()->typeStartToken(), "char|wchar_t") && (argTok->variable()->isPointer() || (argTok->variable()->dimensions().size() == 1 && argTok->variable()->dimensionKnown(0) && argTok->variable()->dimension(0) != 0))) { formatArgTok = argTok->nextArgument(); if (!argTok->values().empty()) { const std::list<ValueFlow::Value>::const_iterator value = std::find_if( argTok->values().cbegin(), argTok->values().cend(), std::mem_fn(&ValueFlow::Value::isTokValue)); if (value != argTok->values().cend() && value->isTokValue() && value->tokvalue && value->tokvalue->tokType() == Token::eString) { formatStringTok = value->tokvalue; } } return true; } return false; } // Utility function returning whether iToTest equals iTypename or iOptionalPrefix+iTypename static inline bool typesMatch(const std::string& iToTest, const std::string& iTypename, const std::string& iOptionalPrefix = "std::") { return (iToTest == iTypename) || (iToTest == iOptionalPrefix + iTypename); } void CheckIO::checkWrongPrintfScanfArguments() { const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); const bool isWindows = mSettings->platform.isWindows(); logChecker("CheckIO::checkWrongPrintfScanfArguments"); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isName()) continue; const Token* argListTok = nullptr; // Points to first va_list argument const Token* formatStringTok = nullptr; // Points to format string token bool scan = false; bool scanf_s = false; int formatStringArgNo = -1; if (tok->strAt(1) == "(" && mSettings->library.formatstr_function(tok)) { formatStringArgNo = mSettings->library.formatstr_argno(tok); scan = mSettings->library.formatstr_scan(tok); scanf_s = mSettings->library.formatstr_secure(tok); } if (formatStringArgNo >= 0) { // formatstring found in library. Find format string and first argument belonging to format string. if (!findFormat(formatStringArgNo, tok->tokAt(2), formatStringTok, argListTok)) continue; } else if (Token::simpleMatch(tok, "swprintf (")) { if (Token::Match(tok->tokAt(2)->nextArgument(), "%str%")) { // Find third parameter and format string if (!findFormat(1, tok->tokAt(2), formatStringTok, argListTok)) continue; } else { // Find fourth parameter and format string if (!findFormat(2, tok->tokAt(2), formatStringTok, argListTok)) continue; } } else if (isWindows && Token::Match(tok, "sprintf_s|swprintf_s (")) { // template <size_t size> int sprintf_s(char (&buffer)[size], const char *format, ...); if (findFormat(1, tok->tokAt(2), formatStringTok, argListTok)) { if (!formatStringTok) continue; } // int sprintf_s(char *buffer, size_t sizeOfBuffer, const char *format, ...); else if (findFormat(2, tok->tokAt(2), formatStringTok, argListTok)) { if (!formatStringTok) continue; } } else if (isWindows && Token::Match(tok, "_snprintf_s|_snwprintf_s (")) { // template <size_t size> int _snprintf_s(char (&buffer)[size], size_t count, const char *format, ...); if (findFormat(2, tok->tokAt(2), formatStringTok, argListTok)) { if (!formatStringTok) continue; } // int _snprintf_s(char *buffer, size_t sizeOfBuffer, size_t count, const char *format, ...); else if (findFormat(3, tok->tokAt(2), formatStringTok, argListTok)) { if (!formatStringTok) continue; } } else { continue; } if (!formatStringTok) continue; checkFormatString(tok, formatStringTok, argListTok, scan, scanf_s); } } } void CheckIO::checkFormatString(const Token * const tok, const Token * const formatStringTok, const Token * argListTok, const bool scan, const bool scanf_s) { const bool isWindows = mSettings->platform.isWindows(); const bool printWarning = mSettings->severity.isEnabled(Severity::warning); const std::string &formatString = formatStringTok->str(); // Count format string parameters.. int numFormat = 0; int numSecure = 0; bool percent = false; const Token* argListTok2 = argListTok; std::set<int> parameterPositionsUsed; for (std::string::const_iterator i = formatString.cbegin(); i != formatString.cend(); ++i) { if (*i == '%') { percent = !percent; } else if (percent && *i == '[') { while (i != formatString.cend()) { if (*i == ']') { numFormat++; if (argListTok) argListTok = argListTok->nextArgument(); percent = false; break; } ++i; } if (scanf_s) { numSecure++; if (argListTok) { argListTok = argListTok->nextArgument(); } } if (i == formatString.cend()) break; } else if (percent) { percent = false; bool _continue = false; bool skip = false; std::string width; int parameterPosition = 0; bool hasParameterPosition = false; while (i != formatString.cend() && *i != '[' && !std::isalpha((unsigned char)*i)) { if (*i == '*') { skip = true; if (scan) _continue = true; else { numFormat++; if (argListTok) argListTok = argListTok->nextArgument(); } } else if (std::isdigit(*i)) { width += *i; } else if (*i == '$') { parameterPosition = strToInt<int>(width); hasParameterPosition = true; width.clear(); } ++i; } auto bracketBeg = formatString.cend(); if (i != formatString.cend() && *i == '[') { bracketBeg = i; while (i != formatString.cend()) { if (*i == ']') break; ++i; } if (scanf_s && !skip) { numSecure++; if (argListTok) { argListTok = argListTok->nextArgument(); } } } if (i == formatString.cend()) break; if (_continue) continue; if (scan || *i != 'm') { // %m is a non-standard extension that requires no parameter on print functions. ++numFormat; // Handle parameter positions (POSIX extension) - Ticket #4900 if (hasParameterPosition) { if (parameterPositionsUsed.find(parameterPosition) == parameterPositionsUsed.end()) parameterPositionsUsed.insert(parameterPosition); else // Parameter already referenced, hence don't consider it a new format --numFormat; } // Perform type checks ArgumentInfo argInfo(argListTok, *mSettings, mTokenizer->isCPP()); if ((argInfo.typeToken && !argInfo.isLibraryType(*mSettings)) || *i == ']') { if (scan) { std::string specifier; bool done = false; while (!done) { switch (*i) { case 's': case ']': // charset specifier += (*i == 's' || bracketBeg == formatString.end()) ? std::string{ 's' } : std::string{ bracketBeg, i + 1 }; if (argInfo.variableInfo && argInfo.isKnownType() && argInfo.variableInfo->isArray() && (argInfo.variableInfo->dimensions().size() == 1) && argInfo.variableInfo->dimensions()[0].known) { if (!width.empty()) { const int numWidth = strToInt<int>(width); if (numWidth != (argInfo.variableInfo->dimension(0) - 1)) invalidScanfFormatWidthError(tok, numFormat, numWidth, argInfo.variableInfo, specifier); } } if (argListTok && argListTok->tokType() != Token::eString && argInfo.typeToken && argInfo.isKnownType() && argInfo.isArrayOrPointer() && (!Token::Match(argInfo.typeToken, "char|wchar_t") || argInfo.typeToken->strAt(-1) == "const")) { if (!(argInfo.isArrayOrPointer() && argInfo.element && !argInfo.typeToken->isStandardType())) invalidScanfArgTypeError_s(tok, numFormat, specifier, &argInfo); } if (scanf_s && argInfo.typeToken) { numSecure++; if (argListTok) { argListTok = argListTok->nextArgument(); } } done = true; break; case 'c': if (argInfo.variableInfo && argInfo.isKnownType() && argInfo.variableInfo->isArray() && (argInfo.variableInfo->dimensions().size() == 1) && argInfo.variableInfo->dimensions()[0].known) { if (!width.empty()) { const int numWidth = strToInt<int>(width); if (numWidth > argInfo.variableInfo->dimension(0)) invalidScanfFormatWidthError(tok, numFormat, numWidth, argInfo.variableInfo, std::string(1, *i)); } } if (scanf_s) { numSecure++; if (argListTok) { argListTok = argListTok->nextArgument(); } } done = true; break; case 'x': case 'X': case 'u': case 'o': specifier += *i; if (argInfo.typeToken->tokType() == Token::eString) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); else if (argInfo.isKnownType()) { if (!Token::Match(argInfo.typeToken, "char|short|int|long")) { if (argInfo.typeToken->isStandardType() || !argInfo.element) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); } else if (!argInfo.typeToken->isUnsigned() || !argInfo.isArrayOrPointer() || argInfo.typeToken->strAt(-1) == "const") { invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); } else { switch (specifier[0]) { case 'h': if (specifier[1] == 'h') { if (argInfo.typeToken->str() != "char") invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); } else if (argInfo.typeToken->str() != "short") invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; case 'l': if (specifier[1] == 'l') { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || typesMatch(argInfo.typeToken->originalName(), "uintmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); } else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || typesMatch(argInfo.typeToken->originalName(), "uintmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; case 'I': if (specifier.find("I64") != std::string::npos) { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); } else if (specifier.find("I32") != std::string::npos) { if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); } else if (!typesMatch(argInfo.typeToken->originalName(), "size_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; case 'j': if (!typesMatch(argInfo.typeToken->originalName(), "uintmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; case 'z': if (!typesMatch(argInfo.typeToken->originalName(), "size_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; case 't': if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; case 'L': if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || typesMatch(argInfo.typeToken->originalName(), "uintmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; default: if (argInfo.typeToken->str() != "int") invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || typesMatch(argInfo.typeToken->originalName(), "uintmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, true); break; } } } done = true; break; case 'n': case 'd': case 'i': specifier += *i; if (argInfo.typeToken->tokType() == Token::eString) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); else if (argInfo.isKnownType()) { if (!Token::Match(argInfo.typeToken, "char|short|int|long")) { if (argInfo.typeToken->isStandardType() || !argInfo.element) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); } else if (argInfo.typeToken->isUnsigned() || !argInfo.isArrayOrPointer() || argInfo.typeToken->strAt(-1) == "const") { invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); } else { switch (specifier[0]) { case 'h': if (specifier[1] == 'h') { if (argInfo.typeToken->str() != "char") invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); } else if (argInfo.typeToken->str() != "short") invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; case 'l': if (specifier[1] == 'l') { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || typesMatch(argInfo.typeToken->originalName(), "intmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); } else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || typesMatch(argInfo.typeToken->originalName(), "intmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; case 'I': if (specifier.find("I64") != std::string::npos) { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); } else if (specifier.find("I32") != std::string::npos) { if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); } else if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; case 'j': if (!typesMatch(argInfo.typeToken->originalName(), "intmax_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; case 'z': if (!(typesMatch(argInfo.typeToken->originalName(), "ssize_t") || (isWindows && typesMatch(argInfo.typeToken->originalName(), "SSIZE_T")))) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; case 't': if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t")) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; case 'L': if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; default: if (argInfo.typeToken->str() != "int") invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || argInfo.typeToken->originalName() == "intmax_t") invalidScanfArgTypeError_int(tok, numFormat, specifier, &argInfo, false); break; } } } done = true; break; case 'e': case 'E': case 'f': case 'g': case 'G': case 'a': specifier += *i; if (argInfo.typeToken->tokType() == Token::eString) invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo); else if (argInfo.isKnownType()) { if (!Token::Match(argInfo.typeToken, "float|double")) { if (argInfo.typeToken->isStandardType()) invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo); } else if (!argInfo.isArrayOrPointer() || argInfo.typeToken->strAt(-1) == "const") { invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo); } else { switch (specifier[0]) { case 'l': if (argInfo.typeToken->str() != "double" || argInfo.typeToken->isLong()) invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo); break; case 'L': if (argInfo.typeToken->str() != "double" || !argInfo.typeToken->isLong()) invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo); break; default: if (argInfo.typeToken->str() != "float") invalidScanfArgTypeError_float(tok, numFormat, specifier, &argInfo); break; } } } done = true; break; case 'I': if ((i+1 != formatString.cend() && *(i+1) == '6' && i+2 != formatString.cend() && *(i+2) == '4') || (i+1 != formatString.cend() && *(i+1) == '3' && i+2 != formatString.cend() && *(i+2) == '2')) { specifier += *i++; specifier += *i++; if ((i+1) != formatString.cend() && !isalpha(*(i+1))) { specifier += *i; invalidLengthModifierError(tok, numFormat, specifier); done = true; } else { specifier += *i++; } } else { if ((i+1) != formatString.cend() && !isalpha(*(i+1))) { specifier += *i; invalidLengthModifierError(tok, numFormat, specifier); done = true; } else { specifier += *i++; } } break; case 'h': case 'l': if (i+1 != formatString.cend() && *(i+1) == *i) specifier += *i++; FALLTHROUGH; case 'j': case 'q': case 't': case 'z': case 'L': // Expect an alphabetical character after these specifiers if ((i + 1) != formatString.end() && !isalpha(*(i+1))) { specifier += *i; invalidLengthModifierError(tok, numFormat, specifier); done = true; } else { specifier += *i++; } break; default: done = true; break; } } } else if (printWarning) { std::string specifier; bool done = false; while (!done) { if (i == formatString.end()) { break; } switch (*i) { case 's': if (argListTok->tokType() != Token::eString && argInfo.isKnownType() && !argInfo.isArrayOrPointer()) { if (!Token::Match(argInfo.typeToken, "char|wchar_t")) { if (!argInfo.element) invalidPrintfArgTypeError_s(tok, numFormat, &argInfo); } } done = true; break; case 'n': if ((argInfo.isKnownType() && (!argInfo.isArrayOrPointer() || argInfo.typeToken->strAt(-1) == "const")) || argListTok->tokType() == Token::eString) invalidPrintfArgTypeError_n(tok, numFormat, &argInfo); done = true; break; case 'c': case 'x': case 'X': case 'o': specifier += *i; if (argInfo.typeToken->tokType() == Token::eString) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); else if (argInfo.isArrayOrPointer() && !argInfo.element) { // use %p on pointers and arrays invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (argInfo.isKnownType()) { if (!Token::Match(argInfo.typeToken, "bool|short|long|int|char|wchar_t")) { if (!(!argInfo.isArrayOrPointer() && argInfo.element)) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else { switch (specifier[0]) { case 'h': if (specifier[1] == 'h') { if (!(argInfo.typeToken->str() == "char" && argInfo.typeToken->isUnsigned())) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (!(argInfo.typeToken->str() == "short" && argInfo.typeToken->isUnsigned())) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'l': if (specifier[1] == 'l') { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || argInfo.typeToken->originalName() == "uintmax_t") invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || argInfo.typeToken->originalName() == "uintmax_t") invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'j': if (argInfo.typeToken->originalName() != "uintmax_t") invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'z': if (!typesMatch(argInfo.typeToken->originalName(), "size_t")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 't': if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'I': if (specifier.find("I64") != std::string::npos) { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (specifier.find("I32") != std::string::npos) { if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (!(typesMatch(argInfo.typeToken->originalName(), "size_t") || argInfo.typeToken->originalName() == "WPARAM" || argInfo.typeToken->originalName() == "UINT_PTR" || argInfo.typeToken->originalName() == "LONG_PTR" || argInfo.typeToken->originalName() == "LPARAM" || argInfo.typeToken->originalName() == "LRESULT")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; default: if (!Token::Match(argInfo.typeToken, "bool|char|short|wchar_t|int")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; } } } done = true; break; case 'd': case 'i': specifier += *i; if (argInfo.typeToken->tokType() == Token::eString) { invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else if (argInfo.isArrayOrPointer() && !argInfo.element) { // use %p on pointers and arrays invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else if (argInfo.isKnownType()) { if (argInfo.typeToken->isUnsigned() && !Token::Match(argInfo.typeToken, "char|short")) { if (!(!argInfo.isArrayOrPointer() && argInfo.element)) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else if (!Token::Match(argInfo.typeToken, "bool|char|short|int|long")) { if (!(!argInfo.isArrayOrPointer() && argInfo.element)) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else { switch (specifier[0]) { case 'h': if (specifier[1] == 'h') { if (!(argInfo.typeToken->str() == "char" && !argInfo.typeToken->isUnsigned())) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else if (!(argInfo.typeToken->str() == "short" && !argInfo.typeToken->isUnsigned())) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; case 'l': if (specifier[1] == 'l') { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || argInfo.typeToken->originalName() == "intmax_t") invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong()) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || argInfo.typeToken->originalName() == "intmax_t") invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; case 'j': if (argInfo.typeToken->originalName() != "intmax_t") invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; case 't': if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t")) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; case 'I': if (specifier.find("I64") != std::string::npos) { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else if (specifier.find("I32") != std::string::npos) { if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong()) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); } else if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t")) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; case 'z': if (!(typesMatch(argInfo.typeToken->originalName(), "ssize_t") || (isWindows && typesMatch(argInfo.typeToken->originalName(), "SSIZE_T")))) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; case 'L': if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; default: if (!Token::Match(argInfo.typeToken, "bool|char|short|int")) invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t") || argInfo.typeToken->originalName() == "intmax_t") invalidPrintfArgTypeError_sint(tok, numFormat, specifier, &argInfo); break; } } } done = true; break; case 'u': specifier += *i; if (argInfo.typeToken->tokType() == Token::eString) { invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (argInfo.isArrayOrPointer() && !argInfo.element) { // use %p on pointers and arrays invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (argInfo.isKnownType()) { if (!argInfo.typeToken->isUnsigned() && !Token::Match(argInfo.typeToken, "bool|_Bool")) { if (!(!argInfo.isArrayOrPointer() && argInfo.element)) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (!Token::Match(argInfo.typeToken, "bool|char|short|long|int")) { if (!(!argInfo.isArrayOrPointer() && argInfo.element)) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else { switch (specifier[0]) { case 'h': if (specifier[1] == 'h') { if (!(argInfo.typeToken->str() == "char" && argInfo.typeToken->isUnsigned())) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (!(argInfo.typeToken->str() == "short" && argInfo.typeToken->isUnsigned())) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'l': if (specifier[1] == 'l') { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || argInfo.typeToken->originalName() == "uintmax_t") invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (argInfo.typeToken->str() != "long" || argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || argInfo.typeToken->originalName() == "uintmax_t") invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'j': if (argInfo.typeToken->originalName() != "uintmax_t") invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'z': if (!typesMatch(argInfo.typeToken->originalName(), "size_t")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 't': if (!typesMatch(argInfo.typeToken->originalName(), "ptrdiff_t")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'I': if (specifier.find("I64") != std::string::npos) { if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (specifier.find("I32") != std::string::npos) { if (argInfo.typeToken->str() != "int" || argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); } else if (!typesMatch(argInfo.typeToken->originalName(), "size_t")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; case 'L': if (argInfo.typeToken->str() != "long" || !argInfo.typeToken->isLong()) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; default: if (!Token::Match(argInfo.typeToken, "bool|char|short|int")) invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); else if (typesMatch(argInfo.typeToken->originalName(), "size_t") || argInfo.typeToken->originalName() == "intmax_t") invalidPrintfArgTypeError_uint(tok, numFormat, specifier, &argInfo); break; } } } done = true; break; case 'p': if (argInfo.typeToken->tokType() == Token::eString) ; // string literals are passed as pointers to literal start, okay else if (argInfo.isKnownType() && !argInfo.isArrayOrPointer()) invalidPrintfArgTypeError_p(tok, numFormat, &argInfo); done = true; break; case 'e': case 'E': case 'f': case 'g': case 'G': specifier += *i; if (argInfo.typeToken->tokType() == Token::eString) invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo); else if (argInfo.isArrayOrPointer() && !argInfo.element) { // use %p on pointers and arrays invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo); } else if (argInfo.isKnownType()) { if (!Token::Match(argInfo.typeToken, "float|double")) { if (!(!argInfo.isArrayOrPointer() && argInfo.element)) invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo); } else if ((specifier[0] == 'L' && (!argInfo.typeToken->isLong() || argInfo.typeToken->str() != "double")) || (specifier[0] != 'L' && argInfo.typeToken->isLong())) invalidPrintfArgTypeError_float(tok, numFormat, specifier, &argInfo); } done = true; break; case 'h': // Can be 'hh' (signed char or unsigned char) or 'h' (short int or unsigned short int) case 'l': { // Can be 'll' (long long int or unsigned long long int) or 'l' (long int or unsigned long int) // If the next character is the same (which makes 'hh' or 'll') then expect another alphabetical character if ((i + 1) != formatString.end() && *(i + 1) == *i) { if ((i + 2) != formatString.end() && !isalpha(*(i + 2))) { std::string modifier; modifier += *i; modifier += *(i + 1); invalidLengthModifierError(tok, numFormat, modifier); done = true; } else { specifier = *i++; specifier += *i++; } } else { if ((i + 1) != formatString.end() && !isalpha(*(i + 1))) { std::string modifier; modifier += *i; invalidLengthModifierError(tok, numFormat, modifier); done = true; } else { specifier = *i++; } } } break; case 'I': // Microsoft extension: I for size_t and ptrdiff_t, I32 for __int32, and I64 for __int64 if ((*(i+1) == '3' && *(i+2) == '2') || (*(i+1) == '6' && *(i+2) == '4')) { specifier += *i++; specifier += *i++; } FALLTHROUGH; case 'j': // intmax_t or uintmax_t case 'z': // size_t case 't': // ptrdiff_t case 'L': // long double // Expect an alphabetical character after these specifiers if ((i + 1) != formatString.end() && !isalpha(*(i+1))) { specifier += *i; invalidLengthModifierError(tok, numFormat, specifier); done = true; } else { specifier += *i++; } break; default: done = true; break; } } } } if (argListTok) argListTok = argListTok->nextArgument(); // Find next argument } } } // Count printf/scanf parameters.. int numFunction = 0; while (argListTok2) { if (Token::Match(argListTok2, "%name% ...")) // bailout for parameter pack return; numFunction++; argListTok2 = argListTok2->nextArgument(); // Find next argument } if (printWarning) { // Check that all parameter positions reference an actual parameter for (const int i : parameterPositionsUsed) { if ((i == 0) || (i > numFormat)) wrongPrintfScanfPosixParameterPositionError(tok, tok->str(), i, numFormat); } } // Mismatching number of parameters => warning if ((numFormat + numSecure) != numFunction) wrongPrintfScanfArgumentsError(tok, tok->originalName().empty() ? tok->str() : tok->originalName(), numFormat + numSecure, numFunction); } // We currently only support string literals, variables, and functions. /// @todo add non-string literals, and generic expressions CheckIO::ArgumentInfo::ArgumentInfo(const Token * arg, const Settings &settings, bool _isCPP) : isCPP(_isCPP) { if (!arg) return; // Use AST type info // TODO: This is a bailout so that old code is used in simple cases. Remove the old code and always use the AST type. if (!Token::Match(arg, "%str% ,|)") && !(arg->variable() && arg->variable()->isArray())) { const Token *top = arg; while (top->str() == "(" && !top->isCast()) top = top->next(); while (top->astParent() && top->astParent()->str() != "," && top->astParent() != arg->previous()) top = top->astParent(); const ValueType *valuetype = top->argumentType(); if (valuetype && valuetype->type >= ValueType::Type::BOOL) { typeToken = tempToken = new Token(top); if (valuetype->pointer && valuetype->constness & 1) { tempToken->str("const"); tempToken->insertToken("a"); tempToken = tempToken->next(); } if (valuetype->type == ValueType::BOOL) tempToken->str("bool"); else if (valuetype->type == ValueType::CHAR) tempToken->str("char"); else if (valuetype->type == ValueType::SHORT) tempToken->str("short"); else if (valuetype->type == ValueType::WCHAR_T) tempToken->str("wchar_t"); else if (valuetype->type == ValueType::INT) tempToken->str("int"); else if (valuetype->type == ValueType::LONG) tempToken->str("long"); else if (valuetype->type == ValueType::LONGLONG) { tempToken->str("long"); tempToken->isLong(true); } else if (valuetype->type == ValueType::FLOAT) tempToken->str("float"); else if (valuetype->type == ValueType::DOUBLE) tempToken->str("double"); else if (valuetype->type == ValueType::LONGDOUBLE) { tempToken->str("double"); tempToken->isLong(true); } if (valuetype->isIntegral()) { if (valuetype->sign == ValueType::Sign::UNSIGNED) tempToken->isUnsigned(true); else if (valuetype->sign == ValueType::Sign::SIGNED) tempToken->isSigned(true); } if (!valuetype->originalTypeName.empty()) tempToken->originalName(valuetype->originalTypeName); for (int p = 0; p < valuetype->pointer; p++) tempToken->insertToken("*"); tempToken = const_cast<Token*>(typeToken); if (top->isBinaryOp() && valuetype->pointer == 1 && (valuetype->type == ValueType::CHAR || valuetype->type == ValueType::WCHAR_T)) tempToken->tokType(Token::eString); return; } } if (arg->tokType() == Token::eString) { typeToken = arg; return; } if (arg->str() == "&" || arg->tokType() == Token::eVariable || arg->tokType() == Token::eFunction || Token::Match(arg, "%type% ::") || (Token::Match(arg, "static_cast|reinterpret_cast|const_cast <") && Token::simpleMatch(arg->linkAt(1), "> (") && Token::Match(arg->linkAt(1)->linkAt(1), ") ,|)"))) { if (Token::Match(arg, "static_cast|reinterpret_cast|const_cast")) { typeToken = arg->tokAt(2); while (typeToken->str() == "const" || typeToken->str() == "extern") typeToken = typeToken->next(); return; } if (arg->str() == "&") { address = true; arg = arg->next(); } while (Token::Match(arg, "%type% ::")) arg = arg->tokAt(2); if (!arg || !(arg->tokType() == Token::eVariable || arg->tokType() == Token::eFunction)) return; const Token *varTok = nullptr; const Token *tok1 = arg->next(); for (; tok1; tok1 = tok1->next()) { if (tok1->str() == "," || tok1->str() == ")") { if (tok1->strAt(-1) == "]") { varTok = tok1->linkAt(-1)->previous(); if (varTok->str() == ")" && varTok->link()->previous()->tokType() == Token::eFunction) { const Function * function = varTok->link()->previous()->function(); if (function && function->retType && function->retType->isEnumType()) { if (function->retType->classScope->enumType) typeToken = function->retType->classScope->enumType; else { tempToken = new Token(tok1); tempToken->str("int"); typeToken = tempToken; } } else if (function && function->retDef) { typeToken = function->retDef; while (typeToken->str() == "const" || typeToken->str() == "extern") typeToken = typeToken->next(); functionInfo = function; element = true; } return; } } else if (tok1->strAt(-1) == ")" && tok1->linkAt(-1)->previous()->tokType() == Token::eFunction) { const Function * function = tok1->linkAt(-1)->previous()->function(); if (function && function->retType && function->retType->isEnumType()) { if (function->retType->classScope->enumType) typeToken = function->retType->classScope->enumType; else { tempToken = new Token(tok1); tempToken->str("int"); typeToken = tempToken; } } else if (function && function->retDef) { typeToken = function->retDef; while (typeToken->str() == "const" || typeToken->str() == "extern") typeToken = typeToken->next(); functionInfo = function; element = false; } return; } else varTok = tok1->previous(); break; } if (tok1->str() == "(" || tok1->str() == "{" || tok1->str() == "[") tok1 = tok1->link(); else if (tok1->link() && tok1->str() == "<") tok1 = tok1->link(); // check for some common well known functions else if (isCPP && ((Token::Match(tok1->previous(), "%var% . size|empty|c_str ( ) [,)]") && isStdContainer(tok1->previous())) || (Token::Match(tok1->previous(), "] . size|empty|c_str ( ) [,)]") && isStdContainer(tok1->linkAt(-1)->previous())))) { tempToken = new Token(tok1); if (tok1->strAt(1) == "size") { // size_t is platform dependent if (settings.platform.sizeof_size_t == 8) { tempToken->str("long"); if (settings.platform.sizeof_long != 8) tempToken->isLong(true); } else if (settings.platform.sizeof_size_t == 4) { if (settings.platform.sizeof_long == 4) { tempToken->str("long"); } else { tempToken->str("int"); } } tempToken->originalName("size_t"); tempToken->isUnsigned(true); } else if (tok1->strAt(1) == "empty") { tempToken->str("bool"); } else if (tok1->strAt(1) == "c_str") { tempToken->str("const"); tempToken->insertToken("*"); if (typeToken->strAt(2) == "string") tempToken->insertToken("char"); else tempToken->insertToken("wchar_t"); } typeToken = tempToken; return; } // check for std::vector::at() and std::string::at() else if (Token::Match(tok1->previous(), "%var% . at (") && Token::Match(tok1->linkAt(2), ") [,)]")) { varTok = tok1->previous(); variableInfo = varTok->variable(); if (!variableInfo || !isStdVectorOrString()) { variableInfo = nullptr; typeToken = nullptr; } return; } else if (!(tok1->str() == "." || tok1->tokType() == Token::eVariable || tok1->tokType() == Token::eFunction)) return; } if (varTok) { variableInfo = varTok->variable(); element = tok1->strAt(-1) == "]"; // look for std::vector operator [] and use template type as return type if (variableInfo) { if (element && isStdVectorOrString()) { // isStdVectorOrString sets type token if true element = false; // not really an array element } else if (variableInfo->isEnumType()) { if (variableInfo->type() && variableInfo->type()->classScope && variableInfo->type()->classScope->enumType) typeToken = variableInfo->type()->classScope->enumType; else { tempToken = new Token(tok1); tempToken->str("int"); typeToken = tempToken; } } else typeToken = variableInfo->typeStartToken(); } return; } } } CheckIO::ArgumentInfo::~ArgumentInfo() { if (tempToken) { while (tempToken->next()) tempToken->deleteNext(); delete tempToken; } } namespace { const std::set<std::string> stl_vector = { "array", "vector" }; const std::set<std::string> stl_string = { "string", "u16string", "u32string", "wstring" }; } bool CheckIO::ArgumentInfo::isStdVectorOrString() { if (!isCPP) return false; if (variableInfo->isStlType(stl_vector)) { typeToken = variableInfo->typeStartToken()->tokAt(4); _template = true; return true; } if (variableInfo->isStlType(stl_string)) { tempToken = new Token(variableInfo->typeStartToken()); if (variableInfo->typeStartToken()->strAt(2) == "string") tempToken->str("char"); else tempToken->str("wchar_t"); typeToken = tempToken; return true; } if (variableInfo->type() && !variableInfo->type()->derivedFrom.empty()) { const std::vector<Type::BaseInfo>& derivedFrom = variableInfo->type()->derivedFrom; for (const Type::BaseInfo & i : derivedFrom) { const Token* nameTok = i.nameTok; if (Token::Match(nameTok, "std :: vector|array <")) { typeToken = nameTok->tokAt(4); _template = true; return true; } if (Token::Match(nameTok, "std :: string|wstring")) { tempToken = new Token(variableInfo->typeStartToken()); if (nameTok->strAt(2) == "string") tempToken->str("char"); else tempToken->str("wchar_t"); typeToken = tempToken; return true; } } } else if (variableInfo->type()) { const Scope * classScope = variableInfo->type()->classScope; if (classScope) { for (const Function &func : classScope->functionList) { if (func.name() == "operator[]") { if (Token::Match(func.retDef, "%type% &")) { typeToken = func.retDef; return true; } } } } } return false; } static const std::set<std::string> stl_container = { "array", "bitset", "deque", "forward_list", "hash_map", "hash_multimap", "hash_set", "list", "map", "multimap", "multiset", "priority_queue", "queue", "set", "stack", "unordered_map", "unordered_multimap", "unordered_multiset", "unordered_set", "vector" }; bool CheckIO::ArgumentInfo::isStdContainer(const Token *tok) { if (!isCPP) return false; if (tok && tok->variable()) { const Variable* variable = tok->variable(); if (variable->isStlType(stl_container)) { typeToken = variable->typeStartToken()->tokAt(4); return true; } if (variable->isStlType(stl_string)) { typeToken = variable->typeStartToken(); return true; } if (variable->type() && !variable->type()->derivedFrom.empty()) { for (const Type::BaseInfo &baseInfo : variable->type()->derivedFrom) { const Token* nameTok = baseInfo.nameTok; if (Token::Match(nameTok, "std :: vector|array|bitset|deque|list|forward_list|map|multimap|multiset|priority_queue|queue|set|stack|hash_map|hash_multimap|hash_set|unordered_map|unordered_multimap|unordered_set|unordered_multiset <")) { typeToken = nameTok->tokAt(4); return true; } if (Token::Match(nameTok, "std :: string|wstring")) { typeToken = nameTok; return true; } } } } return false; } bool CheckIO::ArgumentInfo::isArrayOrPointer() const { if (address) return true; if (variableInfo && !_template) return variableInfo->isArrayOrPointer(); const Token *tok = typeToken; while (Token::Match(tok, "const|struct")) tok = tok->next(); return tok && tok->strAt(1) == "*"; } bool CheckIO::ArgumentInfo::isComplexType() const { if (variableInfo->type()) return (true); const Token* varTypeTok = typeToken; if (varTypeTok->str() == "std") varTypeTok = varTypeTok->tokAt(2); return ((variableInfo->isStlStringType() || (varTypeTok->strAt(1) == "<" && varTypeTok->linkAt(1) && varTypeTok->linkAt(1)->strAt(1) != "::")) && !variableInfo->isArrayOrPointer()); } bool CheckIO::ArgumentInfo::isKnownType() const { if (variableInfo) return (typeToken->isStandardType() || typeToken->next()->isStandardType() || isComplexType()); if (functionInfo) return (typeToken->isStandardType() || functionInfo->retType || Token::Match(typeToken, "std :: string|wstring")); return typeToken->isStandardType() || Token::Match(typeToken, "std :: string|wstring"); } bool CheckIO::ArgumentInfo::isLibraryType(const Settings &settings) const { return typeToken && typeToken->isStandardType() && settings.library.podtype(typeToken->str()); } void CheckIO::wrongPrintfScanfArgumentsError(const Token* tok, const std::string &functionName, nonneg int numFormat, nonneg int numFunction) { const Severity severity = numFormat > numFunction ? Severity::error : Severity::warning; if (severity != Severity::error && !mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("wrongPrintfScanfArgNum")) return; std::ostringstream errmsg; errmsg << functionName << " format string requires " << numFormat << " parameter" << (numFormat != 1 ? "s" : "") << " but " << (numFormat > numFunction ? "only " : "") << numFunction << (numFunction != 1 ? " are" : " is") << " given."; reportError(tok, severity, "wrongPrintfScanfArgNum", errmsg.str(), CWE685, Certainty::normal); } void CheckIO::wrongPrintfScanfPosixParameterPositionError(const Token* tok, const std::string& functionName, nonneg int index, nonneg int numFunction) { if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("wrongPrintfScanfParameterPositionError")) return; std::ostringstream errmsg; errmsg << functionName << ": "; if (index == 0) { errmsg << "parameter positions start at 1, not 0"; } else { errmsg << "referencing parameter " << index << " while " << numFunction << " arguments given"; } reportError(tok, Severity::warning, "wrongPrintfScanfParameterPositionError", errmsg.str(), CWE685, Certainty::normal); } void CheckIO::invalidScanfArgTypeError_s(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires a \'"; if (specifier[0] == 's') errmsg << "char"; else if (specifier[0] == 'S') errmsg << "wchar_t"; errmsg << " *\' but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidScanfArgType_s", errmsg.str(), CWE686, Certainty::normal); } void CheckIO::invalidScanfArgTypeError_int(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo, bool isUnsigned) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'"; if (specifier[0] == 'h') { if (specifier[1] == 'h') errmsg << (isUnsigned ? "unsigned " : "") << "char"; else errmsg << (isUnsigned ? "unsigned " : "") << "short"; } else if (specifier[0] == 'l') { if (specifier[1] == 'l') errmsg << (isUnsigned ? "unsigned " : "") << "long long"; else errmsg << (isUnsigned ? "unsigned " : "") << "long"; } else if (specifier.find("I32") != std::string::npos) { errmsg << (isUnsigned ? "unsigned " : "") << "__int32"; } else if (specifier.find("I64") != std::string::npos) { errmsg << (isUnsigned ? "unsigned " : "") << "__int64"; } else if (specifier[0] == 'I') { errmsg << (isUnsigned ? "size_t" : "ptrdiff_t"); } else if (specifier[0] == 'j') { if (isUnsigned) errmsg << "uintmax_t"; else errmsg << "intmax_t"; } else if (specifier[0] == 'z') { if (specifier[1] == 'd' || specifier[1] == 'i') errmsg << "ssize_t"; else errmsg << "size_t"; } else if (specifier[0] == 't') { errmsg << (isUnsigned ? "unsigned " : "") << "ptrdiff_t"; } else if (specifier[0] == 'L') { errmsg << (isUnsigned ? "unsigned " : "") << "long long"; } else { errmsg << (isUnsigned ? "unsigned " : "") << "int"; } errmsg << " *\' but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidScanfArgType_int", errmsg.str(), CWE686, Certainty::normal); } void CheckIO::invalidScanfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'"; if (specifier[0] == 'l' && specifier[1] != 'l') errmsg << "double"; else if (specifier[0] == 'L') errmsg << "long double"; else errmsg << "float"; errmsg << " *\' but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidScanfArgType_float", errmsg.str(), CWE686, Certainty::normal); } void CheckIO::invalidPrintfArgTypeError_s(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%s in format string (no. " << numFormat << ") requires \'char *\' but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidPrintfArgType_s", errmsg.str(), CWE686, Certainty::normal); } void CheckIO::invalidPrintfArgTypeError_n(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%n in format string (no. " << numFormat << ") requires \'int *\' but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidPrintfArgType_n", errmsg.str(), CWE686, Certainty::normal); } void CheckIO::invalidPrintfArgTypeError_p(const Token* tok, nonneg int numFormat, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%p in format string (no. " << numFormat << ") requires an address but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidPrintfArgType_p", errmsg.str(), CWE686, Certainty::normal); } static void printfFormatType(std::ostream& os, const std::string& specifier, bool isUnsigned) { os << "\'"; if (specifier[0] == 'l') { if (specifier[1] == 'l') os << (isUnsigned ? "unsigned " : "") << "long long"; else os << (isUnsigned ? "unsigned " : "") << "long"; } else if (specifier[0] == 'h') { if (specifier[1] == 'h') os << (isUnsigned ? "unsigned " : "") << "char"; else os << (isUnsigned ? "unsigned " : "") << "short"; } else if (specifier.find("I32") != std::string::npos) { os << (isUnsigned ? "unsigned " : "") << "__int32"; } else if (specifier.find("I64") != std::string::npos) { os << (isUnsigned ? "unsigned " : "") << "__int64"; } else if (specifier[0] == 'I') { os << (isUnsigned ? "size_t" : "ptrdiff_t"); } else if (specifier[0] == 'j') { if (isUnsigned) os << "uintmax_t"; else os << "intmax_t"; } else if (specifier[0] == 'z') { if (specifier[1] == 'd' || specifier[1] == 'i') os << "ssize_t"; else os << "size_t"; } else if (specifier[0] == 't') { os << (isUnsigned ? "unsigned " : "") << "ptrdiff_t"; } else if (specifier[0] == 'L') { os << (isUnsigned ? "unsigned " : "") << "long long"; } else { os << (isUnsigned ? "unsigned " : "") << "int"; } os << "\'"; } void CheckIO::invalidPrintfArgTypeError_uint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires "; printfFormatType(errmsg, specifier, true); errmsg << " but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidPrintfArgType_uint", errmsg.str(), CWE686, Certainty::normal); } void CheckIO::invalidPrintfArgTypeError_sint(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires "; printfFormatType(errmsg, specifier, false); errmsg << " but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidPrintfArgType_sint", errmsg.str(), CWE686, Certainty::normal); } void CheckIO::invalidPrintfArgTypeError_float(const Token* tok, nonneg int numFormat, const std::string& specifier, const ArgumentInfo* argInfo) { const Severity severity = getSeverity(argInfo); if (!mSettings->severity.isEnabled(severity)) return; std::ostringstream errmsg; errmsg << "%" << specifier << " in format string (no. " << numFormat << ") requires \'"; if (specifier[0] == 'L') errmsg << "long "; errmsg << "double\' but the argument type is "; argumentType(errmsg, argInfo); errmsg << "."; reportError(tok, severity, "invalidPrintfArgType_float", errmsg.str(), CWE686, Certainty::normal); } Severity CheckIO::getSeverity(const CheckIO::ArgumentInfo *argInfo) { return (argInfo && argInfo->typeToken && !argInfo->typeToken->originalName().empty()) ? Severity::portability : Severity::warning; } void CheckIO::argumentType(std::ostream& os, const ArgumentInfo * argInfo) { if (argInfo) { os << "\'"; const Token *type = argInfo->typeToken; if (type->tokType() == Token::eString) { if (type->isLong()) os << "const wchar_t *"; else os << "const char *"; } else { if (type->originalName().empty()) { if (type->strAt(-1) == "const") os << "const "; while (Token::Match(type, "const|struct")) { os << type->str() << " "; type = type->next(); } while (Token::Match(type, "%any% ::")) { os << type->str() << "::"; type = type->tokAt(2); } os << type->stringify(false, true, false); if (type->strAt(1) == "*" && !argInfo->element) os << " *"; else if (argInfo->variableInfo && !argInfo->element && argInfo->variableInfo->isArray()) os << " *"; else if (type->strAt(1) == "*" && argInfo->variableInfo && argInfo->element && argInfo->variableInfo->isArray()) os << " *"; if (argInfo->address) os << " *"; } else { if (type->isUnsigned()) { if (type->originalName() == "__int64" || type->originalName() == "__int32" || type->originalName() == "ptrdiff_t") os << "unsigned "; } os << type->originalName(); if (type->strAt(1) == "*" || argInfo->address) os << " *"; os << " {aka " << type->stringify(false, true, false); if (type->strAt(1) == "*" || argInfo->address) os << " *"; os << "}"; } } os << "\'"; } else os << "Unknown"; } void CheckIO::invalidLengthModifierError(const Token* tok, nonneg int numFormat, const std::string& modifier) { if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("invalidLengthModifierError")) return; std::ostringstream errmsg; errmsg << "'" << modifier << "' in format string (no. " << numFormat << ") is a length modifier and cannot be used without a conversion specifier."; reportError(tok, Severity::warning, "invalidLengthModifierError", errmsg.str(), CWE704, Certainty::normal); } void CheckIO::invalidScanfFormatWidthError(const Token* tok, nonneg int numFormat, int width, const Variable *var, const std::string& specifier) { MathLib::bigint arrlen = 0; std::string varname; if (var) { arrlen = var->dimension(0); varname = var->name(); } std::ostringstream errmsg; if (arrlen > width) { if (tok != nullptr && (!mSettings->certainty.isEnabled(Certainty::inconclusive) || !mSettings->severity.isEnabled(Severity::warning))) return; errmsg << "Width " << width << " given in format string (no. " << numFormat << ") is smaller than destination buffer" << " '" << varname << "[" << arrlen << "]'."; reportError(tok, Severity::warning, "invalidScanfFormatWidth_smaller", errmsg.str(), CWE(0U), Certainty::inconclusive); } else { errmsg << "Width " << width << " given in format string (no. " << numFormat << ") is larger than destination buffer '" << varname << "[" << arrlen << "]', use %" << (specifier == "c" ? arrlen : (arrlen - 1)) << specifier << " to prevent overflowing it."; reportError(tok, Severity::error, "invalidScanfFormatWidth", errmsg.str(), CWE687, Certainty::normal); } }
111,648
C++
.cpp
1,913
36.877679
251
0.45365
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,145
vf_array.cpp
danmar_cppcheck/lib/vf_array.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_array.h" #include "astutils.h" #include "config.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <map> #include <utility> namespace ValueFlow { void analyzeArray(TokenList &tokenlist, const Settings &settings) { std::map<nonneg int, const Token *> constantArrays; for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (tok->varId() > 0) { // array const std::map<nonneg int, const Token *>::const_iterator it = constantArrays.find(tok->varId()); if (it != constantArrays.end()) { Value value; value.valueType = Value::ValueType::TOK; value.tokvalue = it->second; value.setKnown(); setTokenValue(tok, std::move(value), settings); } // const array decl else if (tok->variable() && tok->variable()->isArray() && tok->variable()->isConst() && tok->variable()->nameToken() == tok && Token::Match(tok, "%var% [ %num%| ] = {")) { Token* rhstok = tok->linkAt(1)->tokAt(2); constantArrays[tok->varId()] = rhstok; tok = rhstok->link(); } // pointer = array else if (tok->variable() && tok->variable()->isArray() && Token::simpleMatch(tok->astParent(), "=") && astIsRHS(tok) && tok->astParent()->astOperand1() && tok->astParent()->astOperand1()->variable() && tok->astParent()->astOperand1()->variable()->isPointer()) { Value value; value.valueType = Value::ValueType::TOK; value.tokvalue = tok; value.setKnown(); setTokenValue(tok, std::move(value), settings); } continue; } if (Token::Match(tok, "const %type% %var% [ %num%| ] = {")) { Token *vartok = tok->tokAt(2); Token *rhstok = vartok->linkAt(1)->tokAt(2); constantArrays[vartok->varId()] = rhstok; tok = rhstok->link(); continue; } if (Token::Match(tok, "const char %var% [ %num%| ] = %str% ;")) { Token *vartok = tok->tokAt(2); Token *strtok = vartok->linkAt(1)->tokAt(2); constantArrays[vartok->varId()] = strtok; tok = strtok->next(); continue; } } } }
3,476
C++
.cpp
80
32.075
118
0.536917
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,146
vf_reverse.cpp
danmar_cppcheck/lib/vf_reverse.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_reverse.h" #include "reverseanalyzer.h" #include "settings.h" #include "vfvalue.h" #include "vf_analyzers.h" #include "vf_common.h" #include <utility> namespace ValueFlow { void valueFlowReverse(Token* tok, const Token* const endToken, const Token* const varToken, std::list<Value> values, const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings, SourceLocation loc) { for (Value& v : values) { if (settings.debugnormal) setSourceLocation(v, loc, tok); valueFlowGenericReverse(tok, endToken, makeReverseAnalyzer(varToken, std::move(v), settings), tokenlist, errorLogger, settings); } } }
1,629
C++
.cpp
42
31.333333
140
0.651075
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,147
vf_infercondition.cpp
danmar_cppcheck/lib/vf_infercondition.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_infercondition.h" #include "astutils.h" #include "infer.h" #include "mathlib.h" #include "token.h" #include "tokenlist.h" #include "valueflow.h" #include "valueptr.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <array> #include <list> #include <utility> #include <vector> namespace ValueFlow { struct IteratorInferModel : InferModel { virtual Value::ValueType getType() const = 0; bool match(const Value& value) const override { return value.valueType == getType(); } Value yield(MathLib::bigint value) const override { Value result(value); result.valueType = getType(); result.setKnown(); return result; } }; struct EndIteratorInferModel : IteratorInferModel { Value::ValueType getType() const override { return Value::ValueType::ITERATOR_END; } }; struct StartIteratorInferModel : IteratorInferModel { Value::ValueType getType() const override { return Value::ValueType::ITERATOR_END; } }; static bool isIntegralOnlyOperator(const Token* tok) { return Token::Match(tok, "%|<<|>>|&|^|~|%or%"); } static bool isIntegralOrPointer(const Token* tok) { if (!tok) return false; if (astIsIntegral(tok, false)) return true; if (astIsPointer(tok)) return true; if (Token::Match(tok, "NULL|nullptr")) return true; if (tok->valueType()) return false; // These operators only work on integers if (isIntegralOnlyOperator(tok)) return true; if (isIntegralOnlyOperator(tok->astParent())) return true; if (Token::Match(tok, "+|-|*|/") && tok->isBinaryOp()) return isIntegralOrPointer(tok->astOperand1()) && isIntegralOrPointer(tok->astOperand2()); return false; } void analyzeInferCondition(TokenList& tokenlist, const Settings& settings) { for (Token* tok = tokenlist.front(); tok; tok = tok->next()) { if (!tok->astParent()) continue; if (tok->hasKnownIntValue()) continue; if (Token::Match(tok, "%comp%|-") && tok->astOperand1() && tok->astOperand2()) { if (astIsIterator(tok->astOperand1()) || astIsIterator(tok->astOperand2())) { static const std::array<ValuePtr<InferModel>, 2> iteratorModels = {EndIteratorInferModel{}, StartIteratorInferModel{}}; for (const ValuePtr<InferModel>& model : iteratorModels) { std::vector<Value> result = infer(model, tok->str(), tok->astOperand1()->values(), tok->astOperand2()->values()); for (Value value : result) { value.valueType = Value::ValueType::INT; setTokenValue(tok, std::move(value), settings); } } } else if (isIntegralOrPointer(tok->astOperand1()) && isIntegralOrPointer(tok->astOperand2())) { std::vector<Value> result = infer(makeIntegralInferModel(), tok->str(), tok->astOperand1()->values(), tok->astOperand2()->values()); for (Value& value : result) { setTokenValue(tok, std::move(value), settings); } } } else if (Token::Match(tok->astParent(), "?|&&|!|%oror%") || Token::Match(tok->astParent()->previous(), "if|while (") || (astIsPointer(tok) && isUsedAsBool(tok, settings))) { std::vector<Value> result = infer(makeIntegralInferModel(), "!=", tok->values(), 0); if (result.size() != 1) continue; Value value = result.front(); setTokenValue(tok, std::move(value), settings); } } } }
4,918
C++
.cpp
118
31.127119
128
0.572025
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,148
checkautovariables.cpp
danmar_cppcheck/lib/checkautovariables.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- // Auto variables checks //--------------------------------------------------------------------------- #include "checkautovariables.h" #include "astutils.h" #include "library.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "valueflow.h" #include "vfvalue.h" #include <algorithm> #include <list> #include <unordered_set> #include <utility> #include <vector> //--------------------------------------------------------------------------- // Register this check class into cppcheck by creating a static instance of it.. namespace { CheckAutoVariables instance; } static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE562(562U); // Return of Stack Variable Address static const CWE CWE590(590U); // Free of Memory not on the Heap static bool isPtrArg(const Token *tok) { const Variable *var = tok->variable(); return (var && var->isArgument() && var->isPointer()); } static bool isArrayArg(const Token *tok, const Settings& settings) { const Variable *var = tok->variable(); return (var && var->isArgument() && var->isArray() && !settings.library.isentrypoint(var->scope()->className)); } static bool isArrayVar(const Token *tok) { const Variable *var = tok->variable(); return (var && var->isArray() && !var->isArgument()); } static bool isRefPtrArg(const Token *tok) { const Variable *var = tok->variable(); return (var && var->isArgument() && var->isReference() && var->isPointer()); } static bool isNonReferenceArg(const Token *tok) { const Variable *var = tok->variable(); return (var && var->isArgument() && !var->isReference() && (var->isPointer() || (var->valueType() && var->valueType()->type >= ValueType::Type::CONTAINER) || var->type())); } static bool isAutoVar(const Token *tok) { const Variable *var = tok->variable(); if (!var || !var->isLocal() || var->isStatic()) return false; if (var->isReference()) { // address of reference variable can be taken if the address // of the variable it points at is not a auto-var // TODO: check what the reference variable references. return false; } if (Token::Match(tok, "%name% .|::")) { do { tok = tok->tokAt(2); } while (Token::Match(tok, "%name% .|::")); if (Token::Match(tok, "%name% (")) return false; } return true; } static bool isAutoVarArray(const Token *tok) { if (!tok) return false; // &x[..] if (tok->isUnaryOp("&") && Token::simpleMatch(tok->astOperand1(), "[")) return isAutoVarArray(tok->astOperand1()->astOperand1()); // x+y if (tok->str() == "+") return isAutoVarArray(tok->astOperand1()) || isAutoVarArray(tok->astOperand2()); // x-intexpr if (tok->str() == "-") return isAutoVarArray(tok->astOperand1()) && tok->astOperand2() && tok->astOperand2()->valueType() && tok->astOperand2()->valueType()->isIntegral(); const Variable *var = tok->variable(); if (!var) return false; // Variable if (var->isLocal() && !var->isStatic() && var->isArray() && !var->isPointer()) return true; // ValueFlow if (var->isPointer() && !var->isArgument()) { for (std::list<ValueFlow::Value>::const_iterator it = tok->values().cbegin(); it != tok->values().cend(); ++it) { const ValueFlow::Value &val = *it; if (val.isTokValue() && isAutoVarArray(val.tokvalue)) return true; } } return false; } static bool isLocalContainerBuffer(const Token* tok) { if (!tok) return false; // x+y if (tok->str() == "+") return isLocalContainerBuffer(tok->astOperand1()) || isLocalContainerBuffer(tok->astOperand2()); if (tok->str() != "(" || !Token::simpleMatch(tok->astOperand1(), ".")) return false; tok = tok->astOperand1()->astOperand1(); const Variable* var = tok->variable(); if (!var || !var->isLocal() || var->isStatic()) return false; const Library::Container::Yield yield = astContainerYield(tok); return yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT; } static bool isAddressOfLocalVariable(const Token *expr) { if (!expr) return false; if (Token::Match(expr, "+|-")) return isAddressOfLocalVariable(expr->astOperand1()) || isAddressOfLocalVariable(expr->astOperand2()); if (expr->isCast()) return isAddressOfLocalVariable(expr->astOperand2() ? expr->astOperand2() : expr->astOperand1()); if (expr->isUnaryOp("&")) { const Token *op = expr->astOperand1(); bool deref = false; while (Token::Match(op, ".|[")) { if (op->originalName() == "->") return false; if (op->str() == "[") deref = true; op = op->astOperand1(); } return op && isAutoVar(op) && (!deref || !op->variable()->isPointer()); } return false; } static bool variableIsUsedInScope(const Token* start, nonneg int varId, const Scope *scope) { if (!start) // Ticket #5024 return false; for (const Token *tok = start; tok && tok != scope->bodyEnd; tok = tok->next()) { if (tok->varId() == varId) return true; const Scope::ScopeType scopeType = tok->scope()->type; if (scopeType == Scope::eFor || scopeType == Scope::eDo || scopeType == Scope::eWhile) // In case of loops, better checking would be necessary return true; if (Token::simpleMatch(tok, "asm (")) return true; } return false; } void CheckAutoVariables::assignFunctionArg() { const bool printStyle = mSettings->severity.isEnabled(Severity::style); const bool printWarning = mSettings->severity.isEnabled(Severity::warning); if (!printStyle && !printWarning && !mSettings->isPremiumEnabled("uselessAssignmentPtrArg")) return; logChecker("CheckAutoVariables::assignFunctionArg"); // style,warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { // TODO: What happens if this is removed? if (tok->astParent()) continue; if (!(tok->isAssignmentOp() || tok->tokType() == Token::eIncDecOp) || !Token::Match(tok->astOperand1(), "%var%")) continue; const Token* const vartok = tok->astOperand1(); if (isNonReferenceArg(vartok) && !Token::Match(vartok->next(), "= %varid% ;", vartok->varId()) && !variableIsUsedInScope(Token::findsimplematch(vartok->next(), ";"), vartok->varId(), scope) && !Token::findsimplematch(vartok, "goto", scope->bodyEnd)) { if (vartok->variable()->isPointer() && printWarning) errorUselessAssignmentPtrArg(vartok); else if (printStyle) errorUselessAssignmentArg(vartok); } } } } static bool isAutoVariableRHS(const Token* tok) { return isAddressOfLocalVariable(tok) || isAutoVarArray(tok) || isLocalContainerBuffer(tok); } static bool hasOverloadedAssignment(const Token* tok, bool& inconclusive) { inconclusive = false; if (tok->isC()) return false; if (const ValueType* vt = tok->valueType()) { if (vt->pointer && !Token::simpleMatch(tok->astParent(), "*")) return false; if (vt->container && vt->container->stdStringLike) return true; if (vt->typeScope) return std::any_of(vt->typeScope->functionList.begin(), vt->typeScope->functionList.end(), [](const Function& f) { // TODO: compare argument type return f.name() == "operator="; }); return false; } inconclusive = true; return true; } void CheckAutoVariables::autoVariables() { logChecker("CheckAutoVariables::autoVariables"); const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { // Skip lambda.. if (const Token *lambdaEndToken = findLambdaEndToken(tok)) { tok = lambdaEndToken; continue; } // Critical assignment if (Token::Match(tok, "[;{}] %var% =") && isRefPtrArg(tok->next()) && isAutoVariableRHS(tok->tokAt(2)->astOperand2())) { checkAutoVariableAssignment(tok->next(), false); } else if (Token::Match(tok, "[;{}] * %var% =") && isPtrArg(tok->tokAt(2)) && isAutoVariableRHS(tok->tokAt(3)->astOperand2())) { const Token* lhs = tok->tokAt(2); bool inconclusive = false; if (!hasOverloadedAssignment(lhs, inconclusive) || (printInconclusive && inconclusive)) checkAutoVariableAssignment(tok->next(), inconclusive); tok = tok->tokAt(4); } else if (Token::Match(tok, "[;{}] %var% . %var% =") && isPtrArg(tok->next()) && isAutoVariableRHS(tok->tokAt(4)->astOperand2())) { const Token* lhs = tok->tokAt(3); bool inconclusive = false; if (!hasOverloadedAssignment(lhs, inconclusive) || (printInconclusive && inconclusive)) checkAutoVariableAssignment(tok->next(), inconclusive); tok = tok->tokAt(5); } else if (Token::Match(tok, "[;{}] %var% [") && Token::simpleMatch(tok->linkAt(2), "] =") && (isPtrArg(tok->next()) || isArrayArg(tok->next(), *mSettings)) && isAutoVariableRHS(tok->linkAt(2)->next()->astOperand2())) { errorAutoVariableAssignment(tok->next(), false); } // Invalid pointer deallocation else if ((Token::Match(tok, "%name% ( %var%|%str% ) ;") && mSettings->library.getDeallocFuncInfo(tok)) || (tok->isCpp() && Token::Match(tok, "delete [| ]| (| %var%|%str% !!["))) { tok = Token::findmatch(tok->next(), "%var%|%str%"); if (Token::simpleMatch(tok->astParent(), ".")) continue; if (isArrayVar(tok) || tok->tokType() == Token::eString) errorInvalidDeallocation(tok, nullptr); else if (tok->variable() && tok->variable()->isPointer()) { for (const ValueFlow::Value &v : tok->values()) { if (v.isImpossible()) continue; if ((v.isTokValue() && (isArrayVar(v.tokvalue) || ((v.tokvalue->tokType() == Token::eString)))) || (v.isLocalLifetimeValue() && v.lifetimeKind == ValueFlow::Value::LifetimeKind::Address && !Token::simpleMatch(v.tokvalue, "("))) { errorInvalidDeallocation(tok, &v); break; } } } } else if ((Token::Match(tok, "%name% ( & %var% ) ;") && mSettings->library.getDeallocFuncInfo(tok)) || (tok->isCpp() && Token::Match(tok, "delete [| ]| (| & %var% !!["))) { tok = Token::findmatch(tok->next(), "%var%"); if (isAutoVar(tok)) errorInvalidDeallocation(tok, nullptr); } } } } bool CheckAutoVariables::checkAutoVariableAssignment(const Token *expr, bool inconclusive, const Token *startToken) { if (!startToken) startToken = Token::findsimplematch(expr, "=")->next(); for (const Token *tok = startToken; tok; tok = tok->next()) { if (tok->str() == "}" && tok->scope()->type == Scope::ScopeType::eFunction) errorAutoVariableAssignment(expr, inconclusive); if (Token::Match(tok, "return|throw|break|continue")) { errorAutoVariableAssignment(expr, inconclusive); return true; } if (Token::simpleMatch(tok, "=")) { const Token *lhs = tok; while (Token::Match(lhs->previous(), "%name%|.|*|]")) { if (lhs->linkAt(-1)) lhs = lhs->linkAt(-1); else lhs = lhs->previous(); } const Token *e = expr; while (e->str() != "=" && lhs->str() == e->str()) { e = e->next(); lhs = lhs->next(); } if (lhs->str() == "=") return false; } if (Token::simpleMatch(tok, "if (")) { const Token *ifStart = tok->linkAt(1)->next(); return checkAutoVariableAssignment(expr, inconclusive, ifStart) || checkAutoVariableAssignment(expr, inconclusive, ifStart->link()->next()); } if (Token::simpleMatch(tok, "} else {")) tok = tok->linkAt(2); } return false; } //--------------------------------------------------------------------------- void CheckAutoVariables::errorAutoVariableAssignment(const Token *tok, bool inconclusive) { if (!inconclusive) { reportError(tok, Severity::error, "autoVariables", "Address of local auto-variable assigned to a function parameter.\n" "Dangerous assignment - the function parameter is assigned the address of a local " "auto-variable. Local auto-variables are reserved from the stack which " "is freed when the function ends. So the pointer to a local variable " "is invalid after the function ends.", CWE562, Certainty::normal); } else { reportError(tok, Severity::error, "autoVariables", "Address of local auto-variable assigned to a function parameter.\n" "Function parameter is assigned the address of a local auto-variable. " "Local auto-variables are reserved from the stack which is freed when " "the function ends. The address is invalid after the function ends and it " "might 'leak' from the function through the parameter.", CWE562, Certainty::inconclusive); } } void CheckAutoVariables::errorUselessAssignmentArg(const Token *tok) { reportError(tok, Severity::style, "uselessAssignmentArg", "Assignment of function parameter has no effect outside the function.", CWE398, Certainty::normal); } void CheckAutoVariables::errorUselessAssignmentPtrArg(const Token *tok) { reportError(tok, Severity::warning, "uselessAssignmentPtrArg", "Assignment of function parameter has no effect outside the function. Did you forget dereferencing it?", CWE398, Certainty::normal); } bool CheckAutoVariables::diag(const Token* tokvalue) { if (!tokvalue) return true; return !mDiagDanglingTemp.insert(tokvalue).second; } //--------------------------------------------------------------------------- static bool isInScope(const Token * tok, const Scope * scope) { if (!tok) return false; if (!scope) return false; const Variable * var = tok->variable(); if (var && (var->isGlobal() || var->isStatic() || var->isExtern())) return false; if (tok->scope() && !tok->scope()->isClassOrStructOrUnion() && tok->scope()->isNestedIn(scope)) return true; if (!var) return false; if (var->isArgument() && !var->isReference()) { const Scope * tokScope = tok->scope(); if (!tokScope) return false; if (std::any_of(tokScope->nestedList.cbegin(), tokScope->nestedList.cend(), [&](const Scope* argScope) { return argScope && argScope->isNestedIn(scope); })) return true; } return false; } static bool isDeadScope(const Token * tok, const Scope * scope) { if (!tok) return false; if (!scope) return false; const Variable * var = tok->variable(); if (var && (!var->isLocal() || var->isStatic() || var->isExtern())) return false; if (tok->scope() && tok->scope()->bodyEnd != scope->bodyEnd && precedes(tok->scope()->bodyEnd, scope->bodyEnd)) return true; return false; } static int getPointerDepth(const Token *tok) { if (!tok) return 0; if (tok->valueType()) return tok->valueType()->pointer; int n = 0; std::pair<const Token*, const Token*> decl = Token::typeDecl(tok); for (const Token* tok2 = decl.first; tok2 != decl.second; tok2 = tok2->next()) if (Token::simpleMatch(tok2, "*")) n++; return n; } static bool isDeadTemporary(const Token* tok, const Token* expr, const Library* library) { if (!isTemporary(tok, library)) return false; if (expr) { if (!precedes(nextAfterAstRightmostLeaf(tok->astTop()), nextAfterAstRightmostLeaf(expr->astTop()))) return false; const Token* parent = tok->astParent(); if (Token::simpleMatch(parent, "{") && Token::simpleMatch(parent->astParent(), ":")) parent = parent->astParent(); // Is in a for loop if (astIsRHS(tok) && Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "(") && Token::simpleMatch(parent->astParent()->previous(), "for (")) { const Token* braces = parent->astParent()->link()->next(); if (precedes(braces, expr) && precedes(expr, braces->link())) return false; } } return true; } static bool isEscapedReference(const Variable* var) { if (!var) return false; if (!var->isReference()) return false; const Token * const varDeclEndToken = var->declEndToken(); if (!varDeclEndToken) return false; if (!Token::simpleMatch(varDeclEndToken, "=")) return false; const Token* vartok = varDeclEndToken->astOperand2(); return !isTemporary(vartok, nullptr, false); } static bool isDanglingSubFunction(const Token* tokvalue, const Token* tok) { if (!tokvalue) return false; const Variable* var = tokvalue->variable(); if (!var->isLocal()) return false; const Function* f = Scope::nestedInFunction(tok->scope()); if (!f) return false; const Token* parent = tokvalue->astParent(); while (parent && !Token::Match(parent->previous(), "%name% (")) { parent = parent->astParent(); } if (!Token::simpleMatch(parent, "(")) return false; return exprDependsOnThis(parent); } static const Variable* getParentVar(const Token* tok) { if (!tok) return nullptr; if (Token::simpleMatch(tok, ".")) return getParentVar(tok->astOperand1()); return tok->variable(); } static bool isAssignedToNonLocal(const Token* tok) { if (!Token::simpleMatch(tok->astParent(), "=")) return false; if (!astIsRHS(tok)) return false; const Variable* var = getParentVar(tok->astParent()->astOperand1()); if (!var) return false; return !var->isLocal() || var->isStatic(); } void CheckAutoVariables::checkVarLifetimeScope(const Token * start, const Token * end) { const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); if (!start) return; const Scope * scope = start->scope(); if (!scope) return; // If the scope is not set correctly then skip checking it if (scope->bodyStart != start) return; const bool returnRef = Function::returnsReference(scope->function); for (const Token *tok = start; tok && tok != end; tok = tok->next()) { // Return reference from function if (returnRef && Token::simpleMatch(tok->astParent(), "return")) { for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(tok, *mSettings, true)) { if (!printInconclusive && lt.inconclusive) continue; const Variable* var = lt.token->variable(); if (var && !var->isGlobal() && !var->isStatic() && !var->isReference() && !var->isRValueReference() && isInScope(var->nameToken(), tok->scope())) { errorReturnReference(tok, lt.errorPath, lt.inconclusive); break; } if (isDeadTemporary(lt.token, nullptr, &mSettings->library)) { errorReturnTempReference(tok, lt.errorPath, lt.inconclusive); break; } } // Assign reference to non-local variable } else if (Token::Match(tok->previous(), "&|&& %var% =") && tok->astParent() == tok->next() && tok->variable() && tok->variable()->nameToken() == tok && tok->variable()->declarationId() == tok->varId() && tok->variable()->isStatic() && !tok->variable()->isArgument()) { ErrorPath errorPath; const Variable *var = ValueFlow::getLifetimeVariable(tok, errorPath, *mSettings); if (var && isInScope(var->nameToken(), tok->scope())) { errorDanglingReference(tok, var, std::move(errorPath)); continue; } // Reference to temporary } else if (tok->variable() && (tok->variable()->isReference() || tok->variable()->isRValueReference())) { for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(getParentLifetime(tok), *mSettings)) { if (!printInconclusive && lt.inconclusive) continue; const Token * tokvalue = lt.token; if (isDeadTemporary(tokvalue, tok, &mSettings->library)) { errorDanglingTempReference(tok, lt.errorPath, lt.inconclusive); break; } } } const bool escape = Token::simpleMatch(tok->astParent(), "throw") || (Token::simpleMatch(tok->astParent(), "return") && !Function::returnsStandardType(scope->function)); std::unordered_set<const Token*> exprs; for (const ValueFlow::Value& val:tok->values()) { if (!val.isLocalLifetimeValue() && !val.isSubFunctionLifetimeValue()) continue; if (!printInconclusive && val.isInconclusive()) continue; const Token* parent = getParentLifetime(val.tokvalue, mSettings->library); if (!exprs.insert(parent).second) continue; for (const ValueFlow::LifetimeToken& lt : ValueFlow::getLifetimeTokens(parent, *mSettings, escape || isAssignedToNonLocal(tok))) { const Token * tokvalue = lt.token; if (val.isLocalLifetimeValue()) { if (escape) { if (getPointerDepth(tok) < getPointerDepth(tokvalue)) continue; if (!ValueFlow::isLifetimeBorrowed(tok, *mSettings)) continue; if (tokvalue->exprId() == tok->exprId() && !(tok->variable() && tok->variable()->isArray()) && !astIsContainerView(tok->astParent())) continue; if ((tokvalue->variable() && !isEscapedReference(tokvalue->variable()) && isInScope(tokvalue->variable()->nameToken(), scope)) || isDeadTemporary(tokvalue, nullptr, &mSettings->library)) { errorReturnDanglingLifetime(tok, &val); break; } } else if (tokvalue->variable() && isDeadScope(tokvalue->variable()->nameToken(), tok->scope())) { errorInvalidLifetime(tok, &val); break; } else if (!tokvalue->variable() && isDeadTemporary(tokvalue, tok, &mSettings->library)) { if (!diag(tokvalue)) errorDanglingTemporaryLifetime(tok, &val, tokvalue); break; } } if (tokvalue->variable() && (isInScope(tokvalue->variable()->nameToken(), tok->scope()) || (val.isSubFunctionLifetimeValue() && isDanglingSubFunction(tokvalue, tok)))) { const Variable * var = nullptr; const Token * tok2 = tok; if (Token::simpleMatch(tok->astParent(), "=")) { if (astIsRHS(tok)) { var = getParentVar(tok->astParent()->astOperand1()); tok2 = tok->astParent()->astOperand1(); } } else if (tok->variable() && tok->variable()->declarationId() == tok->varId()) { var = tok->variable(); } if (!ValueFlow::isLifetimeBorrowed(tok, *mSettings)) continue; const Token* nextTok = nextAfterAstRightmostLeaf(tok->astTop()); if (!nextTok) nextTok = tok->next(); if (var && !var->isLocal() && !var->isArgument() && !(val.tokvalue && val.tokvalue->variable() && val.tokvalue->variable()->isStatic()) && !isVariableChanged(nextTok, tok->scope()->bodyEnd, var->declarationId(), var->isGlobal(), *mSettings)) { errorDanglngLifetime(tok2, &val); break; } } } } const Token *lambdaEndToken = findLambdaEndToken(tok); if (lambdaEndToken) { checkVarLifetimeScope(lambdaEndToken->link(), lambdaEndToken); tok = lambdaEndToken; } if (tok->str() == "{" && tok->scope()) { // Check functions in local classes if (tok->scope()->type == Scope::eClass || tok->scope()->type == Scope::eStruct || tok->scope()->type == Scope::eUnion) { for (const Function& f:tok->scope()->functionList) { if (f.functionScope) checkVarLifetimeScope(f.functionScope->bodyStart, f.functionScope->bodyEnd); } tok = tok->link(); } } } } void CheckAutoVariables::checkVarLifetime() { logChecker("CheckAutoVariables::checkVarLifetime"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { if (!scope->function) continue; checkVarLifetimeScope(scope->bodyStart, scope->bodyEnd); } } void CheckAutoVariables::errorReturnDanglingLifetime(const Token *tok, const ValueFlow::Value *val) { const bool inconclusive = val ? val->isInconclusive() : false; ErrorPath errorPath = val ? val->errorPath : ErrorPath(); std::string msg = "Returning " + lifetimeMessage(tok, val, errorPath); errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "returnDanglingLifetime", msg + " that will be invalid when returning.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckAutoVariables::errorInvalidLifetime(const Token *tok, const ValueFlow::Value* val) { const bool inconclusive = val ? val->isInconclusive() : false; ErrorPath errorPath = val ? val->errorPath : ErrorPath(); std::string msg = "Using " + lifetimeMessage(tok, val, errorPath); errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "invalidLifetime", msg + " that is out of scope.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckAutoVariables::errorDanglingTemporaryLifetime(const Token* tok, const ValueFlow::Value* val, const Token* tempTok) { const bool inconclusive = val ? val->isInconclusive() : false; ErrorPath errorPath = val ? val->errorPath : ErrorPath(); std::string msg = "Using " + lifetimeMessage(tok, val, errorPath); errorPath.emplace_back(tempTok, "Temporary created here."); errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "danglingTemporaryLifetime", msg + " that is a temporary.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckAutoVariables::errorDanglngLifetime(const Token *tok, const ValueFlow::Value *val) { const bool inconclusive = val ? val->isInconclusive() : false; ErrorPath errorPath = val ? val->errorPath : ErrorPath(); std::string tokName = tok ? tok->expressionString() : "x"; std::string msg = "Non-local variable '" + tokName + "' will use " + lifetimeMessage(tok, val, errorPath); errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "danglingLifetime", msg + ".", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckAutoVariables::errorDanglingTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive) { errorPath.emplace_back(tok, ""); reportError( errorPath, Severity::error, "danglingTempReference", "Using reference to dangling temporary.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckAutoVariables::errorReturnReference(const Token* tok, ErrorPath errorPath, bool inconclusive) { errorPath.emplace_back(tok, ""); reportError( errorPath, Severity::error, "returnReference", "Reference to local variable returned.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckAutoVariables::errorDanglingReference(const Token *tok, const Variable *var, ErrorPath errorPath) { std::string tokName = tok ? tok->str() : "x"; std::string varName = var ? var->name() : "y"; std::string msg = "Non-local reference variable '" + tokName + "' to local variable '" + varName + "'"; errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "danglingReference", msg, CWE562, Certainty::normal); } void CheckAutoVariables::errorReturnTempReference(const Token* tok, ErrorPath errorPath, bool inconclusive) { errorPath.emplace_back(tok, ""); reportError( errorPath, Severity::error, "returnTempReference", "Reference to temporary returned.", CWE562, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckAutoVariables::errorInvalidDeallocation(const Token *tok, const ValueFlow::Value *val) { const Variable *var = val ? val->tokvalue->variable() : (tok ? tok->variable() : nullptr); std::string type = "an auto-variable"; if (tok && tok->tokType() == Token::eString) type = "a string literal"; else if (val && val->tokvalue->tokType() == Token::eString) type = "a pointer pointing to a string literal"; else if (var) { if (var->isGlobal()) type = "a global variable"; else if (var->isStatic()) type = "a static variable"; } if (val) type += " (" + val->tokvalue->str() + ")"; reportError(getErrorPath(tok, val, "Deallocating memory that was not dynamically allocated"), Severity::error, "autovarInvalidDeallocation", "Deallocation of " + type + " results in undefined behaviour.\n" "The deallocation of " + type + " results in undefined behaviour. You should only free memory " "that has been allocated dynamically.", CWE590, Certainty::normal); }
33,289
C++
.cpp
716
36.713687
185
0.582
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,149
timer.cpp
danmar_cppcheck/lib/timer.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2023 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "timer.h" #include "utils.h" #include <algorithm> #include <iostream> #include <utility> #include <vector> namespace { using dataElementType = std::pair<std::string, TimerResultsData>; bool more_second_sec(const dataElementType& lhs, const dataElementType& rhs) { return lhs.second.seconds() > rhs.second.seconds(); } // TODO: remove and print through (synchronized) ErrorLogger instead std::mutex stdCoutLock; } // TODO: this does not include any file context when SHOWTIME_FILE thus rendering it useless - should we include the logging with the progress logging? // that could also get rid of the broader locking void TimerResults::showResults(SHOWTIME_MODES mode) const { if (mode == SHOWTIME_MODES::SHOWTIME_NONE || mode == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL) return; TimerResultsData overallData; std::vector<dataElementType> data; { std::lock_guard<std::mutex> l(mResultsSync); data.reserve(mResults.size()); data.insert(data.begin(), mResults.cbegin(), mResults.cend()); } std::sort(data.begin(), data.end(), more_second_sec); // lock the whole logging operation to avoid multiple threads printing their results at the same time std::lock_guard<std::mutex> l(stdCoutLock); std::cout << std::endl; size_t ordinal = 1; // maybe it would be nice to have an ordinal in output later! for (std::vector<dataElementType>::const_iterator iter=data.cbegin(); iter!=data.cend(); ++iter) { const double sec = iter->second.seconds(); const double secAverage = sec / (double)(iter->second.mNumberOfResults); bool hasParent = false; { // Do not use valueFlow.. in "Overall time" because those are included in Tokenizer already if (startsWith(iter->first,"valueFlow")) hasParent = true; // Do not use inner timers in "Overall time" const std::string::size_type pos = iter->first.rfind("::"); if (pos != std::string::npos) hasParent = std::any_of(data.cbegin(), data.cend(), [iter,pos](const dataElementType& d) { return d.first.size() == pos && iter->first.compare(0, d.first.size(), d.first) == 0; }); } if (!hasParent) overallData.mClocks += iter->second.mClocks; if ((mode != SHOWTIME_MODES::SHOWTIME_TOP5_FILE && mode != SHOWTIME_MODES::SHOWTIME_TOP5_SUMMARY) || (ordinal<=5)) { std::cout << iter->first << ": " << sec << "s (avg. " << secAverage << "s - " << iter->second.mNumberOfResults << " result(s))" << std::endl; } ++ordinal; } const double secOverall = overallData.seconds(); std::cout << "Overall time: " << secOverall << "s" << std::endl; } void TimerResults::addResults(const std::string& str, std::clock_t clocks) { std::lock_guard<std::mutex> l(mResultsSync); mResults[str].mClocks += clocks; mResults[str].mNumberOfResults++; } void TimerResults::reset() { std::lock_guard<std::mutex> l(mResultsSync); mResults.clear(); } Timer::Timer(std::string str, SHOWTIME_MODES showtimeMode, TimerResultsIntf* timerResults) : mStr(std::move(str)) , mTimerResults(timerResults) , mStart(std::clock()) , mShowTimeMode(showtimeMode) , mStopped(showtimeMode == SHOWTIME_MODES::SHOWTIME_NONE || showtimeMode == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL) {} Timer::Timer(bool fileTotal, std::string filename) : mStr(std::move(filename)) , mStopped(!fileTotal) {} Timer::~Timer() { stop(); } void Timer::stop() { if ((mShowTimeMode != SHOWTIME_MODES::SHOWTIME_NONE) && !mStopped) { const std::clock_t end = std::clock(); const std::clock_t diff = end - mStart; if (mShowTimeMode == SHOWTIME_MODES::SHOWTIME_FILE) { const double sec = (double)diff / CLOCKS_PER_SEC; std::lock_guard<std::mutex> l(stdCoutLock); std::cout << mStr << ": " << sec << "s" << std::endl; } else if (mShowTimeMode == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL) { const double sec = (double)diff / CLOCKS_PER_SEC; std::lock_guard<std::mutex> l(stdCoutLock); std::cout << "Check time: " << mStr << ": " << sec << "s" << std::endl; } else { if (mTimerResults) mTimerResults->addResults(mStr, diff); } } mStopped = true; }
5,212
C++
.cpp
121
37.157025
154
0.65075
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,150
vf_impossiblevalues.cpp
danmar_cppcheck/lib/vf_impossiblevalues.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_impossiblevalues.h" #include "astutils.h" #include "calculate.h" #include "library.h" #include "mathlib.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "utils.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <algorithm> #include <array> #include <iterator> #include <list> #include <string> #include <utility> #include <vector> namespace ValueFlow { static std::vector<MathLib::bigint> minUnsignedValue(const Token* tok, int depth = 8) { std::vector<MathLib::bigint> result; if (!tok) return result; if (depth < 0) return result; if (tok->hasKnownIntValue()) { result = {tok->values().front().intvalue}; } else if (!Token::Match(tok, "-|%|&|^") && tok->isConstOp() && tok->astOperand1() && tok->astOperand2()) { std::vector<MathLib::bigint> op1 = minUnsignedValue(tok->astOperand1(), depth - 1); std::vector<MathLib::bigint> op2 = minUnsignedValue(tok->astOperand2(), depth - 1); if (!op1.empty() && !op2.empty()) { result = calculate<std::vector<MathLib::bigint>>(tok->str(), op1.front(), op2.front()); } } if (result.empty() && astIsUnsigned(tok)) result = {0}; return result; } static bool isSameToken(const Token* tok1, const Token* tok2) { if (!tok1 || !tok2) return false; if (tok1->exprId() != 0 && tok1->exprId() == tok2->exprId()) return true; if (tok1->hasKnownIntValue() && tok2->hasKnownIntValue()) return tok1->values().front().intvalue == tok2->values().front().intvalue; return false; } static bool isConvertedToIntegral(const Token* tok, const Settings& settings) { if (!tok) return false; std::vector<ValueType> parentTypes = getParentValueTypes(tok, settings); if (parentTypes.empty()) return false; const ValueType& vt = parentTypes.front(); return vt.type != ValueType::UNKNOWN_INT && vt.isIntegral(); } void analyzeImpossibleValues(TokenList& tokenList, const Settings& settings) { for (Token* tok = tokenList.front(); tok; tok = tok->next()) { if (tok->hasKnownIntValue()) continue; if (Token::Match(tok, "true|false")) continue; if (astIsBool(tok) || Token::Match(tok, "%comp%")) { Value lower{-1}; lower.bound = Value::Bound::Upper; lower.setImpossible(); setTokenValue(tok, std::move(lower), settings); Value upper{2}; upper.bound = Value::Bound::Lower; upper.setImpossible(); setTokenValue(tok, std::move(upper), settings); } else if (astIsUnsigned(tok) && !astIsPointer(tok)) { std::vector<MathLib::bigint> minvalue = minUnsignedValue(tok); if (minvalue.empty()) continue; Value value{std::max<MathLib::bigint>(0, minvalue.front()) - 1}; value.bound = Value::Bound::Upper; value.setImpossible(); setTokenValue(tok, std::move(value), settings); } if (Token::simpleMatch(tok, "?") && Token::Match(tok->astOperand1(), "<|<=|>|>=")) { const Token* condTok = tok->astOperand1(); const Token* branchesTok = tok->astOperand2(); auto tokens = makeArray(condTok->astOperand1(), condTok->astOperand2()); auto branches = makeArray(branchesTok->astOperand1(), branchesTok->astOperand2()); bool flipped = false; if (std::equal(tokens.cbegin(), tokens.cend(), branches.crbegin(), &isSameToken)) flipped = true; else if (!std::equal(tokens.cbegin(), tokens.cend(), branches.cbegin(), &isSameToken)) continue; const bool isMin = Token::Match(condTok, "<|<=") ^ flipped; std::vector<Value> values; for (const Token* tok2 : tokens) { if (tok2->hasKnownIntValue()) { values.emplace_back(tok2->values().front()); } else { Value symValue{}; symValue.valueType = Value::ValueType::SYMBOLIC; symValue.tokvalue = tok2; values.push_back(symValue); std::copy_if(tok2->values().cbegin(), tok2->values().cend(), std::back_inserter(values), [](const Value& v) { if (!v.isKnown()) return false; return v.isSymbolicValue(); }); } } for (Value& value : values) { value.setImpossible(); if (isMin) { value.intvalue++; value.bound = Value::Bound::Lower; } else { value.intvalue--; value.bound = Value::Bound::Upper; } setTokenValue(tok, std::move(value), settings); } } else if (Token::simpleMatch(tok, "%") && tok->astOperand2() && tok->astOperand2()->hasKnownIntValue()) { Value value{tok->astOperand2()->values().front()}; value.bound = Value::Bound::Lower; value.setImpossible(); setTokenValue(tok, std::move(value), settings); } else if (Token::Match(tok, "abs|labs|llabs|fabs|fabsf|fabsl (")) { Value value{-1}; value.bound = Value::Bound::Upper; value.setImpossible(); setTokenValue(tok->next(), std::move(value), settings); } else if (Token::Match(tok, ". data|c_str (") && astIsContainerOwned(tok->astOperand1())) { const Library::Container* container = getLibraryContainer(tok->astOperand1()); if (!container) continue; if (!container->stdStringLike) continue; if (container->view) continue; Value value{0}; value.setImpossible(); setTokenValue(tok->tokAt(2), std::move(value), settings); } else if (Token::Match(tok, "make_shared|make_unique <") && Token::simpleMatch(tok->linkAt(1), "> (")) { Value value{0}; value.setImpossible(); setTokenValue(tok->linkAt(1)->next(), std::move(value), settings); } else if ((tokenList.isCPP() && Token::simpleMatch(tok, "this")) || tok->isUnaryOp("&")) { Value value{0}; value.setImpossible(); setTokenValue(tok, std::move(value), settings); } else if (tok->variable() && tok->variable()->isArray() && !tok->variable()->isArgument() && !tok->variable()->isStlType()) { Value value{0}; value.setImpossible(); setTokenValue(tok, std::move(value), settings); } else if (tok->isIncompleteVar() && tok->astParent() && tok->astParent()->isUnaryOp("-") && isConvertedToIntegral(tok->astParent(), settings)) { Value value{0}; value.setImpossible(); setTokenValue(tok, std::move(value), settings); } } } }
8,585
C++
.cpp
186
33.048387
118
0.531593
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,152
suppressions.cpp
danmar_cppcheck/lib/suppressions.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "suppressions.h" #include "errorlogger.h" #include "errortypes.h" #include "filesettings.h" #include "path.h" #include "utils.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include <algorithm> #include <cctype> // std::isdigit, std::isalnum, etc #include <cstring> #include <functional> // std::bind, std::placeholders #include <sstream> #include <utility> #include "xml.h" static const char ID_UNUSEDFUNCTION[] = "unusedFunction"; static const char ID_CHECKERSREPORT[] = "checkersReport"; SuppressionList::ErrorMessage SuppressionList::ErrorMessage::fromErrorMessage(const ::ErrorMessage &msg, const std::set<std::string> &macroNames) { SuppressionList::ErrorMessage ret; ret.hash = msg.hash; ret.errorId = msg.id; if (!msg.callStack.empty()) { ret.setFileName(msg.callStack.back().getfile(false)); ret.lineNumber = msg.callStack.back().line; } else { ret.lineNumber = SuppressionList::Suppression::NO_LINE; } ret.certainty = msg.certainty; ret.symbolNames = msg.symbolNames(); ret.macroNames = macroNames; return ret; } static bool isAcceptedErrorIdChar(char c) { switch (c) { case '_': case '-': case '.': case '*': return true; default: return c > 0 && std::isalnum(c); } } std::string SuppressionList::parseFile(std::istream &istr) { // Change '\r' to '\n' in the istr std::string filedata; std::string line; while (std::getline(istr, line)) filedata += line + "\n"; std::replace(filedata.begin(), filedata.end(), '\r', '\n'); // Parse filedata.. std::istringstream istr2(filedata); while (std::getline(istr2, line)) { // Skip empty lines if (line.empty()) continue; std::string::size_type pos = 0; while (pos < line.size() && std::isspace(line[pos])) ++pos; if (pos == line.size()) continue; // Skip comments if (line[pos] == '#') continue; if (pos < line.size() - 1 && line[pos] == '/' && line[pos + 1] == '/') continue; const std::string errmsg(addSuppressionLine(line)); if (!errmsg.empty()) return errmsg; } return ""; } std::string SuppressionList::parseXmlFile(const char *filename) { tinyxml2::XMLDocument doc; const tinyxml2::XMLError error = doc.LoadFile(filename); if (error != tinyxml2::XML_SUCCESS) return std::string("failed to load suppressions XML '") + filename + "' (" + tinyxml2::XMLDocument::ErrorIDToName(error) + ")."; const tinyxml2::XMLElement * const rootnode = doc.FirstChildElement(); if (!rootnode) return std::string("failed to load suppressions XML '") + filename + "' (no root node found)."; // TODO: check for proper root node 'suppressions' for (const tinyxml2::XMLElement * e = rootnode->FirstChildElement(); e; e = e->NextSiblingElement()) { if (std::strcmp(e->Name(), "suppress") != 0) return std::string("invalid suppression xml file '") + filename + "', expected 'suppress' element but got a '" + e->Name() + "'."; Suppression s; for (const tinyxml2::XMLElement * e2 = e->FirstChildElement(); e2; e2 = e2->NextSiblingElement()) { const char *name = e2->Name(); const char *text = empty_if_null(e2->GetText()); if (std::strcmp(name, "id") == 0) s.errorId = text; else if (std::strcmp(name, "fileName") == 0) s.fileName = text; else if (std::strcmp(name, "lineNumber") == 0) s.lineNumber = strToInt<int>(text); else if (std::strcmp(name, "symbolName") == 0) s.symbolName = text; else if (*text && std::strcmp(name, "hash") == 0) s.hash = strToInt<std::size_t>(text); else return std::string("unknown element '") + name + "' in suppressions XML '" + filename + "', expected id/fileName/lineNumber/symbolName/hash."; } const std::string err = addSuppression(std::move(s)); if (!err.empty()) return err; } return ""; } std::vector<SuppressionList::Suppression> SuppressionList::parseMultiSuppressComment(const std::string &comment, std::string *errorMessage) { std::vector<Suppression> suppressions; // If this function is called we assume that comment starts with "cppcheck-suppress[". const std::string::size_type start_position = comment.find('['); const std::string::size_type end_position = comment.find(']', start_position); if (end_position == std::string::npos) { if (errorMessage && errorMessage->empty()) *errorMessage = "Bad multi suppression '" + comment + "'. legal format is cppcheck-suppress[errorId, errorId symbolName=arr, ...]"; return suppressions; } // parse all suppressions for (std::string::size_type pos = start_position; pos < end_position;) { const std::string::size_type pos1 = pos + 1; pos = comment.find(',', pos1); const std::string::size_type pos2 = (pos < end_position) ? pos : end_position; if (pos1 == pos2) continue; Suppression s; std::istringstream iss(comment.substr(pos1, pos2-pos1)); iss >> s.errorId; if (!iss) { if (errorMessage && errorMessage->empty()) *errorMessage = "Bad multi suppression '" + comment + "'. legal format is cppcheck-suppress[errorId, errorId symbolName=arr, ...]"; suppressions.clear(); return suppressions; } const std::string symbolNameString = "symbolName="; while (iss) { std::string word; iss >> word; if (!iss) break; if (word.find_first_not_of("+-*/%#;") == std::string::npos) break; if (startsWith(word, symbolNameString)) { s.symbolName = word.substr(symbolNameString.size()); } else { if (errorMessage && errorMessage->empty()) *errorMessage = "Bad multi suppression '" + comment + "'. legal format is cppcheck-suppress[errorId, errorId symbolName=arr, ...]"; suppressions.clear(); return suppressions; } } suppressions.push_back(std::move(s)); } return suppressions; } std::string SuppressionList::addSuppressionLine(const std::string &line) { std::istringstream lineStream; SuppressionList::Suppression suppression; // Strip any end of line comments std::string::size_type endpos = std::min(line.find('#'), line.find("//")); if (endpos != std::string::npos) { while (endpos > 0 && std::isspace(line[endpos-1])) { endpos--; } lineStream.str(line.substr(0, endpos)); } else { lineStream.str(line); } if (std::getline(lineStream, suppression.errorId, ':')) { if (std::getline(lineStream, suppression.fileName)) { // If there is not a dot after the last colon in "file" then // the colon is a separator and the contents after the colon // is a line number.. // Get position of last colon const std::string::size_type pos = suppression.fileName.rfind(':'); // if a colon is found and there is no dot after it.. if (pos != std::string::npos && suppression.fileName.find('.', pos) == std::string::npos) { // Try to parse out the line number try { std::istringstream istr1(suppression.fileName.substr(pos+1)); istr1 >> suppression.lineNumber; } catch (...) { suppression.lineNumber = SuppressionList::Suppression::NO_LINE; } if (suppression.lineNumber != SuppressionList::Suppression::NO_LINE) { suppression.fileName.erase(pos); } } } } suppression.fileName = Path::simplifyPath(suppression.fileName); return addSuppression(std::move(suppression)); } std::string SuppressionList::addSuppression(SuppressionList::Suppression suppression) { // Check if suppression is already in list auto foundSuppression = std::find_if(mSuppressions.begin(), mSuppressions.end(), std::bind(&Suppression::isSameParameters, &suppression, std::placeholders::_1)); if (foundSuppression != mSuppressions.end()) { // Update matched state of existing global suppression if (!suppression.isLocal() && suppression.matched) foundSuppression->matched = suppression.matched; return ""; } // Check that errorId is valid.. if (suppression.errorId.empty() && suppression.hash == 0) return "Failed to add suppression. No id."; for (std::string::size_type pos = 0; pos < suppression.errorId.length(); ++pos) { if (!isAcceptedErrorIdChar(suppression.errorId[pos])) { return "Failed to add suppression. Invalid id \"" + suppression.errorId + "\""; } if (pos == 0 && std::isdigit(suppression.errorId[pos])) { return "Failed to add suppression. Invalid id \"" + suppression.errorId + "\""; } } if (!isValidGlobPattern(suppression.errorId)) return "Failed to add suppression. Invalid glob pattern '" + suppression.errorId + "'."; if (!isValidGlobPattern(suppression.fileName)) return "Failed to add suppression. Invalid glob pattern '" + suppression.fileName + "'."; mSuppressions.push_back(std::move(suppression)); return ""; } std::string SuppressionList::addSuppressions(std::list<Suppression> suppressions) { for (auto &newSuppression : suppressions) { auto errmsg = addSuppression(std::move(newSuppression)); if (!errmsg.empty()) return errmsg; } return ""; } void SuppressionList::ErrorMessage::setFileName(std::string s) { mFileName = Path::simplifyPath(std::move(s)); } bool SuppressionList::Suppression::parseComment(std::string comment, std::string *errorMessage) { if (comment.size() < 2) return false; if (comment.find(';') != std::string::npos) comment.erase(comment.find(';')); if (comment.find("//", 2) != std::string::npos) comment.erase(comment.find("//",2)); if (comment.compare(comment.size() - 2, 2, "*/") == 0) comment.erase(comment.size() - 2, 2); const std::set<std::string> cppchecksuppress{ "cppcheck-suppress", "cppcheck-suppress-begin", "cppcheck-suppress-end", "cppcheck-suppress-file", "cppcheck-suppress-macro" }; std::istringstream iss(comment.substr(2)); std::string word; iss >> word; if (!cppchecksuppress.count(word)) return false; iss >> errorId; if (!iss) return false; const std::string symbolNameString = "symbolName="; while (iss) { iss >> word; if (!iss) break; if (word.find_first_not_of("+-*/%#;") == std::string::npos) break; if (startsWith(word, symbolNameString)) symbolName = word.substr(symbolNameString.size()); else if (errorMessage && errorMessage->empty()) *errorMessage = "Bad suppression attribute '" + word + "'. You can write comments in the comment after a ; or //. Valid suppression attributes; symbolName=sym"; } return true; } bool SuppressionList::Suppression::isSuppressed(const SuppressionList::ErrorMessage &errmsg) const { if (hash > 0 && hash != errmsg.hash) return false; if (!errorId.empty() && !matchglob(errorId, errmsg.errorId)) return false; if (type == SuppressionList::Type::macro) { if (errmsg.macroNames.count(macroName) == 0) return false; } else { if (!fileName.empty() && !matchglob(fileName, errmsg.getFileName())) return false; if ((SuppressionList::Type::unique == type) && (lineNumber != NO_LINE) && (lineNumber != errmsg.lineNumber)) { if (!thisAndNextLine || lineNumber + 1 != errmsg.lineNumber) return false; } if ((SuppressionList::Type::block == type) && ((errmsg.lineNumber < lineBegin) || (errmsg.lineNumber > lineEnd))) return false; } if (!symbolName.empty()) { for (std::string::size_type pos = 0; pos < errmsg.symbolNames.size();) { const std::string::size_type pos2 = errmsg.symbolNames.find('\n',pos); std::string symname; if (pos2 == std::string::npos) { symname = errmsg.symbolNames.substr(pos); pos = pos2; } else { symname = errmsg.symbolNames.substr(pos,pos2-pos); pos = pos2+1; } if (matchglob(symbolName, symname)) return true; } return false; } return true; } bool SuppressionList::Suppression::isMatch(const SuppressionList::ErrorMessage &errmsg) { if (!isSuppressed(errmsg)) return false; matched = true; checked = true; return true; } // cppcheck-suppress unusedFunction - used by GUI only std::string SuppressionList::Suppression::getText() const { std::string ret; if (!errorId.empty()) ret = errorId; if (!fileName.empty()) ret += " fileName=" + fileName; if (lineNumber != NO_LINE) ret += " lineNumber=" + std::to_string(lineNumber); if (!symbolName.empty()) ret += " symbolName=" + symbolName; if (hash > 0) ret += " hash=" + std::to_string(hash); if (startsWith(ret," ")) return ret.substr(1); return ret; } bool SuppressionList::isSuppressed(const SuppressionList::ErrorMessage &errmsg, bool global) { const bool unmatchedSuppression(errmsg.errorId == "unmatchedSuppression"); bool returnValue = false; for (Suppression &s : mSuppressions) { if (!global && !s.isLocal()) continue; if (unmatchedSuppression && s.errorId != errmsg.errorId) continue; if (s.isMatch(errmsg)) returnValue = true; } return returnValue; } bool SuppressionList::isSuppressedExplicitly(const SuppressionList::ErrorMessage &errmsg, bool global) { for (Suppression &s : mSuppressions) { if (!global && !s.isLocal()) continue; if (s.errorId != errmsg.errorId) // Error id must match exactly continue; if (s.isMatch(errmsg)) return true; } return false; } bool SuppressionList::isSuppressed(const ::ErrorMessage &errmsg, const std::set<std::string>& macroNames) { if (mSuppressions.empty()) return false; return isSuppressed(SuppressionList::ErrorMessage::fromErrorMessage(errmsg, macroNames)); } void SuppressionList::dump(std::ostream & out) const { out << " <suppressions>" << std::endl; for (const Suppression &suppression : mSuppressions) { out << " <suppression"; out << " errorId=\"" << ErrorLogger::toxml(suppression.errorId) << '"'; if (!suppression.fileName.empty()) out << " fileName=\"" << ErrorLogger::toxml(suppression.fileName) << '"'; if (suppression.lineNumber != Suppression::NO_LINE) out << " lineNumber=\"" << suppression.lineNumber << '"'; if (!suppression.symbolName.empty()) out << " symbolName=\"" << ErrorLogger::toxml(suppression.symbolName) << '\"'; if (suppression.hash > 0) out << " hash=\"" << suppression.hash << '\"'; if (suppression.lineBegin != Suppression::NO_LINE) out << " lineBegin=\"" << suppression.lineBegin << '"'; if (suppression.lineEnd != Suppression::NO_LINE) out << " lineEnd=\"" << suppression.lineEnd << '"'; if (suppression.type == SuppressionList::Type::file) out << " type=\"file\""; else if (suppression.type == SuppressionList::Type::block) out << " type=\"block\""; else if (suppression.type == SuppressionList::Type::blockBegin) out << " type=\"blockBegin\""; else if (suppression.type == SuppressionList::Type::blockEnd) out << " type=\"blockEnd\""; else if (suppression.type == SuppressionList::Type::macro) out << " type=\"macro\""; out << " />" << std::endl; } out << " </suppressions>" << std::endl; } std::list<SuppressionList::Suppression> SuppressionList::getUnmatchedLocalSuppressions(const FileWithDetails &file, const bool unusedFunctionChecking) const { std::list<Suppression> result; for (const Suppression &s : mSuppressions) { if (s.matched || ((s.lineNumber != Suppression::NO_LINE) && !s.checked)) continue; if (s.type == SuppressionList::Type::macro) continue; if (s.hash > 0) continue; if (s.errorId == ID_CHECKERSREPORT) continue; if (!unusedFunctionChecking && s.errorId == ID_UNUSEDFUNCTION) continue; if (!s.isLocal() || s.fileName != file.spath()) continue; result.push_back(s); } return result; } std::list<SuppressionList::Suppression> SuppressionList::getUnmatchedGlobalSuppressions(const bool unusedFunctionChecking) const { std::list<Suppression> result; for (const Suppression &s : mSuppressions) { if (s.matched || ((s.lineNumber != Suppression::NO_LINE) && !s.checked)) continue; if (s.hash > 0) continue; if (!unusedFunctionChecking && s.errorId == ID_UNUSEDFUNCTION) continue; if (s.errorId == ID_CHECKERSREPORT) continue; if (s.isLocal()) continue; result.push_back(s); } return result; } const std::list<SuppressionList::Suppression> &SuppressionList::getSuppressions() const { return mSuppressions; } void SuppressionList::markUnmatchedInlineSuppressionsAsChecked(const Tokenizer &tokenizer) { int currLineNr = -1; int currFileIdx = -1; for (const Token *tok = tokenizer.tokens(); tok; tok = tok->next()) { if (currFileIdx != tok->fileIndex() || currLineNr != tok->linenr()) { currLineNr = tok->linenr(); currFileIdx = tok->fileIndex(); for (auto &suppression : mSuppressions) { if (suppression.type == SuppressionList::Type::unique) { if (!suppression.checked && (suppression.lineNumber == currLineNr) && (suppression.fileName == tokenizer.list.file(tok))) { suppression.checked = true; } } else if (suppression.type == SuppressionList::Type::block) { if ((!suppression.checked && (suppression.lineBegin <= currLineNr) && (suppression.lineEnd >= currLineNr) && (suppression.fileName == tokenizer.list.file(tok)))) { suppression.checked = true; } } else if (!suppression.checked && suppression.fileName == tokenizer.list.file(tok)) { suppression.checked = true; } } } } } bool SuppressionList::reportUnmatchedSuppressions(const std::list<SuppressionList::Suppression> &unmatched, ErrorLogger &errorLogger) { bool err = false; // Report unmatched suppressions for (const SuppressionList::Suppression &s : unmatched) { // don't report "unmatchedSuppression" as unmatched if (s.errorId == "unmatchedSuppression") continue; // check if this unmatched suppression is suppressed bool suppressed = false; for (const SuppressionList::Suppression &s2 : unmatched) { if (s2.errorId == "unmatchedSuppression") { if ((s2.fileName.empty() || s2.fileName == "*" || s2.fileName == s.fileName) && (s2.lineNumber == SuppressionList::Suppression::NO_LINE || s2.lineNumber == s.lineNumber)) { suppressed = true; break; } } } if (suppressed) continue; std::list<::ErrorMessage::FileLocation> callStack; if (!s.fileName.empty()) callStack.emplace_back(s.fileName, s.lineNumber, 0); errorLogger.reportErr(::ErrorMessage(std::move(callStack), emptyString, Severity::information, "Unmatched suppression: " + s.errorId, "unmatchedSuppression", Certainty::normal)); err = true; } return err; }
21,592
C++
.cpp
519
33.456647
186
0.608331
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,153
vf_string.cpp
danmar_cppcheck/lib/vf_string.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_string.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <utility> namespace ValueFlow { void analyzeString(TokenList &tokenlist, const Settings& settings) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (tok->tokType() == Token::eString) { Value strvalue; strvalue.valueType = Value::ValueType::TOK; strvalue.tokvalue = tok; strvalue.setKnown(); setTokenValue(tok, std::move(strvalue), settings); } } } }
1,381
C++
.cpp
38
31.315789
72
0.677877
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,155
checkbool.cpp
danmar_cppcheck/lib/checkbool.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkbool.h" #include "astutils.h" #include "errortypes.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "vfvalue.h" #include <list> #include <vector> //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckBool instance; } static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE571(571U); // Expression is Always True static const CWE CWE587(587U); // Assignment of a Fixed Address to a Pointer static const CWE CWE704(704U); // Incorrect Type Conversion or Cast static bool isBool(const Variable* var) { return (var && Token::Match(var->typeEndToken(), "bool|_Bool")); } //--------------------------------------------------------------------------- void CheckBool::checkIncrementBoolean() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("incrementboolean")) return; logChecker("CheckBool::checkIncrementBoolean"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (astIsBool(tok) && tok->astParent() && tok->astParent()->str() == "++") { incrementBooleanError(tok); } } } } void CheckBool::incrementBooleanError(const Token *tok) { reportError( tok, Severity::style, "incrementboolean", "Incrementing a variable of type 'bool' with postfix operator++ is deprecated by the C++ Standard. You should assign it the value 'true' instead.\n" "The operand of a postfix increment operator may be of type bool but it is deprecated by C++ Standard (Annex D-1) and the operand is always set to true. You should assign it the value 'true' instead.", CWE398, Certainty::normal ); } static bool isConvertedToBool(const Token* tok) { if (!tok->astParent()) return false; return astIsBool(tok->astParent()) || Token::Match(tok->astParent()->previous(), "if|while ("); } //--------------------------------------------------------------------------- // if (bool & bool) -> if (bool && bool) // if (bool | bool) -> if (bool || bool) //--------------------------------------------------------------------------- void CheckBool::checkBitwiseOnBoolean() { if (!mSettings->severity.isEnabled(Severity::style)) return; // danmar: this is inconclusive because I don't like that there are // warnings for calculations. Example: set_flag(a & b); if (!mSettings->certainty.isEnabled(Certainty::inconclusive)) return; logChecker("CheckBool::checkBitwiseOnBoolean"); // style,inconclusive const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (tok->isBinaryOp()) { bool isCompound{}; if (tok->str() == "&" || tok->str() == "|") isCompound = false; else if (tok->str() == "&=" || tok->str() == "|=") isCompound = true; else continue; const bool isBoolOp1 = astIsBool(tok->astOperand1()); const bool isBoolOp2 = astIsBool(tok->astOperand2()); if (!tok->astOperand1()->valueType() || !tok->astOperand2()->valueType()) continue; if (!(isBoolOp1 || isBoolOp2)) continue; if (isCompound && (!isBoolOp1 || isBoolOp2)) continue; if (tok->str() == "|" && !isConvertedToBool(tok) && !(isBoolOp1 && isBoolOp2)) continue; // first operand will always be evaluated if (!isConstExpression(tok->astOperand2(), mSettings->library)) continue; if (tok->astOperand2()->variable() && tok->astOperand2()->variable()->nameToken() == tok->astOperand2()) continue; const std::string expression = (isBoolOp1 ? tok->astOperand1() : tok->astOperand2())->expressionString(); bitwiseOnBooleanError(tok, expression, tok->str() == "&" ? "&&" : "||", isCompound); } } } } void CheckBool::bitwiseOnBooleanError(const Token* tok, const std::string& expression, const std::string& op, bool isCompound) { std::string msg = "Boolean expression '" + expression + "' is used in bitwise operation."; if (!isCompound) msg += " Did you mean '" + op + "'?"; reportError(tok, Severity::style, "bitwiseOnBoolean", msg, CWE398, Certainty::inconclusive); } //--------------------------------------------------------------------------- // if (!x==3) <- Probably meant to be "x!=3" //--------------------------------------------------------------------------- void CheckBool::checkComparisonOfBoolWithInt() { if (!mSettings->severity.isEnabled(Severity::warning) || !mTokenizer->isCPP()) return; logChecker("CheckBool::checkComparisonOfBoolWithInt"); // warning,c++ const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp() || !tok->isBinaryOp()) continue; const Token* const left = tok->astOperand1(); const Token* const right = tok->astOperand2(); if (left->isBoolean() && right->varId()) { // Comparing boolean constant with variable if (tok->str() != "==" && tok->str() != "!=") { comparisonOfBoolWithInvalidComparator(right, left->str()); } } else if (left->varId() && right->isBoolean()) { // Comparing variable with boolean constant if (tok->str() != "==" && tok->str() != "!=") { comparisonOfBoolWithInvalidComparator(right, left->str()); } } } } } void CheckBool::comparisonOfBoolWithInvalidComparator(const Token *tok, const std::string &expression) { reportError(tok, Severity::warning, "comparisonOfBoolWithInvalidComparator", "Comparison of a boolean value using relational operator (<, >, <= or >=).\n" "The result of the expression '" + expression + "' is of type 'bool'. " "Comparing 'bool' value using relational (<, >, <= or >=)" " operator could cause unexpected results."); } //------------------------------------------------------------------------------- // Comparing functions which are returning value of type bool //------------------------------------------------------------------------------- static bool tokenIsFunctionReturningBool(const Token* tok) { const Function* func = tok ? tok->function() : nullptr; if (func && Token::Match(tok, "%name% (")) { if (func->tokenDef && Token::Match(func->tokenDef->previous(), "bool|_Bool")) { return true; } } return false; } void CheckBool::checkComparisonOfFuncReturningBool() { if (!mSettings->severity.isEnabled(Severity::style)) return; if (!mTokenizer->isCPP()) return; logChecker("CheckBool::checkComparisonOfFuncReturningBool"); // style,c++ const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase(); auto getFunctionTok = [](const Token* tok) -> const Token* { while (Token::simpleMatch(tok, "!") || (tok && tok->isCast() && !isCPPCast(tok))) tok = tok->astOperand1(); if (isCPPCast(tok)) tok = tok->astOperand2(); if (tok) return tok->previous(); return nullptr; }; for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp() || tok->str() == "==" || tok->str() == "!=") continue; const Token* firstToken = getFunctionTok(tok->astOperand1()); const Token* secondToken = getFunctionTok(tok->astOperand2()); if (!firstToken || !secondToken) continue; const bool firstIsFunctionReturningBool = tokenIsFunctionReturningBool(firstToken); const bool secondIsFunctionReturningBool = tokenIsFunctionReturningBool(secondToken); if (firstIsFunctionReturningBool && secondIsFunctionReturningBool) { comparisonOfTwoFuncsReturningBoolError(firstToken->next(), firstToken->str(), secondToken->str()); } else if (firstIsFunctionReturningBool) { comparisonOfFuncReturningBoolError(firstToken->next(), firstToken->str()); } else if (secondIsFunctionReturningBool) { comparisonOfFuncReturningBoolError(secondToken->previous(), secondToken->str()); } } } } void CheckBool::comparisonOfFuncReturningBoolError(const Token *tok, const std::string &expression) { reportError(tok, Severity::style, "comparisonOfFuncReturningBoolError", "Comparison of a function returning boolean value using relational (<, >, <= or >=) operator.\n" "The return type of function '" + expression + "' is 'bool' " "and result is of type 'bool'. Comparing 'bool' value using relational (<, >, <= or >=)" " operator could cause unexpected results.", CWE398, Certainty::normal); } void CheckBool::comparisonOfTwoFuncsReturningBoolError(const Token *tok, const std::string &expression1, const std::string &expression2) { reportError(tok, Severity::style, "comparisonOfTwoFuncsReturningBoolError", "Comparison of two functions returning boolean value using relational (<, >, <= or >=) operator.\n" "The return type of function '" + expression1 + "' and function '" + expression2 + "' is 'bool' " "and result is of type 'bool'. Comparing 'bool' value using relational (<, >, <= or >=)" " operator could cause unexpected results.", CWE398, Certainty::normal); } //------------------------------------------------------------------------------- // Comparison of bool with bool //------------------------------------------------------------------------------- void CheckBool::checkComparisonOfBoolWithBool() { if (!mSettings->severity.isEnabled(Severity::style)) return; if (!mTokenizer->isCPP()) return; logChecker("CheckBool::checkComparisonOfBoolWithBool"); // style,c++ const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp() || tok->str() == "==" || tok->str() == "!=") continue; bool firstTokenBool = false; const Token *firstToken = tok->previous(); if (firstToken->varId()) { if (isBool(firstToken->variable())) { firstTokenBool = true; } } if (!firstTokenBool) continue; bool secondTokenBool = false; const Token *secondToken = tok->next(); if (secondToken->varId()) { if (isBool(secondToken->variable())) { secondTokenBool = true; } } if (secondTokenBool) { comparisonOfBoolWithBoolError(firstToken->next(), secondToken->str()); } } } } void CheckBool::comparisonOfBoolWithBoolError(const Token *tok, const std::string &expression) { reportError(tok, Severity::style, "comparisonOfBoolWithBoolError", "Comparison of a variable having boolean value using relational (<, >, <= or >=) operator.\n" "The variable '" + expression + "' is of type 'bool' " "and comparing 'bool' value using relational (<, >, <= or >=)" " operator could cause unexpected results.", CWE398, Certainty::normal); } //----------------------------------------------------------------------------- void CheckBool::checkAssignBoolToPointer() { logChecker("CheckBool::checkAssignBoolToPointer"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() == "=" && astIsPointer(tok->astOperand1()) && astIsBool(tok->astOperand2())) { assignBoolToPointerError(tok); } } } } void CheckBool::assignBoolToPointerError(const Token *tok) { reportError(tok, Severity::error, "assignBoolToPointer", "Boolean value assigned to pointer.", CWE587, Certainty::normal); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void CheckBool::checkComparisonOfBoolExpressionWithInt() { if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("compareBoolExpressionWithInt")) return; logChecker("CheckBool::checkComparisonOfBoolExpressionWithInt"); // warning const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp()) continue; const Token* numTok = nullptr; const Token* boolExpr = nullptr; bool numInRhs; if (astIsBool(tok->astOperand1())) { boolExpr = tok->astOperand1(); numTok = tok->astOperand2(); numInRhs = true; } else if (astIsBool(tok->astOperand2())) { boolExpr = tok->astOperand2(); numTok = tok->astOperand1(); numInRhs = false; } else { continue; } if (!numTok || !boolExpr) continue; if (boolExpr->isOp() && numTok->isName() && Token::Match(tok, "==|!=")) // there is weird code such as: ((a<b)==c) // but it is probably written this way by design. continue; if (astIsBool(numTok)) continue; const ValueFlow::Value *minval = numTok->getValueLE(0, *mSettings); if (minval && minval->intvalue == 0 && (numInRhs ? Token::Match(tok, ">|==|!=") : Token::Match(tok, "<|==|!="))) minval = nullptr; const ValueFlow::Value *maxval = numTok->getValueGE(1, *mSettings); if (maxval && maxval->intvalue == 1 && (numInRhs ? Token::Match(tok, "<|==|!=") : Token::Match(tok, ">|==|!="))) maxval = nullptr; if (minval || maxval) { const bool not0or1 = (minval && minval->intvalue < 0) || (maxval && maxval->intvalue > 1); comparisonOfBoolExpressionWithIntError(tok, not0or1); } } } } void CheckBool::comparisonOfBoolExpressionWithIntError(const Token *tok, bool not0or1) { if (not0or1) reportError(tok, Severity::warning, "compareBoolExpressionWithInt", "Comparison of a boolean expression with an integer other than 0 or 1.", CWE398, Certainty::normal); else reportError(tok, Severity::warning, "compareBoolExpressionWithInt", "Comparison of a boolean expression with an integer.", CWE398, Certainty::normal); } void CheckBool::pointerArithBool() { logChecker("CheckBool::pointerArithBool"); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eIf && !scope.isLoopScope()) continue; const Token* tok = scope.classDef->next()->astOperand2(); if (scope.type == Scope::eFor) { tok = Token::findsimplematch(scope.classDef->tokAt(2), ";"); if (tok) tok = tok->astOperand2(); if (tok) tok = tok->astOperand1(); } else if (scope.type == Scope::eDo) tok = (scope.bodyEnd->tokAt(2)) ? scope.bodyEnd->tokAt(2)->astOperand2() : nullptr; pointerArithBoolCond(tok); } } void CheckBool::pointerArithBoolCond(const Token *tok) { if (!tok) return; if (Token::Match(tok, "&&|%oror%")) { pointerArithBoolCond(tok->astOperand1()); pointerArithBoolCond(tok->astOperand2()); return; } if (tok->str() != "+" && tok->str() != "-") return; if (tok->isBinaryOp() && tok->astOperand1()->isName() && tok->astOperand1()->variable() && tok->astOperand1()->variable()->isPointer() && tok->astOperand2()->isNumber()) pointerArithBoolError(tok); } void CheckBool::pointerArithBoolError(const Token *tok) { reportError(tok, Severity::error, "pointerArithBool", "Converting pointer arithmetic result to bool. The bool is always true unless there is undefined behaviour.\n" "Converting pointer arithmetic result to bool. The boolean result is always true unless there is pointer arithmetic overflow, and overflow is undefined behaviour. Probably a dereference is forgotten.", CWE571, Certainty::normal); } void CheckBool::checkAssignBoolToFloat() { if (!mTokenizer->isCPP()) return; if (!mSettings->severity.isEnabled(Severity::style)) return; logChecker("CheckBool::checkAssignBoolToFloat"); // style,c++ const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() == "=" && astIsFloat(tok->astOperand1(), false) && astIsBool(tok->astOperand2())) { assignBoolToFloatError(tok); } } } } void CheckBool::assignBoolToFloatError(const Token *tok) { reportError(tok, Severity::style, "assignBoolToFloat", "Boolean value assigned to floating point variable.", CWE704, Certainty::normal); } void CheckBool::returnValueOfFunctionReturningBool() { if (!mSettings->severity.isEnabled(Severity::style)) return; logChecker("CheckBool::returnValueOfFunctionReturningBool"); // style const SymbolDatabase * const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { if (!(scope->function && Token::Match(scope->function->retDef, "bool|_Bool"))) continue; for (const Token* tok = scope->bodyStart->next(); tok && (tok != scope->bodyEnd); tok = tok->next()) { // Skip lambdas const Token* tok2 = findLambdaEndToken(tok); if (tok2) tok = tok2; else if (tok->scope() && tok->scope()->isClassOrStruct()) tok = tok->scope()->bodyEnd; else if (Token::simpleMatch(tok, "return") && tok->astOperand1() && (tok->astOperand1()->getValueGE(2, *mSettings) || tok->astOperand1()->getValueLE(-1, *mSettings)) && !(tok->astOperand1()->astOperand1() && Token::Match(tok->astOperand1(), "&|%or%"))) returnValueBoolError(tok); } } } void CheckBool::returnValueBoolError(const Token *tok) { reportError(tok, Severity::style, "returnNonBoolInBooleanFunction", "Non-boolean value returned from function returning bool"); }
21,479
C++
.cpp
447
39.239374
245
0.580153
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,156
checkstring.cpp
danmar_cppcheck/lib/checkstring.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkstring.h" #include "astutils.h" #include "errortypes.h" #include "mathlib.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "utils.h" #include <cstddef> #include <list> #include <vector> #include <utility> //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckString instance; } // CWE ids used: static const CWE CWE570(570U); // Expression is Always False static const CWE CWE571(571U); // Expression is Always True static const CWE CWE595(595U); // Comparison of Object References Instead of Object Contents static const CWE CWE628(628U); // Function Call with Incorrectly Specified Arguments static const CWE CWE665(665U); // Improper Initialization static const CWE CWE758(758U); // Reliance on Undefined, Unspecified, or Implementation-Defined Behavior //--------------------------------------------------------------------------- // Writing string literal is UB //--------------------------------------------------------------------------- void CheckString::stringLiteralWrite() { logChecker("CheckString::stringLiteralWrite"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->variable() || !tok->variable()->isPointer()) continue; const Token *str = tok->getValueTokenMinStrSize(*mSettings); if (!str) continue; if (Token::Match(tok, "%var% [") && Token::simpleMatch(tok->linkAt(1), "] =")) stringLiteralWriteError(tok, str); else if (Token::Match(tok->previous(), "* %var% =")) stringLiteralWriteError(tok, str); } } } void CheckString::stringLiteralWriteError(const Token *tok, const Token *strValue) { std::list<const Token*> callstack{ tok }; if (strValue) callstack.push_back(strValue); std::string errmsg("Modifying string literal"); if (strValue) { std::string s = strValue->str(); // 20 is an arbitrary value, the max string length shown in a warning message if (s.size() > 20U) s.replace(17, std::string::npos, "..\""); errmsg += " " + s; } errmsg += " directly or indirectly is undefined behaviour."; reportError(callstack, Severity::error, "stringLiteralWrite", errmsg, CWE758, Certainty::normal); } //--------------------------------------------------------------------------- // Check for string comparison involving two static strings. // if(strcmp("00FF00","00FF00")==0) // <- statement is always true //--------------------------------------------------------------------------- void CheckString::checkAlwaysTrueOrFalseStringCompare() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckString::checkAlwaysTrueOrFalseStringCompare"); // warning for (const Token* tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (tok->isName() && tok->strAt(1) == "(" && Token::Match(tok, "memcmp|strncmp|strcmp|stricmp|strverscmp|bcmp|strcmpi|strcasecmp|strncasecmp|strncasecmp_l|strcasecmp_l|wcsncasecmp|wcscasecmp|wmemcmp|wcscmp|wcscasecmp_l|wcsncasecmp_l|wcsncmp|_mbscmp|_mbscmp_l|_memicmp|_memicmp_l|_stricmp|_wcsicmp|_mbsicmp|_stricmp_l|_wcsicmp_l|_mbsicmp_l")) { if (Token::Match(tok->tokAt(2), "%str% , %str% ,|)")) { const std::string &str1 = tok->strAt(2); const std::string &str2 = tok->strAt(4); if (!tok->isExpandedMacro() && !tok->tokAt(2)->isExpandedMacro() && !tok->tokAt(4)->isExpandedMacro()) alwaysTrueFalseStringCompareError(tok, str1, str2); tok = tok->tokAt(5); } else if (Token::Match(tok->tokAt(2), "%name% , %name% ,|)")) { const std::string &str1 = tok->strAt(2); const std::string &str2 = tok->strAt(4); if (str1 == str2) alwaysTrueStringVariableCompareError(tok, str1, str2); tok = tok->tokAt(5); } else if (Token::Match(tok->tokAt(2), "%name% . c_str ( ) , %name% . c_str ( ) ,|)")) { const std::string &str1 = tok->strAt(2); const std::string &str2 = tok->strAt(8); if (str1 == str2) alwaysTrueStringVariableCompareError(tok, str1, str2); tok = tok->tokAt(13); } } else if (tok->isName() && Token::Match(tok, "QString :: compare ( %str% , %str% )")) { const std::string &str1 = tok->strAt(4); const std::string &str2 = tok->strAt(6); alwaysTrueFalseStringCompareError(tok, str1, str2); tok = tok->tokAt(7); } else if (Token::Match(tok, "!!+ %str% ==|!= %str% !!+")) { const std::string &str1 = tok->strAt(1); const std::string &str2 = tok->strAt(3); alwaysTrueFalseStringCompareError(tok, str1, str2); tok = tok->tokAt(5); } if (!tok) break; } } void CheckString::alwaysTrueFalseStringCompareError(const Token *tok, const std::string& str1, const std::string& str2) { constexpr std::size_t stringLen = 10; const std::string string1 = (str1.size() < stringLen) ? str1 : (str1.substr(0, stringLen-2) + ".."); const std::string string2 = (str2.size() < stringLen) ? str2 : (str2.substr(0, stringLen-2) + ".."); reportError(tok, Severity::warning, "staticStringCompare", "Unnecessary comparison of static strings.\n" "The compared strings, '" + string1 + "' and '" + string2 + "', are always " + (str1==str2?"identical":"unequal") + ". " "Therefore the comparison is unnecessary and looks suspicious.", (str1==str2)?CWE571:CWE570, Certainty::normal); } void CheckString::alwaysTrueStringVariableCompareError(const Token *tok, const std::string& str1, const std::string& str2) { reportError(tok, Severity::warning, "stringCompare", "Comparison of identical string variables.\n" "The compared strings, '" + str1 + "' and '" + str2 + "', are identical. " "This could be a logic bug.", CWE571, Certainty::normal); } //----------------------------------------------------------------------------- // Detect "str == '\0'" where "*str == '\0'" is correct. // Comparing char* with each other instead of using strcmp() //----------------------------------------------------------------------------- void CheckString::checkSuspiciousStringCompare() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckString::checkSuspiciousStringCompare"); // warning const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp()) continue; const Token* varTok = tok->astOperand1(); const Token* litTok = tok->astOperand2(); if (!varTok || !litTok) // <- failed to create AST for comparison continue; if (Token::Match(varTok, "%char%|%num%|%str%")) std::swap(varTok, litTok); else if (!Token::Match(litTok, "%char%|%num%|%str%")) continue; if (varTok->isLiteral()) continue; const ValueType* varType = varTok->valueType(); if (varTok->isCpp() && (!varType || !varType->isIntegral())) continue; if (litTok->tokType() == Token::eString) { if (varTok->isC() || (varType && varType->pointer)) suspiciousStringCompareError(tok, varTok->expressionString(), litTok->isLong()); } else if (litTok->tokType() == Token::eChar && varType && varType->pointer) { suspiciousStringCompareError_char(tok, varTok->expressionString()); } } } } void CheckString::suspiciousStringCompareError(const Token* tok, const std::string& var, bool isLong) { const std::string cmpFunc = isLong ? "wcscmp" : "strcmp"; reportError(tok, Severity::warning, "literalWithCharPtrCompare", "$symbol:" + var + "\nString literal compared with variable '$symbol'. Did you intend to use " + cmpFunc + "() instead?", CWE595, Certainty::normal); } void CheckString::suspiciousStringCompareError_char(const Token* tok, const std::string& var) { reportError(tok, Severity::warning, "charLiteralWithCharPtrCompare", "$symbol:" + var + "\nChar literal compared with pointer '$symbol'. Did you intend to dereference it?", CWE595, Certainty::normal); } //--------------------------------------------------------------------------- // Adding C-string and char with operator+ //--------------------------------------------------------------------------- static bool isChar(const Variable* var) { return (var && !var->isPointer() && !var->isArray() && (var->typeStartToken()->str() == "char" || var->typeStartToken()->str() == "wchar_t")); } void CheckString::strPlusChar() { logChecker("CheckString::strPlusChar"); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() == "+") { if (tok->astOperand1() && (tok->astOperand1()->tokType() == Token::eString)) { // string literal... if (tok->astOperand2() && (tok->astOperand2()->tokType() == Token::eChar || isChar(tok->astOperand2()->variable()))) // added to char variable or char constant strPlusCharError(tok); } } } } } void CheckString::strPlusCharError(const Token *tok) { std::string charType = "char"; if (tok && tok->astOperand2() && tok->astOperand2()->variable()) charType = tok->astOperand2()->variable()->typeStartToken()->str(); else if (tok && tok->astOperand2() && tok->astOperand2()->tokType() == Token::eChar && tok->astOperand2()->isLong()) charType = "wchar_t"; reportError(tok, Severity::error, "strPlusChar", "Unusual pointer arithmetic. A value of type '" + charType +"' is added to a string literal.", CWE665, Certainty::normal); } static bool isMacroUsage(const Token* tok) { if (const Token* parent = tok->astParent()) { while (parent && (parent->isCast() || parent->str() == "&&")) { if (parent->isExpandedMacro()) return true; parent = parent->astParent(); } if (!parent) return false; if (parent->isExpandedMacro()) return true; if (parent->isUnaryOp("!") || parent->isComparisonOp()) { int argn{}; const Token* ftok = getTokenArgumentFunction(parent, argn); if (ftok && !ftok->function()) return true; } } return false; } //--------------------------------------------------------------------------- // Implicit casts of string literals to bool // Comparing string literal with strlen() with wrong length //--------------------------------------------------------------------------- void CheckString::checkIncorrectStringCompare() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckString::checkIncorrectStringCompare"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { // skip "assert(str && ..)" and "assert(.. && str)" if ((endsWith(tok->str(), "assert") || endsWith(tok->str(), "ASSERT")) && Token::Match(tok, "%name% (") && (Token::Match(tok->tokAt(2), "%str% &&") || Token::Match(tok->linkAt(1)->tokAt(-2), "&& %str% )"))) tok = tok->linkAt(1); if (Token::simpleMatch(tok, ". substr (") && Token::Match(tok->tokAt(3)->nextArgument(), "%num% )")) { const MathLib::biguint clen = MathLib::toBigUNumber(tok->linkAt(2)->strAt(-1)); const Token* begin = tok->previous(); for (;;) { // Find start of statement while (begin->link() && Token::Match(begin, "]|)|>")) begin = begin->link()->previous(); if (Token::Match(begin->previous(), ".|::")) begin = begin->tokAt(-2); else break; } begin = begin->previous(); const Token* end = tok->linkAt(2)->next(); if (Token::Match(begin->previous(), "%str% ==|!=") && begin->strAt(-2) != "+") { const std::size_t slen = Token::getStrLength(begin->previous()); if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", begin->strAt(-1)); } } else if (Token::Match(end, "==|!= %str% !!+")) { const std::size_t slen = Token::getStrLength(end->next()); if (clen != slen) { incorrectStringCompareError(tok->next(), "substr", end->strAt(1)); } } } else if (Token::Match(tok, "%str%|%char%") && isUsedAsBool(tok, *mSettings) && !isMacroUsage(tok)) incorrectStringBooleanError(tok, tok->str()); } } } void CheckString::incorrectStringCompareError(const Token *tok, const std::string& func, const std::string &string) { reportError(tok, Severity::warning, "incorrectStringCompare", "$symbol:" + func + "\nString literal " + string + " doesn't match length argument for $symbol().", CWE570, Certainty::normal); } void CheckString::incorrectStringBooleanError(const Token *tok, const std::string& string) { const bool charLiteral = isCharLiteral(string); const std::string literalType = charLiteral ? "char" : "string"; const std::string result = bool_to_string(getCharLiteral(string) != "\\0"); reportError(tok, Severity::warning, charLiteral ? "incorrectCharBooleanError" : "incorrectStringBooleanError", "Conversion of " + literalType + " literal " + string + " to bool always evaluates to " + result + '.', CWE571, Certainty::normal); } //--------------------------------------------------------------------------- // always true: strcmp(str,"a")==0 || strcmp(str,"b") // TODO: Library configuration for string comparison functions //--------------------------------------------------------------------------- void CheckString::overlappingStrcmp() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckString::overlappingStrcmp"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() != "||") continue; std::list<const Token *> equals0; std::list<const Token *> notEquals0; visitAstNodes(tok, [&](const Token * t) { if (!t) return ChildrenToVisit::none; if (t->str() == "||") { return ChildrenToVisit::op1_and_op2; } if (t->str() == "==") { if (Token::simpleMatch(t->astOperand1(), "(") && Token::simpleMatch(t->astOperand2(), "0")) equals0.push_back(t->astOperand1()); else if (Token::simpleMatch(t->astOperand2(), "(") && Token::simpleMatch(t->astOperand1(), "0")) equals0.push_back(t->astOperand2()); return ChildrenToVisit::none; } if (t->str() == "!=") { if (Token::simpleMatch(t->astOperand1(), "(") && Token::simpleMatch(t->astOperand2(), "0")) notEquals0.push_back(t->astOperand1()); else if (Token::simpleMatch(t->astOperand2(), "(") && Token::simpleMatch(t->astOperand1(), "0")) notEquals0.push_back(t->astOperand2()); return ChildrenToVisit::none; } if (t->str() == "!" && Token::simpleMatch(t->astOperand1(), "(")) equals0.push_back(t->astOperand1()); else if (t->str() == "(") notEquals0.push_back(t); return ChildrenToVisit::none; }); for (const Token *eq0 : equals0) { for (const Token * ne0 : notEquals0) { if (!Token::Match(eq0->previous(), "strcmp|wcscmp (")) continue; if (!Token::Match(ne0->previous(), "strcmp|wcscmp (")) continue; const std::vector<const Token *> args1 = getArguments(eq0->previous()); const std::vector<const Token *> args2 = getArguments(ne0->previous()); if (args1.size() != 2 || args2.size() != 2) continue; if (args1[1]->isLiteral() && args2[1]->isLiteral() && args1[1]->str() != args2[1]->str() && isSameExpression(true, args1[0], args2[0], *mSettings, true, false)) overlappingStrcmpError(eq0, ne0); } } } } } void CheckString::overlappingStrcmpError(const Token *eq0, const Token *ne0) { std::string eq0Expr(eq0 ? eq0->expressionString() : std::string("strcmp(x,\"abc\")")); if (eq0 && eq0->astParent()->str() == "!") eq0Expr = "!" + eq0Expr; else eq0Expr += " == 0"; const std::string ne0Expr = (ne0 ? ne0->expressionString() : std::string("strcmp(x,\"def\")")) + " != 0"; reportError(ne0, Severity::warning, "overlappingStrcmp", "The expression '" + ne0Expr + "' is suspicious. It overlaps '" + eq0Expr + "'."); } //--------------------------------------------------------------------------- // Overlapping source and destination passed to sprintf(). // TODO: Library configuration for overlapping arguments //--------------------------------------------------------------------------- void CheckString::sprintfOverlappingData() { logChecker("CheckString::sprintfOverlappingData"); const SymbolDatabase* symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "sprintf|snprintf|swprintf (")) continue; const std::vector<const Token *> args = getArguments(tok); const int formatString = Token::simpleMatch(tok, "sprintf") ? 1 : 2; for (unsigned int argnr = formatString + 1; argnr < args.size(); ++argnr) { const Token *dest = args[0]; while (dest->isCast()) dest = dest->astOperand2() ? dest->astOperand2() : dest->astOperand1(); const Token *arg = args[argnr]; if (!arg->valueType() || arg->valueType()->pointer != 1) continue; while (arg->isCast()) arg = arg->astOperand2() ? arg->astOperand2() : arg->astOperand1(); const bool same = isSameExpression(false, dest, arg, *mSettings, true, false); if (same) { sprintfOverlappingDataError(tok, args[argnr], arg->expressionString()); } } } } } void CheckString::sprintfOverlappingDataError(const Token *funcTok, const Token *tok, const std::string &varname) { const std::string func = funcTok ? funcTok->str() : "s[n]printf"; reportError(tok, Severity::error, "sprintfOverlappingData", "$symbol:" + varname + "\n" "Undefined behavior: Variable '$symbol' is used as parameter and destination in " + func + "().\n" + "The variable '$symbol' is used both as a parameter and as destination in " + func + "(). The origin and destination buffers overlap. Quote from glibc (C-library) " "documentation (http://www.gnu.org/software/libc/manual/html_mono/libc.html#Formatted-Output-Functions): " "\"If copying takes place between objects that overlap as a result of a call " "to sprintf() or snprintf(), the results are undefined.\"", CWE628, Certainty::normal); }
22,570
C++
.cpp
423
42.943262
351
0.546438
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,157
check.cpp
danmar_cppcheck/lib/check.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2023 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "check.h" #include "errorlogger.h" #include "settings.h" #include "token.h" #include "tokenize.h" #include "vfvalue.h" #include <algorithm> #include <cctype> #include <iostream> #include <stdexcept> #include <utility> //--------------------------------------------------------------------------- Check::Check(const std::string &aname) : mName(aname) { { const auto it = std::find_if(instances().begin(), instances().end(), [&](const Check *i) { return i->name() == aname; }); if (it != instances().end()) throw std::runtime_error("'" + aname + "' instance already exists"); } // make sure the instances are sorted const auto it = std::find_if(instances().begin(), instances().end(), [&](const Check* i) { return i->name() > aname; }); if (it == instances().end()) instances().push_back(this); else instances().insert(it, this); } void Check::writeToErrorList(const ErrorMessage &errmsg) { std::cout << errmsg.toXML() << std::endl; } void Check::reportError(const std::list<const Token *> &callstack, Severity severity, const std::string &id, const std::string &msg, const CWE &cwe, Certainty certainty) { const ErrorMessage errmsg(callstack, mTokenizer ? &mTokenizer->list : nullptr, severity, id, msg, cwe, certainty); if (mErrorLogger) mErrorLogger->reportErr(errmsg); else writeToErrorList(errmsg); } void Check::reportError(const ErrorPath &errorPath, Severity severity, const char id[], const std::string &msg, const CWE &cwe, Certainty certainty) { const ErrorMessage errmsg(errorPath, mTokenizer ? &mTokenizer->list : nullptr, severity, id, msg, cwe, certainty); if (mErrorLogger) mErrorLogger->reportErr(errmsg); else writeToErrorList(errmsg); } bool Check::wrongData(const Token *tok, const char *str) { if (mSettings->daca) reportError(tok, Severity::debug, "DacaWrongData", "Wrong data detected by condition " + std::string(str)); return true; } std::list<Check *> &Check::instances() { #ifdef __SVR4 // Under Solaris, destructors are called in wrong order which causes a segmentation fault. // This fix ensures pointer remains valid and reachable until program terminates. static std::list<Check *> *_instances= new std::list<Check *>; return *_instances; #else static std::list<Check *> _instances; return _instances; #endif } std::string Check::getMessageId(const ValueFlow::Value &value, const char id[]) { if (value.condition != nullptr) return id + std::string("Cond"); if (value.safe) return std::string("safe") + (char)std::toupper(id[0]) + (id + 1); return id; } ErrorPath Check::getErrorPath(const Token* errtok, const ValueFlow::Value* value, std::string bug) const { ErrorPath errorPath; if (!value) { errorPath.emplace_back(errtok, std::move(bug)); } else if (mSettings->verbose || mSettings->xml || !mSettings->templateLocation.empty()) { errorPath = value->errorPath; errorPath.emplace_back(errtok, std::move(bug)); } else { if (value->condition) errorPath.emplace_back(value->condition, "condition '" + value->condition->expressionString() + "'"); //else if (!value->isKnown() || value->defaultArg) // errorPath = value->callstack; errorPath.emplace_back(errtok, std::move(bug)); } return errorPath; } void Check::logChecker(const char id[]) { reportError(nullptr, Severity::internal, "logChecker", id); }
4,418
C++
.cpp
116
33.974138
169
0.658343
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,158
checkersidmapping.cpp
danmar_cppcheck/lib/checkersidmapping.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // This file is auto generated by script, do not edit // Mappings of Cppcheck warning IDs to guidelines #include "checkers.h" std::vector<checkers::IdMapping> checkers::idMappingAutosar{ {"m0-1-1", "unreachableCode,duplicateBreak"}, {"m0-1-2", "unsignedLessThanZero"}, {"m0-1-3", "unusedVariable,unusedStructMember"}, {"a0-1-1", "unreadVariable,unusedValue,redundantAssignment"}, {"m0-1-9", "redundantAssignment,redundantInitialization"}, {"m0-1-10", "unusedFunction"}, {"m0-2-1", "overlappingWriteUnion,overlappingWriteFunction"}, {"a1-1-1", "g++ .."}, {"a2-3-1", "The code contains unhandled character(s) (character code=195). Neither unicode nor extended ascii is supported. [syntaxError]"}, {"a2-7-3", "doxygen,clang -Wdocumentation"}, {"a2-10-1", "shadowVariable,shadowFunction,shadowArgument"}, {"a2-13-2", "compile error"}, {"a2-13-4", "compiler error"}, {"m3-2-2", "ctuOneDefinitionRuleViolation"}, {"m3-4-1", "variableScope"}, {"a5-0-1", "-Wsequence-point"}, {"m5-0-16", "pointerOutOfBounds"}, {"m5-0-17", "comparePointers"}, {"m5-0-18", "comparePointers"}, {"a5-1-4", "returnDanglingLifetime"}, {"a5-2-2", "cstyleCast"}, {"a5-2-5", "arrayIndexOutOfBounds,arrayIndexOutOfBoundsCond,pointerOutOfBounds,pointerOutOfBoundsCond,negativeIndex,arrayIndexThenCheck,bufferAccessOutOfBounds,objectIndex,argumentSize"}, {"m5-3-4", "sizeofFunctionCall"}, {"a5-3-2", "nullPointer,nullPointerRedundantCheck,nullPointerArithmetic,nullPointerArithmeticRedundantCheck,nullPointerDefaultArg"}, {"a5-6-1", "zerodiv,zerodivcond"}, {"m5-8-1", "shiftTooManyBits"}, {"m7-1-2", "constParameter"}, {"a7-5-1", "returnDanglingLifetime"}, {"m8-4-2", "funcArgNamesDifferent"}, {"a8-4-2", "missingReturn"}, {"a8-5-0", "uninitdata"}, {"m9-3-3", "functionConst,functionStatic"}, {"a12-1-1", "uninitMemberVar"}, {"m12-1-1", "virtualCallInConstructor"}, {"a12-1-4", "noExplicitConstructor"}, {"a12-6-1", "useInitializationList"}, {"a12-8-3", "accessMoved"}, {"a15-1-4", "memleak"}, {"m15-3-1", "exceptThrowInDestructor"}, {"a15-4-2", "throwInNoexceptFunction"}, {"m16-0-5", "preprocessorErrorDirective"}, {"a16-2-2", "iwyu,check headers"}, {"a18-5-3", "mismatchAllocDealloc"}, {"a20-8-1", "doubleFree"}, {"a23-0-2", "invalidContainer"}, }; std::vector<checkers::IdMapping> checkers::idMappingCertC{ {"PRE30", "preprocessorErrorDirective"}, {"PRE32", "preprocessorErrorDirective"}, {"DCL30", "danglingLifetime,autoVariables,invalidLifetime,returnDanglingLifetime"}, {"EXP30", "unknownEvaluationOrder"}, {"EXP33", "uninitvar,uninitdata,uninitStructMember"}, {"EXP34", "nullPointer,nullPointerDefaultArg,nullPointerRedundantCheck,nullPointerArithmetic,nullPointerArithmeticRedundantCheck"}, {"EXP44", "sizeofCalculation"}, {"EXP46", "bitwiseOnBoolean"}, {"FLP32", "invalidFunctionArg"}, {"FLP34", "floatConversionOverflow"}, {"ARR36", "comparePointers"}, {"STR30", "stringLiteralWrite"}, {"STR37", "invalidFunctionArg"}, {"MEM30", "doubleFree,deallocret,deallocuse"}, {"MEM31", "memleak,leakReturnValNotUsed,leakUnsafeArgAlloc,memleakOnRealloc"}, {"MEM34", "autovarInvalidDeallocation,mismatchAllocDealloc"}, {"FIO39", "IOWithoutPositioning"}, {"FIO42", "resourceLeak"}, {"FIO46", "deallocuse,useClosedFile"}, {"FIO47", "invalidscanf,wrongPrintfScanfArgNum,invalidLengthModifierError,invalidScanfFormatWidth,wrongPrintfScanfParameterPositionError"}, {"MSC37", "missingReturn"}, }; std::vector<checkers::IdMapping> checkers::idMappingCertCpp{ {"DCL57", "deallocThrow,exceptThrowInDestructor"}, {"DCL60", "ctuOneDefinitionRuleViolation"}, {"EXP52", "sizeofCalculation"}, {"EXP53", "uninitvar"}, {"EXP54", "uninitvar,danglingLifetime,danglingReference,danglingTemporaryLifetime,danglingTempReference,returnDanglingLifetime"}, {"EXP61", "danglingLifetime,danglingReference,danglingTemporaryLifetime,danglingTempReference,returnDanglingLifetime"}, {"EXP63", "accessMoved"}, {"CTR51", "eraseDereference"}, {"CTR54", "comparePointers"}, {"CTR55", "containerOutOfBounds"}, {"STR51", "nullPointer"}, {"STR52", "invalidContainer"}, {"MEM50", "deallocuse"}, {"MEM51", "mismatchAllocDealloc"}, {"MEM56", "doubleFree"}, {"FIO50", "IOWithoutPositioning"}, {"ERR57", "memleak"}, {"OOP50", "virtualCallInConstructor"}, {"OOP52", "virtualDestructor"}, {"OOP53", "initializerList"}, {"OOP54", "operatorEqToSelf"}, {"MSC52", "missingReturn"}, }; std::vector<checkers::IdMapping> checkers::idMappingMisraC{ {"1.1", "syntaxError"}, {"1.3", "error"}, {"2.1", "duplicateBreak,unreachableCode"}, {"2.2", "redundantCondition,redundantAssignment,redundantAssignInSwitch,unreadVariable"}, {"2.6", "unusedLabel"}, {"2.8", "unusedVariable"}, {"5.3", "shadowVariable"}, {"8.3", "funcArgNamesDifferent"}, {"8.13", "constParameterPointer"}, {"9.1", "uninitvar"}, {"12.5", "sizeofwithsilentarraypointer"}, {"13.2", "unknownEvaluationOrder"}, {"13.6", "sizeofCalculation"}, {"14.3", "compareValueOutOfTypeRangeError,knownConditionTrueFalse"}, {"17.4", "missingReturn"}, {"17.5", "argumentSize"}, {"18.1", "pointerOutOfBounds"}, {"18.2", "comparePointers"}, {"18.3", "comparePointers"}, {"18.6", "danglingLifetime,danglingTemporaryLifetime,returnDanglingLifetime"}, {"19.1", "overlappingWriteUnion,overlappingWriteFunction"}, {"20.6", "preprocessorErrorDirective"}, {"21.13", "invalidFunctionArg"}, {"21.17", "bufferAccessOutOfBounds"}, {"21.18", "bufferAccessOutOfBounds"}, {"22.1", "memleak,resourceLeak,memleakOnRealloc,leakReturnValNotUsed,leakNoVarFunctionCall"}, {"22.2", "autovarInvalidDeallocation"}, {"22.3", "incompatibleFileOpen"}, {"22.4", "writeReadOnlyFile"}, {"22.6", "useClosedFile"}, }; std::vector<checkers::IdMapping> checkers::idMappingMisraCpp2008{ {"0-1-1", "unreachableCode,duplicateBreak"}, {"0-1-2", "unsignedLessThanZero"}, {"0-1-3", "unusedVariable,unusedStructMember"}, {"0-1-6", "redundantAssignment,unreadVariable,variableScope"}, {"0-1-9", "redundantAssignment,redundantInitialization"}, {"0-1-10", "unusedFunction"}, {"0-2-1", "overlappingWriteUnion,overlappingWriteFunction"}, {"2-10-2", "shadowVariable"}, {"3-2-2", "ctuOneDefinitionRuleViolation"}, {"3-4-1", "variableScope"}, {"5-0-1", "unknownEvaluationOrder"}, {"5-0-16", "pointerOutOfBounds"}, {"5-0-17", "comparePointers"}, {"5-0-18", "comparePointers"}, {"5-2-4", "cstyleCast"}, {"5-3-4", "sizeofFunctionCall"}, {"5-8-1", "shiftTooManyBits"}, {"7-1-1", "constVariable,constParameter"}, {"7-1-2", "constParameter"}, {"7-5-1", "autoVariables,returnReference,returnTempReference"}, {"7-5-2", "danglingLifetime"}, {"8-4-2", "funcArgNamesDifferent"}, {"8-4-3", "missingReturn"}, {"8-5-1", "uninitvar,uninitdata,uninitStructMember,uninitMemberVar,uninitMemberVarPrivate,uninitDerivedMemberVar,uninitDerivedMemberVarPrivate"}, {"9-3-3", "functionConst,functionStatic"}, {"12-1-1", "virtualCallInConstructor"}, {"12-1-3", "noExplicitConstructor"}, {"15-3-1", "exceptThrowInDestructor"}, {"15-5-1", "exceptThrowInDestructor"}, {"15-5-3", "exceptThrowInDestructor"}, {"16-0-5", "preprocessorErrorDirective"}, }; std::vector<checkers::IdMapping> checkers::idMappingMisraCpp2023{ {"0.0.1", "unreachableCode"}, {"0.0.2", "compareBoolExpressionWithInt,compareValueOutOfTypeRangeError,identicalConditionAfterEarlyExit,identicalInnerCondition,knownConditionTrueFalse"}, {"0.1.1", "redundantAssignInSwitch,redundantAssignment,redundantCopy,redundantInitialization,unreadVariable"}, {"Dir 0.3.2", "invalidFunctionArg,invalidFunctionArgBool,invalidFunctionArgStr"}, {"4.1.3", "error"}, {"4.6.1", "unknownEvaluationOrder"}, {"6.2.1", "ctuOneDefinitionRuleViolation"}, {"6.4.1", "shadowVariable"}, {"6.8.1", "danglingLifetime"}, {"6.8.2", "autoVariables"}, {"8.7.1", "pointerOutOfBounds,pointerOutOfBoundsCond"}, {"8.7.2", "subtractPointers"}, {"8.9.1", "comparePointers"}, {"8.18.1", "overlappingWriteUnion"}, {"9.6.5", "missingReturn"}, {"10.1.1", "constParameter,constParameterReference"}, {"11.6.2", "uninitvar"}, {"15.1.1", "virtualCallInConstructor"}, {"15.1.4", "uninitMemberVar"}, {"Dir 15.8.1", "operatorEqToSelf"}, {"19.3.5", "preprocessorErrorDirective"}, {"28.6.3", "accessForwarded,accessMoved"}, {"28.6.4", "ignoredReturnValue"}, };
9,499
C++
.cpp
204
42.083333
191
0.690386
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,159
mathlib.cpp
danmar_cppcheck/lib/mathlib.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mathlib.h" #include "errortypes.h" #include "utils.h" #include <cctype> #include <cmath> #include <cstdint> #include <cstdlib> #include <exception> #include <limits> #include <locale> #include <sstream> #include <stdexcept> #include <numeric> #include <simplecpp.h> const int MathLib::bigint_bits = 64; MathLib::value::value(const std::string &s) { if (MathLib::isFloat(s)) { mType = MathLib::value::Type::FLOAT; mDoubleValue = MathLib::toDoubleNumber(s); return; } if (!MathLib::isInt(s)) throw InternalError(nullptr, "Invalid value: " + s); mType = MathLib::value::Type::INT; mIntValue = MathLib::toBigNumber(s); if (isIntHex(s) && mIntValue < 0) mIsUnsigned = true; // read suffix if (s.size() >= 2U) { for (std::size_t i = s.size() - 1U; i > 0U; --i) { const char c = s[i]; if (c == 'u' || c == 'U') mIsUnsigned = true; else if (c == 'l' || c == 'L') { if (mType == MathLib::value::Type::INT) mType = MathLib::value::Type::LONG; else if (mType == MathLib::value::Type::LONG) mType = MathLib::value::Type::LONGLONG; } else if (i > 2U && c == '4' && s[i-1] == '6' && s[i-2] == 'i') mType = MathLib::value::Type::LONGLONG; } } } std::string MathLib::value::str() const { std::ostringstream ostr; if (mType == MathLib::value::Type::FLOAT) { if (std::isnan(mDoubleValue)) return "nan.0"; if (std::isinf(mDoubleValue)) return (mDoubleValue > 0) ? "inf.0" : "-inf.0"; ostr.precision(9); ostr << std::fixed << mDoubleValue; // remove trailing zeros std::string ret(ostr.str()); std::string::size_type pos = ret.size() - 1U; while (ret[pos] == '0') pos--; if (ret[pos] == '.') ++pos; return ret.substr(0, pos+1); } if (mIsUnsigned) ostr << static_cast<biguint>(mIntValue) << "U"; else ostr << mIntValue; if (mType == MathLib::value::Type::LONG) ostr << "L"; else if (mType == MathLib::value::Type::LONGLONG) ostr << "LL"; return ostr.str(); } void MathLib::value::promote(const MathLib::value &v) { if (isInt() && v.isInt()) { if (mType < v.mType) { mType = v.mType; mIsUnsigned = v.mIsUnsigned; } else if (mType == v.mType) { mIsUnsigned |= v.mIsUnsigned; } } else if (!isFloat()) { mIsUnsigned = false; mDoubleValue = mIntValue; mType = MathLib::value::Type::FLOAT; } } MathLib::value MathLib::value::calc(char op, const MathLib::value &v1, const MathLib::value &v2) { value temp(v1); temp.promote(v2); if (temp.isFloat()) { switch (op) { case '+': temp.mDoubleValue += v2.getDoubleValue(); break; case '-': temp.mDoubleValue -= v2.getDoubleValue(); break; case '*': temp.mDoubleValue *= v2.getDoubleValue(); break; case '/': temp.mDoubleValue /= v2.getDoubleValue(); break; case '%': case '&': case '|': case '^': throw InternalError(nullptr, "Invalid calculation"); default: throw InternalError(nullptr, "Unhandled calculation"); } } else if (temp.mIsUnsigned) { switch (op) { case '+': temp.mIntValue += (unsigned long long)v2.mIntValue; break; case '-': temp.mIntValue -= (unsigned long long)v2.mIntValue; break; case '*': temp.mIntValue *= (unsigned long long)v2.mIntValue; break; case '/': if (v2.mIntValue == 0) throw InternalError(nullptr, "Internal Error: Division by zero"); if (v1.mIntValue == std::numeric_limits<bigint>::min() && std::abs(v2.mIntValue)<=1) throw InternalError(nullptr, "Internal Error: Division overflow"); temp.mIntValue /= (unsigned long long)v2.mIntValue; break; case '%': if (v2.mIntValue == 0) throw InternalError(nullptr, "Internal Error: Division by zero"); temp.mIntValue %= (unsigned long long)v2.mIntValue; break; case '&': temp.mIntValue &= (unsigned long long)v2.mIntValue; break; case '|': temp.mIntValue |= (unsigned long long)v2.mIntValue; break; case '^': temp.mIntValue ^= (unsigned long long)v2.mIntValue; break; default: throw InternalError(nullptr, "Unhandled calculation"); } } else { switch (op) { case '+': temp.mIntValue += v2.mIntValue; break; case '-': temp.mIntValue -= v2.mIntValue; break; case '*': temp.mIntValue *= v2.mIntValue; break; case '/': if (v2.mIntValue == 0) throw InternalError(nullptr, "Internal Error: Division by zero"); if (v1.mIntValue == std::numeric_limits<bigint>::min() && std::abs(v2.mIntValue)<=1) throw InternalError(nullptr, "Internal Error: Division overflow"); temp.mIntValue /= v2.mIntValue; break; case '%': if (v2.mIntValue == 0) throw InternalError(nullptr, "Internal Error: Division by zero"); temp.mIntValue %= v2.mIntValue; break; case '&': temp.mIntValue &= v2.mIntValue; break; case '|': temp.mIntValue |= v2.mIntValue; break; case '^': temp.mIntValue ^= v2.mIntValue; break; default: throw InternalError(nullptr, "Unhandled calculation"); } } return temp; } int MathLib::value::compare(const MathLib::value &v) const { value temp(*this); temp.promote(v); if (temp.isFloat()) { if (temp.mDoubleValue < v.getDoubleValue()) return -1; if (temp.mDoubleValue > v.getDoubleValue()) return 1; return 0; } if (temp.mIsUnsigned) { if ((unsigned long long)mIntValue < (unsigned long long)v.mIntValue) return -1; if ((unsigned long long)mIntValue > (unsigned long long)v.mIntValue) return 1; return 0; } if (mIntValue < v.mIntValue) return -1; if (mIntValue > v.mIntValue) return 1; return 0; } MathLib::value MathLib::value::add(int v) const { MathLib::value temp(*this); if (temp.isInt()) temp.mIntValue += v; else temp.mDoubleValue += v; return temp; } MathLib::value MathLib::value::shiftLeft(const MathLib::value &v) const { if (!isInt() || !v.isInt()) throw InternalError(nullptr, "Shift operand is not integer"); MathLib::value ret(*this); if (v.mIntValue >= MathLib::bigint_bits) { return ret; } ret.mIntValue <<= v.mIntValue; return ret; } MathLib::value MathLib::value::shiftRight(const MathLib::value &v) const { if (!isInt() || !v.isInt()) throw InternalError(nullptr, "Shift operand is not integer"); MathLib::value ret(*this); if (v.mIntValue >= MathLib::bigint_bits) { return ret; } ret.mIntValue >>= v.mIntValue; return ret; } // TODO: remove handling of non-literal stuff MathLib::biguint MathLib::toBigUNumber(const std::string & str) { // hexadecimal numbers: if (isIntHex(str)) { try { const biguint ret = std::stoull(str, nullptr, 16); return ret; } catch (const std::out_of_range& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: out_of_range: " + str); } catch (const std::invalid_argument& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: invalid_argument: " + str); } } // octal numbers: if (isOct(str)) { try { const biguint ret = std::stoull(str, nullptr, 8); return ret; } catch (const std::out_of_range& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: out_of_range: " + str); } catch (const std::invalid_argument& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: invalid_argument: " + str); } } // binary numbers: if (isBin(str)) { biguint ret = 0; for (std::string::size_type i = str[0] == '0'?2:3; i < str.length(); i++) { if (str[i] != '1' && str[i] != '0') break; ret <<= 1; if (str[i] == '1') ret |= 1; } if (str[0] == '-') ret = -ret; return ret; } if (isFloat(str)) { // Things are going to be less precise now: the value can't be represented in the biguint type. // Use min/max values as an approximation. See #5843 // TODO: bail out when we are out of range? const double doubleval = toDoubleNumber(str); if (doubleval > (double)std::numeric_limits<biguint>::max()) return std::numeric_limits<biguint>::max(); // cast to bigint to avoid UBSAN warning about negative double being out-of-range return static_cast<biguint>(static_cast<bigint>(doubleval)); } if (isCharLiteral(str)) return simplecpp::characterLiteralToLL(str); try { std::size_t idx = 0; const biguint ret = std::stoull(str, &idx, 10); if (idx != str.size()) { const std::string s = str.substr(idx); if (!isValidIntegerSuffix(s, true)) throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: input was not completely consumed: " + str); } return ret; } catch (const std::out_of_range& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: out_of_range: " + str); } catch (const std::invalid_argument& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigUNumber: invalid_argument: " + str); } } unsigned int MathLib::encodeMultiChar(const std::string& str) { return std::accumulate(str.cbegin(), str.cend(), uint32_t(), [](uint32_t v, char c) { return (v << 8) | c; }); } // TODO: remove handling of non-literal stuff MathLib::bigint MathLib::toBigNumber(const std::string & str) { // hexadecimal numbers: if (isIntHex(str)) { try { const biguint ret = std::stoull(str, nullptr, 16); return (bigint)ret; } catch (const std::out_of_range& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: out_of_range: " + str); } catch (const std::invalid_argument& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: invalid_argument: " + str); } } // octal numbers: if (isOct(str)) { try { const biguint ret = std::stoull(str, nullptr, 8); return ret; } catch (const std::out_of_range& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: out_of_range: " + str); } catch (const std::invalid_argument& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: invalid_argument: " + str); } } // binary numbers: if (isBin(str)) { bigint ret = 0; for (std::string::size_type i = str[0] == '0'?2:3; i < str.length(); i++) { if (str[i] != '1' && str[i] != '0') break; ret <<= 1; if (str[i] == '1') ret |= 1; } if (str[0] == '-') ret = -ret; return ret; } if (isFloat(str)) { // Things are going to be less precise now: the value can't be represented in the bigint type. // Use min/max values as an approximation. See #5843 // TODO: bail out when we are out of range? const double doubleval = toDoubleNumber(str); if (doubleval > (double)std::numeric_limits<bigint>::max()) return std::numeric_limits<bigint>::max(); if (doubleval < (double)std::numeric_limits<bigint>::min()) return std::numeric_limits<bigint>::min(); return static_cast<bigint>(doubleval); } if (isCharLiteral(str)) return simplecpp::characterLiteralToLL(str); try { std::size_t idx = 0; const biguint ret = std::stoull(str, &idx, 10); if (idx != str.size()) { const std::string s = str.substr(idx); if (!isValidIntegerSuffix(s, true)) throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: input was not completely consumed: " + str); } return ret; } catch (const std::out_of_range& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: out_of_range: " + str); } catch (const std::invalid_argument& /*e*/) { throw InternalError(nullptr, "Internal Error. MathLib::toBigNumber: invalid_argument: " + str); } } // in-place conversion of (sub)string to double. Requires no heap. static double myStod(const std::string& str, std::string::const_iterator from, std::string::const_iterator to, int base) { double result = 0.; bool positivesign = true; std::string::const_iterator it; if ('+' == *from) { it = from + 1; } else if ('-' == *from) { it = from + 1; positivesign = false; } else it = from; const std::size_t decimalsep = str.find('.', it-str.begin()); int distance; if (std::string::npos == decimalsep) { distance = to - it; } else if (decimalsep > (to - str.begin())) return 0.; // error handling?? else distance = int(decimalsep)-(from - str.begin()); auto digitval = [&](char c) { if ((10 < base) && (c > '9')) return 10 + std::tolower(c) - 'a'; return c - '0'; }; for (; it!=to; ++it) { if ('.' == *it) continue; --distance; result += digitval(*it)* std::pow(base, distance); } return positivesign ? result : -result; } // Assuming a limited support of built-in hexadecimal floats (see C99, C++17) that is a fall-back implementation. // Performance has been optimized WRT to heap activity, however the calculation part is not optimized. static double floatHexToDoubleNumber(const std::string& str) { const std::size_t p = str.find_first_of("pP",3); const double factor1 = myStod(str, str.cbegin() + 2, str.cbegin()+p, 16); const bool suffix = (str.back() == 'f') || (str.back() == 'F') || (str.back() == 'l') || (str.back() == 'L'); const double exponent = myStod(str, str.cbegin() + p + 1, suffix ? str.cend()-1:str.cend(), 10); const double factor2 = std::pow(2, exponent); return factor1 * factor2; } double MathLib::toDoubleNumber(const std::string &str) { if (isCharLiteral(str)) { try { return simplecpp::characterLiteralToLL(str); } catch (const std::exception& e) { throw InternalError(nullptr, "Internal Error. MathLib::toDoubleNumber: characterLiteralToLL(" + str + ") => " + e.what()); } } if (isIntHex(str)) return static_cast<double>(toBigNumber(str)); #ifdef _LIBCPP_VERSION if (isFloat(str)) // Workaround libc++ bug at https://github.com/llvm/llvm-project/issues/18156 // TODO: handle locale // TODO: make sure all characters are being consumed return std::strtod(str.c_str(), nullptr); #endif if (isFloatHex(str)) return floatHexToDoubleNumber(str); // otherwise, convert to double std::istringstream istr(str); istr.imbue(std::locale::classic()); double ret; if (!(istr >> ret)) throw InternalError(nullptr, "Internal Error. MathLib::toDoubleNumber: conversion failed: " + str); std::string s; if (istr >> s) { if (isDecimalFloat(str)) return ret; if (!isValidIntegerSuffix(s, true)) throw InternalError(nullptr, "Internal Error. MathLib::toDoubleNumber: input was not completely consumed: " + str); } return ret; } template<> std::string MathLib::toString<double>(double value) { std::ostringstream result; result.precision(12); result << value; std::string s = result.str(); if (s == "-0") return "0.0"; if (s.find_first_of(".e") == std::string::npos) return s + ".0"; return s; } bool MathLib::isFloat(const std::string &str) { return isDecimalFloat(str) || isFloatHex(str); } bool MathLib::isDecimalFloat(const std::string &str) { if (str.empty()) return false; enum class State : std::uint8_t { START, BASE_DIGITS1, LEADING_DECIMAL, TRAILING_DECIMAL, BASE_DIGITS2, E, MANTISSA_PLUSMINUS, MANTISSA_DIGITS, SUFFIX_F, SUFFIX_L, SUFFIX_LITERAL_LEADER, SUFFIX_LITERAL } state = State::START; std::string::const_iterator it = str.cbegin(); if ('+' == *it || '-' == *it) ++it; for (; it != str.cend(); ++it) { switch (state) { case State::START: if (*it=='.') state = State::LEADING_DECIMAL; else if (std::isdigit(static_cast<unsigned char>(*it))) state = State::BASE_DIGITS1; else return false; break; case State::LEADING_DECIMAL: if (std::isdigit(static_cast<unsigned char>(*it))) state = State::BASE_DIGITS2; else return false; break; case State::BASE_DIGITS1: if (*it=='e' || *it=='E') state = State::E; else if (*it=='.') state = State::TRAILING_DECIMAL; else if (!std::isdigit(static_cast<unsigned char>(*it))) return false; break; case State::TRAILING_DECIMAL: if (*it=='e' || *it=='E') state = State::E; else if (*it=='f' || *it=='F') state = State::SUFFIX_F; else if (*it=='l' || *it=='L') state = State::SUFFIX_L; else if (*it == '_') state = State::SUFFIX_LITERAL_LEADER; else if (std::isdigit(static_cast<unsigned char>(*it))) state = State::BASE_DIGITS2; else return false; break; case State::BASE_DIGITS2: if (*it=='e' || *it=='E') state = State::E; else if (*it=='f' || *it=='F') state = State::SUFFIX_F; else if (*it=='l' || *it=='L') state = State::SUFFIX_L; else if (*it == '_') state = State::SUFFIX_LITERAL_LEADER; else if (!std::isdigit(static_cast<unsigned char>(*it))) return false; break; case State::E: if (*it=='+' || *it=='-') state = State::MANTISSA_PLUSMINUS; else if (std::isdigit(static_cast<unsigned char>(*it))) state = State::MANTISSA_DIGITS; else return false; break; case State::MANTISSA_PLUSMINUS: if (!std::isdigit(static_cast<unsigned char>(*it))) return false; else state = State::MANTISSA_DIGITS; break; case State::MANTISSA_DIGITS: if (*it=='f' || *it=='F') state = State::SUFFIX_F; else if (*it=='l' || *it=='L') state = State::SUFFIX_L; else if (!std::isdigit(static_cast<unsigned char>(*it))) return false; break; // Ensure at least one post _ char for user defined literals case State::SUFFIX_LITERAL: case State::SUFFIX_LITERAL_LEADER: state = State::SUFFIX_LITERAL; break; case State::SUFFIX_F: return false; case State::SUFFIX_L: return false; } } return (state==State::BASE_DIGITS2 || state==State::MANTISSA_DIGITS || state==State::TRAILING_DECIMAL || state==State::SUFFIX_F || state==State::SUFFIX_L || (state==State::SUFFIX_LITERAL)); } bool MathLib::isNegative(const std::string &str) { if (str.empty()) return false; return (str[0] == '-'); } bool MathLib::isPositive(const std::string &str) { if (str.empty()) return false; return !MathLib::isNegative(str); } static bool isValidIntegerSuffixIt(std::string::const_iterator it, std::string::const_iterator end, bool supportMicrosoftExtensions=true) { enum class Status : std::uint8_t { START, SUFFIX_U, SUFFIX_UL, SUFFIX_ULL, SUFFIX_UZ, SUFFIX_L, SUFFIX_LU, SUFFIX_LL, SUFFIX_LLU, SUFFIX_I, SUFFIX_I6, SUFFIX_I64, SUFFIX_UI, SUFFIX_UI6, SUFFIX_UI64, SUFFIX_Z, SUFFIX_LITERAL_LEADER, SUFFIX_LITERAL } state = Status::START; for (; it != end; ++it) { switch (state) { case Status::START: if (*it == 'u' || *it == 'U') state = Status::SUFFIX_U; else if (*it == 'l' || *it == 'L') state = Status::SUFFIX_L; else if (*it == 'z' || *it == 'Z') state = Status::SUFFIX_Z; else if (supportMicrosoftExtensions && (*it == 'i' || *it == 'I')) state = Status::SUFFIX_I; else if (*it == '_') state = Status::SUFFIX_LITERAL_LEADER; else return false; break; case Status::SUFFIX_U: if (*it == 'l' || *it == 'L') state = Status::SUFFIX_UL; // UL else if (*it == 'z' || *it == 'Z') state = Status::SUFFIX_UZ; // UZ else if (supportMicrosoftExtensions && (*it == 'i' || *it == 'I')) state = Status::SUFFIX_UI; else return false; break; case Status::SUFFIX_UL: if (*it == 'l' || *it == 'L') state = Status::SUFFIX_ULL; // ULL else return false; break; case Status::SUFFIX_L: if (*it == 'u' || *it == 'U') state = Status::SUFFIX_LU; // LU else if (*it == 'l' || *it == 'L') state = Status::SUFFIX_LL; // LL else return false; break; case Status::SUFFIX_LU: return false; case Status::SUFFIX_LL: if (*it == 'u' || *it == 'U') state = Status::SUFFIX_LLU; // LLU else return false; break; case Status::SUFFIX_I: if (*it == '6') state = Status::SUFFIX_I6; else return false; break; case Status::SUFFIX_I6: if (*it == '4') state = Status::SUFFIX_I64; else return false; break; case Status::SUFFIX_UI: if (*it == '6') state = Status::SUFFIX_UI6; else return false; break; case Status::SUFFIX_UI6: if (*it == '4') state = Status::SUFFIX_UI64; else return false; break; case Status::SUFFIX_Z: if (*it == 'u' || *it == 'U') state = Status::SUFFIX_UZ; else return false; break; // Ensure at least one post _ char for user defined literals case Status::SUFFIX_LITERAL: case Status::SUFFIX_LITERAL_LEADER: state = Status::SUFFIX_LITERAL; break; default: return false; } } return ((state == Status::SUFFIX_U) || (state == Status::SUFFIX_L) || (state == Status::SUFFIX_Z) || (state == Status::SUFFIX_UL) || (state == Status::SUFFIX_UZ) || (state == Status::SUFFIX_LU) || (state == Status::SUFFIX_LL) || (state == Status::SUFFIX_ULL) || (state == Status::SUFFIX_LLU) || (state == Status::SUFFIX_I64) || (state == Status::SUFFIX_UI64) || (state == Status::SUFFIX_LITERAL)); } // cppcheck-suppress unusedFunction bool MathLib::isValidIntegerSuffix(const std::string& str, bool supportMicrosoftExtensions) { return isValidIntegerSuffixIt(str.cbegin(), str.cend(), supportMicrosoftExtensions); } /*! \brief Does the string represent an octal number? * In case leading or trailing white space is provided, the function * returns false. * Additional information can be found here: * http://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html * * \param str The string to check. In case the string is empty, the function returns false. * \return Return true in case a octal number is provided and false otherwise. **/ bool MathLib::isOct(const std::string& str) { enum class Status : std::uint8_t { START, OCTAL_PREFIX, DIGITS } state = Status::START; if (str.empty()) return false; std::string::const_iterator it = str.cbegin(); if ('+' == *it || '-' == *it) ++it; for (; it != str.cend(); ++it) { switch (state) { case Status::START: if (*it == '0') state = Status::OCTAL_PREFIX; else return false; break; case Status::OCTAL_PREFIX: if (isOctalDigit(static_cast<unsigned char>(*it))) state = Status::DIGITS; else return false; break; case Status::DIGITS: if (isOctalDigit(static_cast<unsigned char>(*it))) state = Status::DIGITS; else return isValidIntegerSuffixIt(it,str.end()); break; } } return state == Status::DIGITS; } bool MathLib::isIntHex(const std::string& str) { enum class Status : std::uint8_t { START, HEX_0, HEX_X, DIGIT } state = Status::START; if (str.empty()) return false; std::string::const_iterator it = str.cbegin(); if ('+' == *it || '-' == *it) ++it; for (; it != str.cend(); ++it) { switch (state) { case Status::START: if (*it == '0') state = Status::HEX_0; else return false; break; case Status::HEX_0: if (*it == 'x' || *it == 'X') state = Status::HEX_X; else return false; break; case Status::HEX_X: if (isxdigit(static_cast<unsigned char>(*it))) state = Status::DIGIT; else return false; break; case Status::DIGIT: if (isxdigit(static_cast<unsigned char>(*it))) ; // state = Status::DIGIT; else return isValidIntegerSuffixIt(it,str.end()); break; } } return Status::DIGIT == state; } bool MathLib::isFloatHex(const std::string& str) { enum class Status : std::uint8_t { START, HEX_0, HEX_X, WHOLE_NUMBER_DIGIT, POINT, FRACTION, EXPONENT_P, EXPONENT_SIGN, EXPONENT_DIGITS, EXPONENT_SUFFIX } state = Status::START; if (str.empty()) return false; std::string::const_iterator it = str.cbegin(); if ('+' == *it || '-' == *it) ++it; for (; it != str.cend(); ++it) { switch (state) { case Status::START: if (*it == '0') state = Status::HEX_0; else return false; break; case Status::HEX_0: if (*it == 'x' || *it == 'X') state = Status::HEX_X; else return false; break; case Status::HEX_X: if (isxdigit(static_cast<unsigned char>(*it))) state = Status::WHOLE_NUMBER_DIGIT; else if (*it == '.') state = Status::POINT; else return false; break; case Status::WHOLE_NUMBER_DIGIT: if (isxdigit(static_cast<unsigned char>(*it))) ; // state = Status::WHOLE_NUMBER_DIGITS; else if (*it=='.') state = Status::FRACTION; else if (*it=='p' || *it=='P') state = Status::EXPONENT_P; else return false; break; case Status::POINT: case Status::FRACTION: if (isxdigit(static_cast<unsigned char>(*it))) state = Status::FRACTION; else if (*it == 'p' || *it == 'P') state = Status::EXPONENT_P; else return false; break; case Status::EXPONENT_P: if (isdigit(static_cast<unsigned char>(*it))) state = Status::EXPONENT_DIGITS; else if (*it == '+' || *it == '-') state = Status::EXPONENT_SIGN; else return false; break; case Status::EXPONENT_SIGN: if (isdigit(static_cast<unsigned char>(*it))) state = Status::EXPONENT_DIGITS; else return false; break; case Status::EXPONENT_DIGITS: if (isdigit(static_cast<unsigned char>(*it))) ; // state = Status::EXPONENT_DIGITS; else if (*it == 'f' || *it == 'F' || *it == 'l' || *it == 'L') state = Status::EXPONENT_SUFFIX; else return false; break; case Status::EXPONENT_SUFFIX: return false; } } return (Status::EXPONENT_DIGITS == state) || (Status::EXPONENT_SUFFIX == state); } /*! \brief Does the string represent a binary number? * In case leading or trailing white space is provided, the function * returns false. * Additional information can be found here: * http://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html * * \param str The string to check. In case the string is empty, the function returns false. * \return Return true in case a binary number is provided and false otherwise. **/ bool MathLib::isBin(const std::string& str) { enum class Status : std::uint8_t { START, GNU_BIN_PREFIX_0, GNU_BIN_PREFIX_B, DIGIT } state = Status::START; if (str.empty()) return false; std::string::const_iterator it = str.cbegin(); if ('+' == *it || '-' == *it) ++it; for (; it != str.cend(); ++it) { switch (state) { case Status::START: if (*it == '0') state = Status::GNU_BIN_PREFIX_0; else return false; break; case Status::GNU_BIN_PREFIX_0: if (*it == 'b' || *it == 'B') state = Status::GNU_BIN_PREFIX_B; else return false; break; case Status::GNU_BIN_PREFIX_B: if (*it == '0' || *it == '1') state = Status::DIGIT; else return false; break; case Status::DIGIT: if (*it == '0' || *it == '1') ; // state = Status::DIGIT; else return isValidIntegerSuffixIt(it,str.end()); break; } } return state == Status::DIGIT; } bool MathLib::isDec(const std::string & str) { enum class Status : std::uint8_t { START, DIGIT } state = Status::START; if (str.empty()) return false; std::string::const_iterator it = str.cbegin(); if ('+' == *it || '-' == *it) ++it; for (; it != str.cend(); ++it) { switch (state) { case Status::START: if (isdigit(static_cast<unsigned char>(*it))) state = Status::DIGIT; else return false; break; case Status::DIGIT: if (isdigit(static_cast<unsigned char>(*it))) state = Status::DIGIT; else return isValidIntegerSuffixIt(it,str.end()); break; } } return state == Status::DIGIT; } bool MathLib::isInt(const std::string & str) { return isDec(str) || isIntHex(str) || isOct(str) || isBin(str); } std::string MathLib::getSuffix(const std::string& value) { if (value.size() > 3 && value[value.size() - 3] == 'i' && value[value.size() - 2] == '6' && value[value.size() - 1] == '4') { if (value[value.size() - 4] == 'u') return "ULL"; return "LL"; } bool isUnsigned = false; unsigned int longState = 0; for (std::size_t i = 1U; i < value.size(); ++i) { const char c = value[value.size() - i]; if (c == 'u' || c == 'U') isUnsigned = true; else if (c == 'L' || c == 'l') longState++; else break; } if (longState == 0) return isUnsigned ? "U" : ""; if (longState == 1) return isUnsigned ? "UL" : "L"; if (longState == 2) return isUnsigned ? "ULL" : "LL"; return ""; } static std::string intsuffix(const std::string & first, const std::string & second) { const std::string suffix1 = MathLib::getSuffix(first); const std::string suffix2 = MathLib::getSuffix(second); if (suffix1 == "ULL" || suffix2 == "ULL") return "ULL"; if (suffix1 == "LL" || suffix2 == "LL") return "LL"; if (suffix1 == "UL" || suffix2 == "UL") return "UL"; if (suffix1 == "L" || suffix2 == "L") return "L"; if (suffix1 == "U" || suffix2 == "U") return "U"; return suffix1.empty() ? suffix2 : suffix1; } std::string MathLib::add(const std::string & first, const std::string & second) { #ifdef TEST_MATHLIB_VALUE return (value(first) + value(second)).str(); #else if (MathLib::isInt(first) && MathLib::isInt(second)) { return std::to_string(toBigNumber(first) + toBigNumber(second)) + intsuffix(first, second); } double d1 = toDoubleNumber(first); double d2 = toDoubleNumber(second); int count = 0; while (d1 > 100000.0 * d2 && toString(d1+d2)==first && ++count<5) d2 *= 10.0; while (d2 > 100000.0 * d1 && toString(d1+d2)==second && ++count<5) d1 *= 10.0; return toString(d1 + d2); #endif } std::string MathLib::subtract(const std::string &first, const std::string &second) { #ifdef TEST_MATHLIB_VALUE return (value(first) - value(second)).str(); #else if (MathLib::isInt(first) && MathLib::isInt(second)) { return std::to_string(toBigNumber(first) - toBigNumber(second)) + intsuffix(first, second); } if (first == second) return "0.0"; double d1 = toDoubleNumber(first); double d2 = toDoubleNumber(second); int count = 0; while (d1 > 100000.0 * d2 && toString(d1-d2)==first && ++count<5) d2 *= 10.0; while (d2 > 100000.0 * d1 && toString(d1-d2)==second && ++count<5) d1 *= 10.0; return toString(d1 - d2); #endif } std::string MathLib::divide(const std::string &first, const std::string &second) { #ifdef TEST_MATHLIB_VALUE return (value(first) / value(second)).str(); #else if (MathLib::isInt(first) && MathLib::isInt(second)) { const bigint a = toBigNumber(first); const bigint b = toBigNumber(second); if (b == 0) throw InternalError(nullptr, "Internal Error: Division by zero"); if (a == std::numeric_limits<bigint>::min() && std::abs(b)<=1) throw InternalError(nullptr, "Internal Error: Division overflow"); return std::to_string(toBigNumber(first) / b) + intsuffix(first, second); } if (isNullValue(second)) { if (isNullValue(first)) return "nan.0"; return isPositive(first) == isPositive(second) ? "inf.0" : "-inf.0"; } return toString(toDoubleNumber(first) / toDoubleNumber(second)); #endif } std::string MathLib::multiply(const std::string &first, const std::string &second) { #ifdef TEST_MATHLIB_VALUE return (value(first) * value(second)).str(); #else if (MathLib::isInt(first) && MathLib::isInt(second)) { return std::to_string(toBigNumber(first) * toBigNumber(second)) + intsuffix(first, second); } return toString(toDoubleNumber(first) * toDoubleNumber(second)); #endif } std::string MathLib::mod(const std::string &first, const std::string &second) { #ifdef TEST_MATHLIB_VALUE return (value(first) % value(second)).str(); #else if (MathLib::isInt(first) && MathLib::isInt(second)) { const bigint b = toBigNumber(second); if (b == 0) throw InternalError(nullptr, "Internal Error: Division by zero"); return std::to_string(toBigNumber(first) % b) + intsuffix(first, second); } return toString(std::fmod(toDoubleNumber(first),toDoubleNumber(second))); #endif } std::string MathLib::calculate(const std::string &first, const std::string &second, char action) { switch (action) { case '+': return MathLib::add(first, second); case '-': return MathLib::subtract(first, second); case '*': return MathLib::multiply(first, second); case '/': return MathLib::divide(first, second); case '%': return MathLib::mod(first, second); case '&': return std::to_string(MathLib::toBigNumber(first) & MathLib::toBigNumber(second)) + intsuffix(first, second); case '|': return std::to_string(MathLib::toBigNumber(first) | MathLib::toBigNumber(second)) + intsuffix(first, second); case '^': return std::to_string(MathLib::toBigNumber(first) ^ MathLib::toBigNumber(second)) + intsuffix(first, second); default: throw InternalError(nullptr, std::string("Unexpected action '") + action + "' in MathLib::calculate(). Please report this to Cppcheck developers."); } } std::string MathLib::sin(const std::string &tok) { return toString(std::sin(toDoubleNumber(tok))); } std::string MathLib::cos(const std::string &tok) { return toString(std::cos(toDoubleNumber(tok))); } std::string MathLib::tan(const std::string &tok) { return toString(std::tan(toDoubleNumber(tok))); } std::string MathLib::abs(const std::string &tok) { if (isNegative(tok)) return tok.substr(1, tok.length() - 1); return tok; } bool MathLib::isEqual(const std::string &first, const std::string &second) { // this conversion is needed for formatting // e.g. if first=0.1 and second=1.0E-1, the direct comparison of the strings would fail return toString(toDoubleNumber(first)) == toString(toDoubleNumber(second)); } bool MathLib::isNotEqual(const std::string &first, const std::string &second) { return !isEqual(first, second); } // cppcheck-suppress unusedFunction bool MathLib::isGreater(const std::string &first, const std::string &second) { return toDoubleNumber(first) > toDoubleNumber(second); } // cppcheck-suppress unusedFunction bool MathLib::isGreaterEqual(const std::string &first, const std::string &second) { return toDoubleNumber(first) >= toDoubleNumber(second); } // cppcheck-suppress unusedFunction bool MathLib::isLess(const std::string &first, const std::string &second) { return toDoubleNumber(first) < toDoubleNumber(second); } bool MathLib::isLessEqual(const std::string &first, const std::string &second) { return toDoubleNumber(first) <= toDoubleNumber(second); } /*! \brief Does the string represent the numerical value of 0? * In case leading or trailing white space is provided, the function * returns false. * Requirement for this function: * - This code is allowed to be slow because of simplicity of the code. * * \param[in] str The string to check. In case the string is empty, the function returns false. * \return Return true in case the string represents a numerical null value. **/ bool MathLib::isNullValue(const std::string &str) { if (str.empty() || (!std::isdigit(static_cast<unsigned char>(str[0])) && (str[0] != '.' && str[0] != '-' && str[0] != '+'))) return false; // Has to be a number if (!isInt(str) && !isFloat(str)) return false; const bool isHex = isIntHex(str) || isFloatHex(str); for (const char i : str) { if (std::isdigit(static_cast<unsigned char>(i)) && i != '0') // May not contain digits other than 0 return false; if (i == 'p' || i == 'P' || (!isHex && (i == 'E' || i == 'e'))) return true; if (isHex && isxdigit(i) && i != '0') return false; } return true; } bool MathLib::isOctalDigit(char c) { return (c >= '0' && c <= '7'); } MathLib::value operator+(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('+',v1,v2); } MathLib::value operator-(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('-',v1,v2); } MathLib::value operator*(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('*',v1,v2); } MathLib::value operator/(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('/',v1,v2); } MathLib::value operator%(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('%',v1,v2); } MathLib::value operator&(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('&',v1,v2); } MathLib::value operator|(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('|',v1,v2); } MathLib::value operator^(const MathLib::value &v1, const MathLib::value &v2) { return MathLib::value::calc('^',v1,v2); } MathLib::value operator<<(const MathLib::value &v1, const MathLib::value &v2) { return v1.shiftLeft(v2); } MathLib::value operator>>(const MathLib::value &v1, const MathLib::value &v2) { return v1.shiftRight(v2); }
43,379
C++
.cpp
1,217
27.433032
275
0.559614
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,160
checkexceptionsafety.cpp
danmar_cppcheck/lib/checkexceptionsafety.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkexceptionsafety.h" #include "errortypes.h" #include "library.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include <list> #include <set> #include <utility> #include <vector> //--------------------------------------------------------------------------- // Register CheckExceptionSafety.. namespace { CheckExceptionSafety instance; } static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE703(703U); // Improper Check or Handling of Exceptional Conditions static const CWE CWE480(480U); // Use of Incorrect Operator //--------------------------------------------------------------------------- void CheckExceptionSafety::destructors() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckExceptionSafety::destructors"); // warning const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); // Perform check.. for (const Scope * scope : symbolDatabase->functionScopes) { const Function * function = scope->function; if (!function) continue; // only looking for destructors if (function->type == Function::eDestructor) { // Inspect this destructor. for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { // Skip try blocks if (Token::simpleMatch(tok, "try {")) { tok = tok->linkAt(1); } // Skip uncaught exceptions else if (Token::simpleMatch(tok, "if ( ! std :: uncaught_exception ( ) ) {")) { tok = tok->linkAt(1); // end of if ( ... ) tok = tok->linkAt(1); // end of { ... } } // throw found within a destructor else if (tok->str() == "throw" && function->isNoExcept()) { destructorsError(tok, scope->className); break; } } } } } void CheckExceptionSafety::destructorsError(const Token * const tok, const std::string &className) { reportError(tok, Severity::warning, "exceptThrowInDestructor", "Class " + className + " is not safe, destructor throws exception\n" "The class " + className + " is not safe because its destructor " "throws an exception. If " + className + " is used and an exception " "is thrown that is caught in an outer scope the program will terminate.", CWE398, Certainty::normal); } void CheckExceptionSafety::deallocThrow() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckExceptionSafety::deallocThrow"); // warning const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); // Deallocate a global/member pointer and then throw exception // the pointer will be a dead pointer for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { // only looking for delete now if (tok->str() != "delete") continue; // Check if this is something similar with: "delete p;" tok = tok->next(); if (Token::simpleMatch(tok, "[ ]")) tok = tok->tokAt(2); if (!tok || tok == scope->bodyEnd) break; if (!Token::Match(tok, "%var% ;")) continue; // we only look for global variables const Variable *var = tok->variable(); if (!var || !(var->isGlobal() || var->isStatic())) continue; const unsigned int varid(tok->varId()); // Token where throw occurs const Token *throwToken = nullptr; // is there a throw after the deallocation? const Token* const end2 = tok->scope()->bodyEnd; for (const Token *tok2 = tok; tok2 != end2; tok2 = tok2->next()) { // Throw after delete -> Dead pointer if (tok2->str() == "throw") { if (printInconclusive) { // For inconclusive checking, throw directly. deallocThrowError(tok2, tok->str()); break; } throwToken = tok2; } // Variable is assigned -> Bail out else if (Token::Match(tok2, "%varid% =", varid)) { if (throwToken) // For non-inconclusive checking, wait until we find an assignment to it. Otherwise we assume it is safe to leave a dead pointer. deallocThrowError(throwToken, tok2->str()); break; } // Variable passed to function. Assume it becomes assigned -> Bail out else if (Token::Match(tok2, "[,(] &| %varid% [,)]", varid)) // TODO: No bailout if passed by value or as const reference break; } } } } void CheckExceptionSafety::deallocThrowError(const Token * const tok, const std::string &varname) { reportError(tok, Severity::warning, "exceptDeallocThrow", "Exception thrown in invalid state, '" + varname + "' points at deallocated memory.", CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // catch(const exception & err) // { // throw err; // <- should be just "throw;" // } //--------------------------------------------------------------------------- void CheckExceptionSafety::checkRethrowCopy() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("exceptRethrowCopy")) return; logChecker("CheckExceptionSafety::checkRethrowCopy"); // style const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eCatch) continue; const unsigned int varid = scope.bodyStart->tokAt(-2)->varId(); if (varid) { for (const Token* tok = scope.bodyStart->next(); tok && tok != scope.bodyEnd; tok = tok->next()) { if (Token::simpleMatch(tok, "catch (") && tok->linkAt(1) && tok->linkAt(1)->next()) { // Don't check inner catch - it is handled in another iteration of outer loop. tok = tok->linkAt(1)->linkAt(1); if (!tok) break; } else if (Token::Match(tok, "%varid% .", varid)) { const Token *parent = tok->astParent(); while (Token::simpleMatch(parent->astParent(), ".")) parent = parent->astParent(); if (Token::Match(parent->astParent(), "%assign%|++|--|(") && parent == parent->astParent()->astOperand1()) break; } else if (Token::Match(tok, "throw %varid% ;", varid)) rethrowCopyError(tok, tok->strAt(1)); } } } } void CheckExceptionSafety::rethrowCopyError(const Token * const tok, const std::string &varname) { reportError(tok, Severity::style, "exceptRethrowCopy", "Throwing a copy of the caught exception instead of rethrowing the original exception.\n" "Rethrowing an exception with 'throw " + varname + ";' creates an unnecessary copy of '" + varname + "'. " "To rethrow the caught exception without unnecessary copying or slicing, use a bare 'throw;'.", CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // try {} catch (std::exception err) {} <- Should be "std::exception& err" //--------------------------------------------------------------------------- void CheckExceptionSafety::checkCatchExceptionByValue() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("catchExceptionByValue")) return; logChecker("CheckExceptionSafety::checkCatchExceptionByValue"); // style const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eCatch) continue; // Find a pass-by-value declaration in the catch(), excluding basic types // e.g. catch (std::exception err) const Variable *var = scope.bodyStart->tokAt(-2)->variable(); if (var && var->isClass() && !var->isPointer() && !var->isReference()) catchExceptionByValueError(scope.classDef); } } void CheckExceptionSafety::catchExceptionByValueError(const Token *tok) { reportError(tok, Severity::style, "catchExceptionByValue", "Exception should be caught by reference.\n" "The exception is caught by value. It could be caught " "as a (const) reference which is usually recommended in C++.", CWE398, Certainty::normal); } static const Token * functionThrowsRecursive(const Function * function, std::set<const Function *> & recursive) { // check for recursion and bail if found if (!recursive.insert(function).second) return nullptr; if (!function->functionScope) return nullptr; for (const Token *tok = function->functionScope->bodyStart->next(); tok != function->functionScope->bodyEnd; tok = tok->next()) { if (Token::simpleMatch(tok, "try {")) tok = tok->linkAt(1); // skip till start of catch clauses if (tok->str() == "throw") return tok; if (tok->function()) { const Function * called = tok->function(); // check if called function has an exception specification if (called->isThrow() && called->throwArg) return tok; if (called->isNoExcept() && called->noexceptArg && called->noexceptArg->str() != "true") return tok; if (functionThrowsRecursive(called, recursive)) return tok; } } return nullptr; } static const Token * functionThrows(const Function * function) { std::set<const Function *> recursive; return functionThrowsRecursive(function, recursive); } //-------------------------------------------------------------------------- // void func() noexcept { throw x; } // void func() throw() { throw x; } // void func() __attribute__((nothrow)); void func() { throw x; } //-------------------------------------------------------------------------- void CheckExceptionSafety::nothrowThrows() { logChecker("CheckExceptionSafety::nothrowThrows"); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { const Function* function = scope->function; if (!function) continue; // check noexcept and noexcept(true) functions if (function->isNoExcept()) { const Token *throws = functionThrows(function); if (throws) noexceptThrowError(throws); } // check throw() functions else if (function->isThrow() && !function->throwArg) { const Token *throws = functionThrows(function); if (throws) noexceptThrowError(throws); } // check __attribute__((nothrow)) or __declspec(nothrow) functions else if (function->isAttributeNothrow()) { const Token *throws = functionThrows(function); if (throws) noexceptThrowError(throws); } } } void CheckExceptionSafety::noexceptThrowError(const Token * const tok) { reportError(tok, Severity::error, "throwInNoexceptFunction", "Exception thrown in function declared not to throw exceptions.", CWE398, Certainty::normal); } //-------------------------------------------------------------------------- // void func() { functionWithExceptionSpecification(); } //-------------------------------------------------------------------------- void CheckExceptionSafety::unhandledExceptionSpecification() { if ((!mSettings->severity.isEnabled(Severity::style) || !mSettings->certainty.isEnabled(Certainty::inconclusive)) && !mSettings->isPremiumEnabled("unhandledExceptionSpecification")) return; logChecker("CheckExceptionSafety::unhandledExceptionSpecification"); // style,inconclusive const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { // only check functions without exception specification if (scope->function && !scope->function->isThrow() && !mSettings->library.isentrypoint(scope->className)) { for (const Token *tok = scope->function->functionScope->bodyStart->next(); tok != scope->function->functionScope->bodyEnd; tok = tok->next()) { if (tok->str() == "try") break; if (tok->function()) { const Function * called = tok->function(); // check if called function has an exception specification if (called->isThrow() && called->throwArg) { unhandledExceptionSpecificationError(tok, called->tokenDef, scope->function->name()); break; } } } } } } void CheckExceptionSafety::unhandledExceptionSpecificationError(const Token * const tok1, const Token * const tok2, const std::string & funcname) { const std::string str1(tok1 ? tok1->str() : "foo"); const std::list<const Token*> locationList = { tok1, tok2 }; reportError(locationList, Severity::style, "unhandledExceptionSpecification", "Unhandled exception specification when calling function " + str1 + "().\n" "Unhandled exception specification when calling function " + str1 + "(). " "Either use a try/catch around the function call, or add a exception specification for " + funcname + "() also.", CWE703, Certainty::inconclusive); } //-------------------------------------------------------------------------- // 7.6.18.4 If no exception is presently being handled, evaluating a throw-expression with no operand calls std​::​​terminate(). //-------------------------------------------------------------------------- void CheckExceptionSafety::rethrowNoCurrentException() { logChecker("CheckExceptionSafety::rethrowNoCurrentException"); const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { const Function* function = scope->function; if (!function) continue; // Rethrow can be used in 'exception dispatcher' idiom which is FP in such case // https://isocpp.org/wiki/faq/exceptions#throw-without-an-object // We check the beginning of the function with idiom pattern if (Token::simpleMatch(function->functionScope->bodyStart->next(), "try { throw ; } catch (")) continue; for (const Token *tok = function->functionScope->bodyStart->next(); tok != function->functionScope->bodyEnd; tok = tok->next()) { if (Token::simpleMatch(tok, "catch (")) { tok = tok->linkAt(1); // skip catch argument if (Token::simpleMatch(tok, ") {")) tok = tok->linkAt(1); // skip catch scope else break; } if (Token::simpleMatch(tok, "throw ;")) { rethrowNoCurrentExceptionError(tok); } } } } void CheckExceptionSafety::rethrowNoCurrentExceptionError(const Token *tok) { reportError(tok, Severity::error, "rethrowNoCurrentException", "Rethrowing current exception with 'throw;', it seems there is no current exception to rethrow." " If there is no current exception this calls std::terminate()." " More: https://isocpp.org/wiki/faq/exceptions#throw-without-an-object", CWE480, Certainty::normal); }
17,451
C++
.cpp
349
40.690544
180
0.579185
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,161
vf_settokenvalue.cpp
danmar_cppcheck/lib/vf_settokenvalue.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_settokenvalue.h" #include "astutils.h" #include "calculate.h" #include "config.h" #include "library.h" #include "mathlib.h" #include "platform.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "utils.h" #include "valueflow.h" #include "vfvalue.h" #include "vf_common.h" #include <algorithm> #include <climits> #include <cstddef> #include <functional> #include <list> #include <string> #include <unordered_map> #include <unordered_set> #include <utility> #include <vector> namespace ValueFlow { static Library::Container::Yield getContainerYield(Token* tok, const Settings& settings, Token*& parent) { if (Token::Match(tok, ". %name% (") && tok->astParent() == tok->tokAt(2) && tok->astOperand1() && tok->astOperand1()->valueType()) { const Library::Container* c = getLibraryContainer(tok->astOperand1()); parent = tok->astParent(); return c ? c->getYield(tok->strAt(1)) : Library::Container::Yield::NO_YIELD; } if (Token::Match(tok->previous(), "%name% (")) { parent = tok; if (const Library::Function* f = settings.library.getFunction(tok->previous())) { return f->containerYield; } } return Library::Container::Yield::NO_YIELD; } static Value truncateImplicitConversion(Token* parent, const Value& value, const Settings& settings) { if (!value.isIntValue() && !value.isFloatValue()) return value; if (!parent) return value; if (!parent->isBinaryOp()) return value; if (!parent->isConstOp()) return value; if (!astIsIntegral(parent->astOperand1(), false)) return value; if (!astIsIntegral(parent->astOperand2(), false)) return value; const ValueType* vt1 = parent->astOperand1()->valueType(); const ValueType* vt2 = parent->astOperand2()->valueType(); // If the sign is the same there is no truncation if (vt1->sign == vt2->sign) return value; const size_t n1 = getSizeOf(*vt1, settings); const size_t n2 = getSizeOf(*vt2, settings); ValueType::Sign sign = ValueType::Sign::UNSIGNED; if (n1 < n2) sign = vt2->sign; else if (n1 > n2) sign = vt1->sign; Value v = castValue(value, sign, std::max(n1, n2) * 8); v.wideintvalue = value.intvalue; return v; } static const Token *getCastTypeStartToken(const Token *parent, const Settings& settings) { // TODO: This might be a generic utility function? if (!Token::Match(parent, "{|(")) return nullptr; // Functional cast if (parent->isBinaryOp() && Token::Match(parent->astOperand1(), "%type% (|{") && parent->astOperand1()->tokType() == Token::eType && astIsPrimitive(parent)) return parent->astOperand1(); if (parent->str() != "(") return nullptr; if (!parent->astOperand2() && Token::Match(parent, "( %name%|::")) { const Token* ftok = parent->next(); if (ftok->isStandardType()) return ftok; if (Token::simpleMatch(ftok, "::")) ftok = ftok->next(); while (Token::Match(ftok, "%name% ::")) ftok = ftok->tokAt(2); if (settings.library.isNotLibraryFunction(ftok)) return parent->next(); } if (parent->astOperand2() && Token::Match(parent->astOperand1(), "const_cast|dynamic_cast|reinterpret_cast|static_cast <")) return parent->astOperand1()->tokAt(2); return nullptr; } static bool isNumeric(const Value& value) { return value.isIntValue() || value.isFloatValue(); } static void setTokenValueCast(Token *parent, const ValueType &valueType, const Value &value, const Settings &settings) { if (valueType.pointer || value.isImpossible()) setTokenValue(parent,value,settings); else if (valueType.type == ValueType::Type::CHAR) setTokenValue(parent, castValue(value, valueType.sign, settings.platform.char_bit), settings); else if (valueType.type == ValueType::Type::SHORT) setTokenValue(parent, castValue(value, valueType.sign, settings.platform.short_bit), settings); else if (valueType.type == ValueType::Type::INT) setTokenValue(parent, castValue(value, valueType.sign, settings.platform.int_bit), settings); else if (valueType.type == ValueType::Type::LONG) setTokenValue(parent, castValue(value, valueType.sign, settings.platform.long_bit), settings); else if (valueType.type == ValueType::Type::LONGLONG) setTokenValue(parent, castValue(value, valueType.sign, settings.platform.long_long_bit), settings); else if (valueType.isFloat() && isNumeric(value)) { Value floatValue = value; floatValue.valueType = Value::ValueType::FLOAT; if (value.isIntValue()) floatValue.floatValue = value.intvalue; setTokenValue(parent, std::move(floatValue), settings); } else if (value.isIntValue()) { const long long charMax = settings.platform.signedCharMax(); const long long charMin = settings.platform.signedCharMin(); if (charMin <= value.intvalue && value.intvalue <= charMax) { // unknown type, but value is small so there should be no truncation etc setTokenValue(parent,value,settings); } } } // does the operation cause a loss of information? static bool isNonInvertibleOperation(const Token* tok) { return !Token::Match(tok, "+|-"); } static bool isComputableValue(const Token* parent, const Value& value) { const bool noninvertible = isNonInvertibleOperation(parent); if (noninvertible && value.isImpossible()) return false; if (!value.isIntValue() && !value.isFloatValue() && !value.isTokValue() && !value.isIteratorValue()) return false; if (value.isIteratorValue() && !Token::Match(parent, "+|-")) return false; if (value.isTokValue() && (!parent->isComparisonOp() || !Token::Match(value.tokvalue, "{|%str%"))) return false; return true; } /** Set token value for cast */ static bool isCompatibleValueTypes(Value::ValueType x, Value::ValueType y) { static const std::unordered_map<Value::ValueType, std::unordered_set<Value::ValueType, EnumClassHash>, EnumClassHash> compatibleTypes = { {Value::ValueType::INT, {Value::ValueType::FLOAT, Value::ValueType::SYMBOLIC, Value::ValueType::TOK}}, {Value::ValueType::FLOAT, {Value::ValueType::INT}}, {Value::ValueType::TOK, {Value::ValueType::INT}}, {Value::ValueType::ITERATOR_START, {Value::ValueType::INT}}, {Value::ValueType::ITERATOR_END, {Value::ValueType::INT}}, }; if (x == y) return true; auto it = compatibleTypes.find(x); if (it == compatibleTypes.end()) return false; return it->second.count(y) > 0; } static bool isCompatibleValues(const Value& value1, const Value& value2) { if (value1.isSymbolicValue() && value2.isSymbolicValue() && value1.tokvalue->exprId() != value2.tokvalue->exprId()) return false; if (!isCompatibleValueTypes(value1.valueType, value2.valueType)) return false; if (value1.isKnown() || value2.isKnown()) return true; if (value1.isImpossible() || value2.isImpossible()) return false; if (value1.varId == 0 || value2.varId == 0) return true; if (value1.varId == value2.varId && value1.varvalue == value2.varvalue && value1.isIntValue() && value2.isIntValue()) return true; return false; } /** set ValueFlow value and perform calculations if possible */ void setTokenValue(Token* tok, Value value, const Settings& settings, SourceLocation loc) { // Skip setting values that are too big since its ambiguous if (!value.isImpossible() && value.isIntValue() && value.intvalue < 0 && astIsUnsigned(tok) && getSizeOf(*tok->valueType(), settings) >= sizeof(MathLib::bigint)) return; if (!value.isImpossible() && value.isIntValue()) value = truncateImplicitConversion(tok->astParent(), value, settings); if (settings.debugnormal) setSourceLocation(value, loc, tok); if (!tok->addValue(value)) return; if (value.path < 0) return; Token *parent = tok->astParent(); if (!parent) return; if (Token::simpleMatch(parent, ",") && !parent->isInitComma() && astIsRHS(tok)) { const Token* callParent = findParent(parent, [](const Token* p) { return !Token::simpleMatch(p, ","); }); // Ensure that the comma isn't a function call if (!callParent || (!Token::Match(callParent->previous(), "%name%|> (") && !Token::simpleMatch(callParent, "{") && (!Token::Match(callParent, "( %name%") || settings.library.isNotLibraryFunction(callParent->next())) && !(callParent->str() == "(" && (Token::simpleMatch(callParent->astOperand1(), "*") || Token::Match(callParent->astOperand1(), "%name%|("))))) { setTokenValue(parent, std::move(value), settings); return; } } if (Token::simpleMatch(parent, "=") && astIsRHS(tok)) { setTokenValue(parent, value, settings); if (!value.isUninitValue()) return; } if (value.isContainerSizeValue() && astIsContainer(tok)) { // .empty, .size, +"abc", +'a' if (Token::Match(parent, "+|==|!=") && parent->astOperand1() && parent->astOperand2()) { for (const Value &value1 : parent->astOperand1()->values()) { if (value1.isImpossible()) continue; for (const Value &value2 : parent->astOperand2()->values()) { if (value2.isImpossible()) continue; if (value1.path != value2.path) continue; Value result; if (Token::Match(parent, "%comp%")) result.valueType = Value::ValueType::INT; else result.valueType = Value::ValueType::CONTAINER_SIZE; if (value1.isContainerSizeValue() && value2.isContainerSizeValue()) result.intvalue = calculate(parent->str(), value1.intvalue, value2.intvalue); else if (value1.isContainerSizeValue() && value2.isTokValue() && value2.tokvalue->tokType() == Token::eString) result.intvalue = calculate(parent->str(), value1.intvalue, MathLib::bigint(Token::getStrLength(value2.tokvalue))); else if (value2.isContainerSizeValue() && value1.isTokValue() && value1.tokvalue->tokType() == Token::eString) result.intvalue = calculate(parent->str(), MathLib::bigint(Token::getStrLength(value1.tokvalue)), value2.intvalue); else continue; combineValueProperties(value1, value2, result); if (Token::simpleMatch(parent, "==") && result.intvalue) continue; if (Token::simpleMatch(parent, "!=") && !result.intvalue) continue; setTokenValue(parent, std::move(result), settings); } } } Token* next = nullptr; const Library::Container::Yield yields = getContainerYield(parent, settings, next); if (yields == Library::Container::Yield::SIZE) { Value v(value); v.valueType = Value::ValueType::INT; setTokenValue(next, std::move(v), settings); } else if (yields == Library::Container::Yield::EMPTY) { Value v(value); v.valueType = Value::ValueType::INT; v.bound = Value::Bound::Point; if (value.isImpossible()) { if (value.intvalue == 0) v.setKnown(); else if ((value.bound == Value::Bound::Upper && value.intvalue > 0) || (value.bound == Value::Bound::Lower && value.intvalue < 0)) { v.intvalue = 0; v.setKnown(); } else v.setPossible(); } else { v.intvalue = !v.intvalue; } setTokenValue(next, std::move(v), settings); } return; } if (value.isLifetimeValue()) { if (!isLifetimeBorrowed(parent, settings)) return; if (value.lifetimeKind == Value::LifetimeKind::Iterator && astIsIterator(parent)) { setTokenValue(parent,std::move(value),settings); } else if (astIsPointer(tok) && astIsPointer(parent) && !parent->isUnaryOp("*") && (parent->isArithmeticalOp() || parent->isCast())) { setTokenValue(parent,std::move(value),settings); } return; } if (value.isUninitValue()) { if (Token::Match(tok, ". %var%")) setTokenValue(tok->next(), value, settings); if (parent->isCast()) { setTokenValue(parent, std::move(value), settings); return; } Value pvalue = value; if (!value.subexpressions.empty() && Token::Match(parent, ". %var%")) { if (contains(value.subexpressions, parent->strAt(1))) pvalue.subexpressions.clear(); else return; } if (parent->isUnaryOp("&")) { pvalue.indirect++; setTokenValue(parent, std::move(pvalue), settings); } else if (Token::Match(parent, ". %var%") && parent->astOperand1() == tok && parent->astOperand2()) { if (parent->originalName() == "->" && pvalue.indirect > 0) pvalue.indirect--; setTokenValue(parent->astOperand2(), std::move(pvalue), settings); } else if (Token::Match(parent->astParent(), ". %var%") && parent->astParent()->astOperand1() == parent) { if (parent->astParent()->originalName() == "->" && pvalue.indirect > 0) pvalue.indirect--; setTokenValue(parent->astParent()->astOperand2(), std::move(pvalue), settings); } else if (parent->isUnaryOp("*") && pvalue.indirect > 0) { pvalue.indirect--; setTokenValue(parent, std::move(pvalue), settings); } return; } // cast.. if (const Token *castType = getCastTypeStartToken(parent, settings)) { if (contains({Value::ValueType::INT, Value::ValueType::SYMBOLIC}, value.valueType) && Token::simpleMatch(parent->astOperand1(), "dynamic_cast")) return; const ValueType &valueType = ValueType::parseDecl(castType, settings); if (value.isImpossible() && value.isIntValue() && value.intvalue < 0 && astIsUnsigned(tok) && valueType.sign == ValueType::SIGNED && tok->valueType() && getSizeOf(*tok->valueType(), settings) >= getSizeOf(valueType, settings)) return; setTokenValueCast(parent, valueType, value, settings); } else if (parent->str() == ":") { setTokenValue(parent,std::move(value),settings); } else if (parent->str() == "?" && tok->str() == ":" && tok == parent->astOperand2() && parent->astOperand1()) { // is condition always true/false? if (parent->astOperand1()->hasKnownValue()) { const Value &condvalue = parent->astOperand1()->values().front(); const bool cond(condvalue.isTokValue() || (condvalue.isIntValue() && condvalue.intvalue != 0)); if (cond && !tok->astOperand1()) { // true condition, no second operator setTokenValue(parent, condvalue, settings); } else { const Token *op = cond ? tok->astOperand1() : tok->astOperand2(); if (!op) // #7769 segmentation fault at setTokenValue() return; const std::list<Value> &values = op->values(); if (std::find(values.cbegin(), values.cend(), value) != values.cend()) setTokenValue(parent, std::move(value), settings); } } else if (!value.isImpossible()) { // is condition only depending on 1 variable? // cppcheck-suppress[variableScope] #8541 nonneg int varId = 0; bool ret = false; visitAstNodes(parent->astOperand1(), [&](const Token *t) { if (t->varId()) { if (varId > 0 || value.varId != 0) ret = true; varId = t->varId(); } else if (t->str() == "(" && Token::Match(t->previous(), "%name%")) ret = true; // function call return ret ? ChildrenToVisit::done : ChildrenToVisit::op1_and_op2; }); if (ret) return; Value v(std::move(value)); v.conditional = true; v.changeKnownToPossible(); setTokenValue(parent, std::move(v), settings); } } else if (parent->str() == "?" && value.isIntValue() && tok == parent->astOperand1() && value.isKnown() && parent->astOperand2() && parent->astOperand2()->astOperand1() && parent->astOperand2()->astOperand2()) { const std::list<Value> &values = (value.intvalue == 0 ? parent->astOperand2()->astOperand2()->values() : parent->astOperand2()->astOperand1()->values()); for (const Value &v : values) setTokenValue(parent, v, settings); } // Offset of non null pointer is not null also else if (astIsPointer(tok) && Token::Match(parent, "+|-") && (parent->astOperand2() == nullptr || !astIsPointer(parent->astOperand2())) && value.isIntValue() && value.isImpossible() && value.intvalue == 0) { setTokenValue(parent, std::move(value), settings); } // Calculations.. else if ((parent->isArithmeticalOp() || parent->isComparisonOp() || (parent->tokType() == Token::eBitOp) || (parent->tokType() == Token::eLogicalOp)) && parent->astOperand1() && parent->astOperand2()) { const bool noninvertible = isNonInvertibleOperation(parent); // Skip operators with impossible values that are not invertible if (noninvertible && value.isImpossible()) return; // known result when a operand is 0. if (Token::Match(parent, "[&*]") && astIsIntegral(parent, true) && value.isKnown() && value.isIntValue() && value.intvalue == 0) { setTokenValue(parent, std::move(value), settings); return; } // known result when a operand is true. if (Token::simpleMatch(parent, "&&") && value.isKnown() && value.isIntValue() && value.intvalue==0) { setTokenValue(parent, std::move(value), settings); return; } // known result when a operand is false. if (Token::simpleMatch(parent, "||") && value.isKnown() && value.isIntValue() && value.intvalue!=0) { setTokenValue(parent, std::move(value), settings); return; } for (const Value &value1 : parent->astOperand1()->values()) { if (!isComputableValue(parent, value1)) continue; for (const Value &value2 : parent->astOperand2()->values()) { if (value1.path != value2.path) continue; if (!isComputableValue(parent, value2)) continue; if (value1.isIteratorValue() && value2.isIteratorValue()) continue; if (!isCompatibleValues(value1, value2)) continue; Value result(0); combineValueProperties(value1, value2, result); if (astIsFloat(parent, false)) { if (!result.isIntValue() && !result.isFloatValue()) continue; result.valueType = Value::ValueType::FLOAT; } const double floatValue1 = value1.isFloatValue() ? value1.floatValue : value1.intvalue; const double floatValue2 = value2.isFloatValue() ? value2.floatValue : value2.intvalue; const auto intValue1 = [&]() -> MathLib::bigint { return value1.isFloatValue() ? static_cast<MathLib::bigint>(value1.floatValue) : value1.intvalue; }; const auto intValue2 = [&]() -> MathLib::bigint { return value2.isFloatValue() ? static_cast<MathLib::bigint>(value2.floatValue) : value2.intvalue; }; if ((value1.isFloatValue() || value2.isFloatValue()) && Token::Match(parent, "&|^|%|<<|>>|==|!=|%or%")) continue; if (Token::Match(parent, "==|!=")) { if ((value1.isIntValue() && value2.isTokValue()) || (value1.isTokValue() && value2.isIntValue())) { if (parent->str() == "==") result.intvalue = 0; else if (parent->str() == "!=") result.intvalue = 1; } else if (value1.isIntValue() && value2.isIntValue()) { bool error = false; result.intvalue = calculate(parent->str(), intValue1(), intValue2(), &error); if (error) continue; } else if (value1.isTokValue() && value2.isTokValue() && (astIsContainer(parent->astOperand1()) || astIsContainer(parent->astOperand2()))) { const Token* tok1 = value1.tokvalue; const Token* tok2 = value2.tokvalue; bool equal = false; if (Token::Match(tok1, "%str%") && Token::Match(tok2, "%str%")) { equal = tok1->str() == tok2->str(); } else if (Token::simpleMatch(tok1, "{") && Token::simpleMatch(tok2, "{")) { std::vector<const Token*> args1 = getArguments(tok1); std::vector<const Token*> args2 = getArguments(tok2); if (args1.size() == args2.size()) { if (!std::all_of(args1.begin(), args1.end(), std::mem_fn(&Token::hasKnownIntValue))) continue; if (!std::all_of(args2.begin(), args2.end(), std::mem_fn(&Token::hasKnownIntValue))) continue; equal = std::equal(args1.begin(), args1.end(), args2.begin(), [&](const Token* atok, const Token* btok) { return atok->values().front().intvalue == btok->values().front().intvalue; }); } else { equal = false; } } else { continue; } result.intvalue = parent->str() == "==" ? equal : !equal; } else { continue; } setTokenValue(parent, std::move(result), settings); } else if (Token::Match(parent, "%op%")) { if (Token::Match(parent, "%comp%")) { if (!result.isFloatValue() && !value1.isIntValue() && !value2.isIntValue()) continue; } else { if (value1.isTokValue() || value2.isTokValue()) break; } bool error = false; if (result.isFloatValue()) { result.floatValue = calculate(parent->str(), floatValue1, floatValue2, &error); } else { result.intvalue = calculate(parent->str(), intValue1(), intValue2(), &error); } if (error) continue; // If the bound comes from the second value then invert the bound when subtracting if (Token::simpleMatch(parent, "-") && value2.bound == result.bound && value2.bound != Value::Bound::Point) result.invertBound(); setTokenValue(parent, std::move(result), settings); } } } } // ! else if (parent->str() == "!") { for (const Value &val : tok->values()) { if (!val.isIntValue()) continue; if (val.isImpossible() && val.intvalue != 0) continue; Value v(val); if (val.isImpossible()) v.setKnown(); else v.intvalue = !v.intvalue; setTokenValue(parent, std::move(v), settings); } } // ~ else if (parent->str() == "~") { for (const Value &val : tok->values()) { if (!val.isIntValue()) continue; Value v(val); v.intvalue = ~v.intvalue; int bits = 0; if (tok->valueType() && tok->valueType()->sign == ValueType::Sign::UNSIGNED && tok->valueType()->pointer == 0) { if (tok->valueType()->type == ValueType::Type::INT) bits = settings.platform.int_bit; else if (tok->valueType()->type == ValueType::Type::LONG) bits = settings.platform.long_bit; } if (bits > 0 && bits < MathLib::bigint_bits) v.intvalue &= (((MathLib::biguint)1)<<bits) - 1; setTokenValue(parent, std::move(v), settings); } } // unary minus else if (parent->isUnaryOp("-")) { for (const Value &val : tok->values()) { if (!val.isIntValue() && !val.isFloatValue()) continue; Value v(val); if (v.isIntValue()) { if (v.intvalue == LLONG_MIN) // Value can't be inverted continue; v.intvalue = -v.intvalue; } else v.floatValue = -v.floatValue; v.invertBound(); setTokenValue(parent, std::move(v), settings); } } // increment else if (parent->str() == "++") { for (const Value &val : tok->values()) { if (!val.isIntValue() && !val.isFloatValue() && !val.isSymbolicValue()) continue; Value v(val); if (parent == tok->previous()) { if (v.isIntValue() || v.isSymbolicValue()) { const ValueType *dst = tok->valueType(); if (dst) { const size_t sz = ValueFlow::getSizeOf(*dst, settings); long long newvalue = ValueFlow::truncateIntValue(v.intvalue + 1, sz, dst->sign); if (v.bound != ValueFlow::Value::Bound::Point) { if (newvalue < v.intvalue) { v.invertBound(); newvalue -= 2; } } v.intvalue = newvalue; } else { v.intvalue = v.intvalue + 1; } } else v.floatValue = v.floatValue + 1.0; } setTokenValue(parent, std::move(v), settings); } } // decrement else if (parent->str() == "--") { for (const Value &val : tok->values()) { if (!val.isIntValue() && !val.isFloatValue() && !val.isSymbolicValue()) continue; Value v(val); if (parent == tok->previous()) { if (v.isIntValue() || v.isSymbolicValue()) { const ValueType *dst = tok->valueType(); if (dst) { const size_t sz = ValueFlow::getSizeOf(*dst, settings); long long newvalue = ValueFlow::truncateIntValue(v.intvalue - 1, sz, dst->sign); if (v.bound != ValueFlow::Value::Bound::Point) { if (newvalue > v.intvalue) { v.invertBound(); newvalue += 2; } } v.intvalue = newvalue; } else { v.intvalue = v.intvalue - 1; } } else v.floatValue = v.floatValue - 1.0; } setTokenValue(parent, std::move(v), settings); } } // C++ init else if (parent->str() == "{" && Token::simpleMatch(parent->previous(), "= {") && Token::simpleMatch(parent->link(), "} ;")) { const Token* lhs = parent->previous()->astOperand1(); if (lhs && lhs->valueType()) { if (lhs->valueType()->isIntegral() || lhs->valueType()->isFloat() || (lhs->valueType()->pointer > 0 && value.isIntValue())) { setTokenValue(parent, std::move(value), settings); } } } else if (Token::Match(parent, ":: %name%") && parent->astOperand2() == tok) { setTokenValue(parent, std::move(value), settings); } // Calling std::size or std::empty on an array else if (value.isTokValue() && Token::simpleMatch(value.tokvalue, "{") && tok->variable() && tok->variable()->isArray() && Token::Match(parent->previous(), "%name% (") && astIsRHS(tok)) { std::vector<const Token*> args = getArguments(value.tokvalue); if (const Library::Function* f = settings.library.getFunction(parent->previous())) { if (f->containerYield == Library::Container::Yield::SIZE) { Value v(std::move(value)); v.valueType = Value::ValueType::INT; v.intvalue = args.size(); setTokenValue(parent, std::move(v), settings); } else if (f->containerYield == Library::Container::Yield::EMPTY) { Value v(std::move(value)); v.intvalue = args.empty(); v.valueType = Value::ValueType::INT; setTokenValue(parent, std::move(v), settings); } } } } }
34,391
C++
.cpp
676
34.474852
174
0.496064
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,162
vf_enumvalue.cpp
danmar_cppcheck/lib/vf_enumvalue.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_enumvalue.h" #include "mathlib.h" #include "symboldatabase.h" #include "token.h" #include "valueflow.h" #include "vfvalue.h" #include <list> #include <vector> namespace ValueFlow { void analyzeEnumValue(SymbolDatabase & symboldatabase, const Settings & settings) { for (Scope & scope : symboldatabase.scopeList) { if (scope.type != Scope::eEnum) continue; MathLib::bigint value = 0; bool prev_enum_is_known = true; for (Enumerator & enumerator : scope.enumeratorList) { if (enumerator.start) { auto* rhs = const_cast<Token*>(enumerator.start->previous()->astOperand2()); valueFlowConstantFoldAST(rhs, settings); if (rhs && rhs->hasKnownIntValue()) { enumerator.value = rhs->values().front().intvalue; enumerator.value_known = true; value = enumerator.value + 1; prev_enum_is_known = true; } else prev_enum_is_known = false; } else if (prev_enum_is_known) { enumerator.value = value++; enumerator.value_known = true; } } } } }
2,086
C++
.cpp
53
30.566038
96
0.608481
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,163
tokenlist.cpp
danmar_cppcheck/lib/tokenlist.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "tokenlist.h" #include "astutils.h" #include "errorlogger.h" #include "errortypes.h" #include "keywords.h" #include "library.h" #include "path.h" #include "platform.h" #include "settings.h" #include "standards.h" #include "token.h" #include <cctype> #include <cstdint> #include <exception> #include <functional> #include <iostream> #include <utility> #include <set> #include <stack> #include <unordered_set> #include <simplecpp.h> //#define N_ASSERT_LANG #ifndef N_ASSERT_LANG #include <cassert> #define ASSERT_LANG(x) assert(x) #else #define ASSERT_LANG(x) #endif // How many compileExpression recursions are allowed? // For practical code this could be endless. But in some special torture test // there needs to be a limit. static constexpr int AST_MAX_DEPTH = 150; TokenList::TokenList(const Settings* settings) : mTokensFrontBack(*this) , mSettings(settings) { if (mSettings && (mSettings->enforcedLang != Standards::Language::None)) { mLang = mSettings->enforcedLang; } } TokenList::~TokenList() { deallocateTokens(); } //--------------------------------------------------------------------------- const std::string& TokenList::getSourceFilePath() const { if (getFiles().empty()) { return emptyString; } return getFiles()[0]; } //--------------------------------------------------------------------------- // Deallocate lists.. void TokenList::deallocateTokens() { deleteTokens(mTokensFrontBack.front); mTokensFrontBack.front = nullptr; mTokensFrontBack.back = nullptr; mFiles.clear(); } void TokenList::determineCppC() { // only try to determine if it wasn't enforced if (mLang == Standards::Language::None) { ASSERT_LANG(!getSourceFilePath().empty()); mLang = Path::identify(getSourceFilePath(), mSettings ? mSettings->cppHeaderProbe : false); // TODO: cannot enable assert as this might occur for unknown extensions //ASSERT_LANG(mLang != Standards::Language::None); if (mLang == Standards::Language::None) { // TODO: should default to C instead like we do for headers // default to C++ mLang = Standards::Language::CPP; } } } int TokenList::appendFileIfNew(std::string fileName) { // Has this file been tokenized already? for (int i = 0; i < mFiles.size(); ++i) if (Path::sameFileName(mFiles[i], fileName)) return i; // The "mFiles" vector remembers what files have been tokenized.. mFiles.push_back(std::move(fileName)); // Update mIsC and mIsCpp properties if (mFiles.size() == 1) { // Update only useful if first file added to _files determineCppC(); } return mFiles.size() - 1; } void TokenList::clangSetOrigFiles() { mOrigFiles = mFiles; } void TokenList::deleteTokens(Token *tok) { while (tok) { Token *next = tok->next(); delete tok; tok = next; } } //--------------------------------------------------------------------------- // add a token. //--------------------------------------------------------------------------- void TokenList::addtoken(const std::string& str, const nonneg int lineno, const nonneg int column, const nonneg int fileno, bool split) { if (str.empty()) return; // If token contains # characters, split it up if (split) { size_t begin = 0; size_t end = 0; while ((end = str.find("##", begin)) != std::string::npos) { addtoken(str.substr(begin, end - begin), lineno, fileno, false); addtoken("##", lineno, column, fileno, false); begin = end+2; } if (begin != 0) { addtoken(str.substr(begin), lineno, column, fileno, false); return; } } if (mTokensFrontBack.back) { mTokensFrontBack.back->insertToken(str); } else { mTokensFrontBack.front = new Token(mTokensFrontBack); mTokensFrontBack.back = mTokensFrontBack.front; mTokensFrontBack.back->str(str); } mTokensFrontBack.back->linenr(lineno); mTokensFrontBack.back->column(column); mTokensFrontBack.back->fileIndex(fileno); } void TokenList::addtoken(const std::string& str, const Token *locationTok) { if (str.empty()) return; if (mTokensFrontBack.back) { mTokensFrontBack.back->insertToken(str); } else { mTokensFrontBack.front = new Token(mTokensFrontBack); mTokensFrontBack.back = mTokensFrontBack.front; mTokensFrontBack.back->str(str); } mTokensFrontBack.back->linenr(locationTok->linenr()); mTokensFrontBack.back->column(locationTok->column()); mTokensFrontBack.back->fileIndex(locationTok->fileIndex()); } void TokenList::addtoken(const Token * tok, const nonneg int lineno, const nonneg int column, const nonneg int fileno) { if (tok == nullptr) return; if (mTokensFrontBack.back) { mTokensFrontBack.back->insertToken(tok->str(), tok->originalName()); } else { mTokensFrontBack.front = new Token(mTokensFrontBack); mTokensFrontBack.back = mTokensFrontBack.front; mTokensFrontBack.back->str(tok->str()); if (!tok->originalName().empty()) mTokensFrontBack.back->originalName(tok->originalName()); } mTokensFrontBack.back->linenr(lineno); mTokensFrontBack.back->column(column); mTokensFrontBack.back->fileIndex(fileno); mTokensFrontBack.back->flags(tok->flags()); } void TokenList::addtoken(const Token *tok, const Token *locationTok) { if (tok == nullptr || locationTok == nullptr) return; if (mTokensFrontBack.back) { mTokensFrontBack.back->insertToken(tok->str(), tok->originalName()); } else { mTokensFrontBack.front = new Token(mTokensFrontBack); mTokensFrontBack.back = mTokensFrontBack.front; mTokensFrontBack.back->str(tok->str()); if (!tok->originalName().empty()) mTokensFrontBack.back->originalName(tok->originalName()); } mTokensFrontBack.back->flags(tok->flags()); mTokensFrontBack.back->linenr(locationTok->linenr()); mTokensFrontBack.back->column(locationTok->column()); mTokensFrontBack.back->fileIndex(locationTok->fileIndex()); } void TokenList::addtoken(const Token *tok) { if (tok == nullptr) return; if (mTokensFrontBack.back) { mTokensFrontBack.back->insertToken(tok->str(), tok->originalName(), tok->getMacroName()); } else { mTokensFrontBack.front = new Token(mTokensFrontBack); mTokensFrontBack.back = mTokensFrontBack.front; mTokensFrontBack.back->str(tok->str()); mTokensFrontBack.back->originalName(tok->originalName()); mTokensFrontBack.back->setMacroName(tok->getMacroName()); } mTokensFrontBack.back->flags(tok->flags()); mTokensFrontBack.back->linenr(tok->linenr()); mTokensFrontBack.back->column(tok->column()); mTokensFrontBack.back->fileIndex(tok->fileIndex()); } //--------------------------------------------------------------------------- // copyTokens - Copy and insert tokens //--------------------------------------------------------------------------- Token *TokenList::copyTokens(Token *dest, const Token *first, const Token *last, bool one_line) { std::stack<Token *> links; Token *tok2 = dest; int linenr = dest->linenr(); const int commonFileIndex = dest->fileIndex(); for (const Token *tok = first; tok != last->next(); tok = tok->next()) { tok2->insertToken(tok->str()); tok2 = tok2->next(); tok2->fileIndex(commonFileIndex); tok2->linenr(linenr); tok2->tokType(tok->tokType()); tok2->flags(tok->flags()); tok2->varId(tok->varId()); tok2->setTokenDebug(tok->getTokenDebug()); // Check for links and fix them up if (Token::Match(tok2, "(|[|{")) links.push(tok2); else if (Token::Match(tok2, ")|]|}")) { if (links.empty()) return tok2; Token * link = links.top(); tok2->link(link); link->link(tok2); links.pop(); } if (!one_line && tok->next()) linenr += tok->next()->linenr() - tok->linenr(); } return tok2; } //--------------------------------------------------------------------------- // InsertTokens - Copy and insert tokens //--------------------------------------------------------------------------- void TokenList::insertTokens(Token *dest, const Token *src, nonneg int n) { // TODO: put the linking in a helper? std::stack<Token *> link; while (n > 0) { dest->insertToken(src->str(), src->originalName()); dest = dest->next(); // Set links if (Token::Match(dest, "(|[|{")) link.push(dest); else if (!link.empty() && Token::Match(dest, ")|]|}")) { Token::createMutualLinks(dest, link.top()); link.pop(); } dest->fileIndex(src->fileIndex()); dest->linenr(src->linenr()); dest->column(src->column()); dest->varId(src->varId()); dest->tokType(src->tokType()); dest->flags(src->flags()); dest->setMacroName(src->getMacroName()); src = src->next(); --n; } } //--------------------------------------------------------------------------- // Tokenize - tokenizes a given file. //--------------------------------------------------------------------------- bool TokenList::createTokens(std::istream &code, const std::string& file0) { ASSERT_LANG(!file0.empty()); appendFileIfNew(file0); return createTokensInternal(code, file0); } //--------------------------------------------------------------------------- bool TokenList::createTokens(std::istream &code, Standards::Language lang) { ASSERT_LANG(lang != Standards::Language::None); if (mLang == Standards::Language::None) { mLang = lang; } else { ASSERT_LANG(lang == mLang); } return createTokensInternal(code, ""); } //--------------------------------------------------------------------------- bool TokenList::createTokensInternal(std::istream &code, const std::string& file0) { simplecpp::OutputList outputList; simplecpp::TokenList tokens(code, mFiles, file0, &outputList); createTokens(std::move(tokens)); return outputList.empty(); } //--------------------------------------------------------------------------- // NOLINTNEXTLINE(cppcoreguidelines-rvalue-reference-param-not-moved) void TokenList::createTokens(simplecpp::TokenList&& tokenList) { // TODO: what to do if the list has been filled already? clear mTokensFrontBack? // tokenList.cfront() might be NULL if the file contained nothing to tokenize so we need to check the files instead if (!tokenList.getFiles().empty()) { // this is a copy // TODO: this points to mFiles when called from createTokens(std::istream &, const std::string&) mOrigFiles = mFiles = tokenList.getFiles(); } else mFiles.clear(); determineCppC(); for (const simplecpp::Token *tok = tokenList.cfront(); tok;) { // TODO: move from TokenList std::string str = tok->str(); // Float literal if (str.size() > 1 && str[0] == '.' && std::isdigit(str[1])) str = '0' + str; if (mTokensFrontBack.back) { mTokensFrontBack.back->insertToken(str); } else { mTokensFrontBack.front = new Token(mTokensFrontBack); mTokensFrontBack.back = mTokensFrontBack.front; mTokensFrontBack.back->str(str); } mTokensFrontBack.back->fileIndex(tok->location.fileIndex); mTokensFrontBack.back->linenr(tok->location.line); mTokensFrontBack.back->column(tok->location.col); mTokensFrontBack.back->setMacroName(tok->macro); tok = tok->next; if (tok) tokenList.deleteToken(tok->previous); } if (mSettings && mSettings->relativePaths) { for (std::string & mFile : mFiles) mFile = Path::getRelativePath(mFile, mSettings->basePaths); } Token::assignProgressValues(mTokensFrontBack.front); } //--------------------------------------------------------------------------- std::size_t TokenList::calculateHash() const { std::string hashData; for (const Token* tok = front(); tok; tok = tok->next()) { hashData += std::to_string(tok->flags()); hashData += std::to_string(tok->varId()); hashData += std::to_string(tok->tokType()); hashData += tok->str(); hashData += tok->originalName(); } return (std::hash<std::string>{})(hashData); } //--------------------------------------------------------------------------- namespace { struct AST_state { std::stack<Token*> op; int depth{}; int inArrayAssignment{}; bool cpp; int assign{}; bool inCase{}; // true from case to : bool stopAtColon{}; // help to properly parse ternary operators const Token* functionCallEndPar{}; explicit AST_state(bool cpp) : cpp(cpp) {} }; } static Token* skipDecl(Token* tok, std::vector<Token*>* inner = nullptr) { auto isDecltypeFuncParam = [](const Token* tok) -> bool { if (!Token::simpleMatch(tok, ")")) return false; tok = tok->next(); while (Token::Match(tok, "*|&|&&|const")) tok = tok->next(); if (Token::simpleMatch(tok, "(")) tok = tok->link()->next(); return Token::Match(tok, "%name%| ,|)"); }; if (!Token::Match(tok->previous(), "( %name%")) return tok; Token *vartok = tok; while (Token::Match(vartok, "%name%|*|&|::|<")) { if (vartok->str() == "<") { if (vartok->link()) vartok = vartok->link(); else return tok; } else if (Token::Match(vartok, "%var% [:=({]")) { return vartok; } else if (Token::Match(vartok, "decltype|typeof (") && !isDecltypeFuncParam(tok->linkAt(1))) { if (inner) inner->push_back(vartok->tokAt(2)); return vartok->linkAt(1)->next(); } vartok = vartok->next(); } return tok; } static bool iscast(const Token *tok, bool cpp) { if (!Token::Match(tok, "( ::| %name%")) return false; if (Token::simpleMatch(tok->link(), ") ( )")) return false; if (Token::Match(tok->link(), ") %assign%|,|...")) return false; if (tok->previous() && tok->previous()->isName() && tok->strAt(-1) != "return" && (!cpp || !Token::Match(tok->previous(), "delete|throw"))) return false; if (Token::simpleMatch(tok->previous(), ">") && tok->linkAt(-1)) return false; if (Token::Match(tok, "( (| typeof (") && Token::Match(tok->link(), ") %num%")) return true; if (Token::Match(tok->link(), ") }|)|]|;")) return false; if (Token::Match(tok->link(), ") ++|-- [;)]")) return false; if (Token::Match(tok->link(), ") %cop%") && !Token::Match(tok->link(), ") [&*+-~!]")) return false; if (Token::Match(tok->previous(), "= ( %name% ) {") && tok->next()->varId() == 0) return true; bool type = false; for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->varId() != 0) return false; if (cpp && !type && tok2->str() == "new") return false; while (tok2->link() && Token::Match(tok2, "(|[|<")) tok2 = tok2->link()->next(); if (tok2->str() == ")") { if (Token::simpleMatch(tok2, ") (") && Token::simpleMatch(tok2->linkAt(1), ") .")) return true; if (Token::simpleMatch(tok2, ") {") && !type) { const Token *tok3 = tok2->linkAt(1); while (tok3 != tok2 && Token::Match(tok3, "[{}]")) tok3 = tok3->previous(); return tok3->str() != ";"; } const bool res = type || tok2->strAt(-1) == "*" || Token::simpleMatch(tok2, ") ~") || (Token::Match(tok2, ") %any%") && (!tok2->next()->isOp() || Token::Match(tok2->next(), "!|~|++|--")) && !Token::Match(tok2->next(), "[[]);,?:.]")); return res; } if (Token::Match(tok2, "&|&& )")) return true; if (!Token::Match(tok2, "%name%|*|::")) return false; if (tok2->isStandardType() && (tok2->strAt(1) != "(" || Token::Match(tok2->next(), "( * *| )"))) type = true; } return false; } // int(1), int*(2), .. static Token * findCppTypeInitPar(Token *tok) { if (!tok || !Token::Match(tok->previous(), "[,()] %name%")) return nullptr; bool istype = false; while (Token::Match(tok, "%name%|::|<")) { if (tok->str() == "<") { tok = tok->link(); if (!tok) return nullptr; } istype |= tok->isStandardType(); tok = tok->next(); } if (!istype) return nullptr; if (!Token::Match(tok, "[*&]")) return nullptr; while (Token::Match(tok, "[*&]")) tok = tok->next(); return (tok && tok->str() == "(") ? tok : nullptr; } // X{} X<Y>{} etc static bool iscpp11init_impl(const Token * tok); static bool iscpp11init(const Token * const tok) { if (tok->isCpp11init() == TokenImpl::Cpp11init::UNKNOWN) tok->setCpp11init(iscpp11init_impl(tok)); return tok->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT; } static bool iscpp11init_impl(const Token * const tok) { if (Token::simpleMatch(tok, "{") && Token::simpleMatch(tok->link()->previous(), "; }")) return false; const Token *nameToken = tok; while (nameToken && nameToken->str() == "{") { if (nameToken->isCpp11init() != TokenImpl::Cpp11init::UNKNOWN) return nameToken->isCpp11init() == TokenImpl::Cpp11init::CPP11INIT; nameToken = nameToken->previous(); if (nameToken && nameToken->str() == "," && Token::simpleMatch(nameToken->previous(), "} ,")) nameToken = nameToken->linkAt(-1); } if (!nameToken) return false; if (nameToken->str() == ")" && Token::simpleMatch(nameToken->link()->previous(), "decltype (") && !Token::simpleMatch(nameToken->link()->tokAt(-2), ".")) nameToken = nameToken->link()->previous(); if (Token::simpleMatch(nameToken, ", {")) return true; if (nameToken->str() == ">" && nameToken->link()) nameToken = nameToken->link()->previous(); if (Token::Match(nameToken, "]|*")) { const Token* newTok = nameToken->link() ? nameToken->link()->previous() : nameToken->previous(); while (Token::Match(newTok, "%type%|::|*") && !newTok->isKeyword()) newTok = newTok->previous(); if (Token::simpleMatch(newTok, "new")) return true; } auto isCaseStmt = [](const Token* colonTok) { if (!Token::Match(colonTok->tokAt(-1), "%name%|%num%|%char%|) :")) return false; if (const Token* castTok = colonTok->linkAt(-1)) { if (Token::simpleMatch(castTok->astParent(), "case")) return true; } const Token* caseTok = colonTok->tokAt(-2); while (caseTok && Token::Match(caseTok->tokAt(-1), "::|%name%")) caseTok = caseTok->tokAt(-1); return Token::simpleMatch(caseTok, "case"); }; const Token *endtok = nullptr; if (Token::Match(nameToken, "%name%|return|: {") && !isCaseStmt(nameToken) && (!Token::simpleMatch(nameToken->tokAt(2), "[") || findLambdaEndScope(nameToken->tokAt(2)))) endtok = nameToken->linkAt(1); else if (Token::Match(nameToken,"%name% <") && Token::simpleMatch(nameToken->linkAt(1),"> {")) endtok = nameToken->linkAt(1)->linkAt(1); else if (Token::Match(nameToken->previous(), "%name%|> ( {")) endtok = nameToken->linkAt(1); else if (Token::simpleMatch(nameToken, "decltype") && nameToken->linkAt(1)) endtok = nameToken->linkAt(1)->linkAt(1); else return false; if (Token::Match(nameToken, "else|try|do|const|constexpr|override|volatile|&|&&")) return false; if (Token::simpleMatch(nameToken->previous(), ". void {") && nameToken->previous()->originalName() == "->") return false; // trailing return type. The only function body that can contain no semicolon is a void function. if (Token::simpleMatch(nameToken->previous(), "namespace") || Token::simpleMatch(nameToken, "namespace") /*anonymous namespace*/) return false; if (precedes(nameToken->next(), endtok) && !Token::Match(nameToken, "return|:")) { // If there is semicolon between {..} this is not a initlist for (const Token *tok2 = nameToken->next(); tok2 != endtok; tok2 = tok2->next()) { if (tok2->str() == ";") return false; const Token * lambdaEnd = findLambdaEndScope(tok2); if (lambdaEnd) tok2 = lambdaEnd; } } // There is no initialisation for example here: 'class Fred {};' if (!Token::simpleMatch(endtok, "} ;")) return true; const Token *prev = nameToken; while (Token::Match(prev, "%name%|::|:|<|>|(|)|,|%num%|%cop%|...")) { if (Token::Match(prev, "class|struct|union|enum")) return false; prev = prev->previous(); } return true; } static bool isQualifier(const Token* tok) { while (Token::Match(tok, "&|&&|*")) tok = tok->next(); return Token::Match(tok, "{|;"); } static void compileUnaryOp(Token *&tok, AST_state& state, void (*f)(Token *&tok, AST_state& state)) { Token *unaryop = tok; if (f) { tok = tok->next(); state.depth++; if (state.depth > AST_MAX_DEPTH) throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST); if (tok) f(tok, state); state.depth--; } if (!state.op.empty() && (!precedes(state.op.top(), unaryop) || unaryop->isIncDecOp() || Token::Match(unaryop, "[({[]"))) { // nullary functions, empty lists/arrays unaryop->astOperand1(state.op.top()); state.op.pop(); } state.op.push(unaryop); } static void compileBinOp(Token *&tok, AST_state& state, void (*f)(Token *&tok, AST_state& state)) { Token *binop = tok; if (f) { tok = tok->next(); if (Token::Match(binop, "::|. ~")) tok = tok->next(); state.depth++; if (tok && state.depth <= AST_MAX_DEPTH) f(tok, state); if (state.depth > AST_MAX_DEPTH) throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST); state.depth--; } // TODO: Should we check if op is empty. // * Is it better to add assertion that it isn't? // * Write debug warning if it's empty? if (!state.op.empty()) { binop->astOperand2(state.op.top()); state.op.pop(); } if (!state.op.empty()) { binop->astOperand1(state.op.top()); state.op.pop(); } state.op.push(binop); } static void compileExpression(Token *&tok, AST_state& state); static void compileTerm(Token *&tok, AST_state& state) { if (!tok) return; if (Token::Match(tok, "L %str%|%char%")) tok = tok->next(); if (state.inArrayAssignment && Token::Match(tok->previous(), "[{,] . %name%")) { // Jump over . in C style struct initialization state.op.push(tok); tok->astOperand1(tok->next()); tok = tok->tokAt(2); } if (state.inArrayAssignment && Token::Match(tok->previous(), "[{,] [ %num%|%name% ]")) { state.op.push(tok); tok->astOperand1(tok->next()); tok = tok->tokAt(3); } if (tok->isLiteral()) { state.op.push(tok); do { tok = tok->next(); } while (Token::Match(tok, "%name%|%str%")); } else if (tok->isName()) { if (Token::Match(tok, "return|case") || (state.cpp && (tok->str() == "throw"))) { if (tok->str() == "case") state.inCase = true; const bool tokIsReturn = tok->str() == "return"; const bool stopAtColon = state.stopAtColon; state.stopAtColon=true; compileUnaryOp(tok, state, compileExpression); state.stopAtColon=stopAtColon; if (tokIsReturn) state.op.pop(); if (state.inCase && Token::simpleMatch(tok, ": ;")) { state.inCase = false; tok = tok->next(); } } else if (Token::Match(tok, "sizeof !!(")) { compileUnaryOp(tok, state, compileExpression); state.op.pop(); } else if (state.cpp && findCppTypeInitPar(tok)) { // int(0), int*(123), .. tok = findCppTypeInitPar(tok); state.op.push(tok); tok = tok->tokAt(2); } else if (state.cpp && iscpp11init(tok)) { // X{} X<Y>{} etc state.op.push(tok); tok = tok->next(); if (tok->str() == "<") tok = tok->link()->next(); if (Token::Match(tok, "{ . %name% =|{")) { const Token* end = tok->link(); const int inArrayAssignment = state.inArrayAssignment; state.inArrayAssignment = 1; compileBinOp(tok, state, compileExpression); state.inArrayAssignment = inArrayAssignment; if (tok == end) tok = tok->next(); else throw InternalError(tok, "Syntax error. Unexpected tokens in designated initializer.", InternalError::AST); } } else if (!state.cpp || !Token::Match(tok, "new|delete %name%|*|&|::|(|[")) { std::vector<Token*> inner; tok = skipDecl(tok, &inner); for (Token* tok3 : inner) { AST_state state1(state.cpp); compileExpression(tok3, state1); } bool repeat = true; while (repeat) { repeat = false; if (Token::Match(tok->next(), "%name%")) { tok = tok->next(); repeat = true; } if (Token::simpleMatch(tok->next(), "<") && Token::Match(tok->linkAt(1), "> %name%")) { tok = tok->linkAt(1)->next(); repeat = true; } } state.op.push(tok); if (Token::Match(tok, "%name% <") && tok->linkAt(1)) tok = tok->linkAt(1); else if (Token::Match(tok, "%name% ...") || (state.op.size() == 1 && state.depth == 0 && Token::Match(tok->tokAt(-3), "!!& ) ( %name% ) ="))) tok = tok->next(); tok = tok->next(); if (Token::Match(tok, "%str%")) { while (Token::Match(tok, "%name%|%str%")) tok = tok->next(); } if (Token::Match(tok, "%name% %assign%")) tok = tok->next(); } } else if (tok->str() == "{") { const Token *prev = tok->previous(); if (Token::simpleMatch(prev, ") {") && iscast(prev->link(), state.cpp)) prev = prev->link()->previous(); if (Token::simpleMatch(tok->link(),"} [")) { tok = tok->next(); } else if ((state.cpp && iscpp11init(tok)) || Token::simpleMatch(tok->previous(), "] {")) { Token *const end = tok->link(); if (state.op.empty() || Token::Match(tok->previous(), "[{,]") || Token::Match(tok->tokAt(-2), "%name% (")) { if (Token::Match(tok->tokAt(-1), "!!, { . %name% =|{")) { const int inArrayAssignment = state.inArrayAssignment; state.inArrayAssignment = 1; compileBinOp(tok, state, compileExpression); state.inArrayAssignment = inArrayAssignment; } else if (Token::simpleMatch(tok, "{ }")) { state.op.push(tok); tok = tok->next(); } else { compileUnaryOp(tok, state, compileExpression); if (precedes(tok,end)) // typically for something like `MACRO(x, { if (c) { ... } })`, where end is the last curly, and tok is the open curly for the if tok = end; } } else compileBinOp(tok, state, compileExpression); if (tok != end) throw InternalError(tok, "Syntax error. Unexpected tokens in initializer.", InternalError::AST); if (tok->next()) tok = tok->next(); } else if (state.cpp && Token::Match(tok->tokAt(-2), "%name% ( {") && !Token::findsimplematch(tok, ";", tok->link())) { if (Token::simpleMatch(tok, "{ }")) tok = tok->tokAt(2); else { Token *tok1 = tok; state.inArrayAssignment++; compileUnaryOp(tok, state, compileExpression); state.inArrayAssignment--; tok = tok1->link()->next(); } } else if (!state.inArrayAssignment && !Token::simpleMatch(prev, "=")) { state.op.push(tok); tok = tok->link()->next(); } else { if (tok->link() != tok->next()) { state.inArrayAssignment++; compileUnaryOp(tok, state, compileExpression); if (Token::Match(tok, "} [,};]") && state.inArrayAssignment > 0) { tok = tok->next(); state.inArrayAssignment--; } } else { state.op.push(tok); tok = tok->tokAt(2); } } } } static void compileScope(Token *&tok, AST_state& state) { compileTerm(tok, state); while (tok) { if (tok->str() == "::") { const Token *lastOp = state.op.empty() ? nullptr : state.op.top(); if (Token::Match(lastOp, ":: %name%")) lastOp = lastOp->next(); if (Token::Match(lastOp, "%name%") && (lastOp->next() == tok || (Token::Match(lastOp, "%name% <") && lastOp->linkAt(1) && tok == lastOp->linkAt(1)->next()))) compileBinOp(tok, state, compileTerm); else compileUnaryOp(tok, state, compileTerm); } else break; } } static bool isPrefixUnary(const Token* tok, bool cpp) { if (cpp && Token::simpleMatch(tok->previous(), "* [") && Token::simpleMatch(tok->link(), "] {")) { for (const Token* prev = tok->previous(); Token::Match(prev, "%name%|::|*|&|>|>>"); prev = prev->previous()) { if (Token::Match(prev, ">|>>")) { if (!prev->link()) break; prev = prev->link(); } if (prev->str() == "new") return false; } } if (!tok->previous() || ((Token::Match(tok->previous(), "(|[|{|%op%|;|?|:|,|.|case|return|::") || (cpp && tok->strAt(-1) == "throw")) && (tok->previous()->tokType() != Token::eIncDecOp || tok->tokType() == Token::eIncDecOp))) return true; if (tok->strAt(-1) == "}") { const Token* parent = tok->linkAt(-1)->tokAt(-1); return !Token::Match(parent, "%type%") || parent->isKeyword(); } if (tok->str() == "*" && tok->previous()->tokType() == Token::eIncDecOp && isPrefixUnary(tok->previous(), cpp)) return true; return tok->strAt(-1) == ")" && iscast(tok->linkAt(-1), cpp); } static void compilePrecedence2(Token *&tok, AST_state& state) { auto doCompileScope = [&](const Token* tok) -> bool { const bool isStartOfCpp11Init = state.cpp && tok && tok->str() == "{" && iscpp11init(tok); if (isStartOfCpp11Init || Token::simpleMatch(tok, "(")) { tok = tok->previous(); while (Token::simpleMatch(tok, "*")) tok = tok->previous(); while (tok && Token::Match(tok->previous(), ":: %type%")) tok = tok->tokAt(-2); if (tok && !tok->isKeyword()) tok = tok->previous(); return !Token::Match(tok, "new ::| %type%"); } return !findLambdaEndTokenWithoutAST(tok); }; bool isNew = true; if (doCompileScope(tok)) { compileScope(tok, state); isNew = false; } while (tok) { if (tok->tokType() == Token::eIncDecOp && !isPrefixUnary(tok, state.cpp)) { compileUnaryOp(tok, state, compileScope); } else if (tok->str() == "...") { if (!Token::simpleMatch(tok->previous(), ")")) state.op.push(tok); tok = tok->next(); break; } else if (tok->str() == "." && tok->strAt(1) != "*") { if (tok->strAt(1) == ".") { state.op.push(tok); tok = tok->tokAt(3); break; } if (!Token::Match(tok->tokAt(-1), "[{,]")) compileBinOp(tok, state, compileScope); else compileUnaryOp(tok, state, compileScope); } else if (tok->str() == "[") { if (state.cpp && isPrefixUnary(tok, /*cpp*/ true) && Token::Match(tok->link(), "] (|{|<")) { // Lambda // What we do here: // - Nest the round bracket under the square bracket. // - Nest what follows the lambda (if anything) with the lambda opening [ // - Compile the content of the lambda function as separate tree (this is done later) // this must be consistent with isLambdaCaptureList Token* const squareBracket = tok; // Parse arguments in the capture list if (tok->strAt(1) != "]") { Token* tok2 = tok->next(); AST_state state2(state.cpp); compileExpression(tok2, state2); if (!state2.op.empty()) { squareBracket->astOperand2(state2.op.top()); } } const bool hasTemplateArg = Token::simpleMatch(squareBracket->link(), "] <") && Token::simpleMatch(squareBracket->link()->linkAt(1), "> ("); if (Token::simpleMatch(squareBracket->link(), "] (") || hasTemplateArg) { Token* const roundBracket = hasTemplateArg ? squareBracket->link()->linkAt(1)->next() : squareBracket->link()->next(); Token* curlyBracket = roundBracket->link()->next(); while (Token::Match(curlyBracket, "mutable|const|constexpr|consteval")) curlyBracket = curlyBracket->next(); if (Token::simpleMatch(curlyBracket, "noexcept")) { if (Token::simpleMatch(curlyBracket->next(), "(")) curlyBracket = curlyBracket->linkAt(1)->next(); else curlyBracket = curlyBracket->next(); } if (curlyBracket && curlyBracket->originalName() == "->") curlyBracket = findTypeEnd(curlyBracket->next()); if (curlyBracket && curlyBracket->str() == "{") { squareBracket->astOperand1(roundBracket); roundBracket->astOperand1(curlyBracket); state.op.push(squareBracket); tok = curlyBracket->link()->next(); continue; } } else { Token* const curlyBracket = squareBracket->link()->next(); squareBracket->astOperand1(curlyBracket); state.op.push(squareBracket); tok = curlyBracket->link() ? curlyBracket->link()->next() : nullptr; continue; } } Token* const tok2 = tok; if (tok->strAt(1) != "]") { compileBinOp(tok, state, compileExpression); if (Token::Match(tok2->previous(), "%type%|* [") && Token::Match(tok, "] { !!}")) { tok = tok->next(); Token* const tok3 = tok; compileBinOp(tok, state, compileExpression); if (tok != tok3->link()) throw InternalError(tok, "Syntax error in {..}", InternalError::AST); tok = tok->next(); continue; } } else compileUnaryOp(tok, state, compileExpression); tok = tok2->link()->next(); } else if (Token::simpleMatch(tok->previous(), "requires {")) { state.op.push(tok); tok = tok->link()->next(); continue; } else if (Token::simpleMatch(tok, "( {") && Token::simpleMatch(tok->linkAt(1)->previous(), "; } )") && !Token::Match(tok->previous(), "%name% (")) { state.op.push(tok->next()); tok = tok->link()->next(); continue; } else if (tok->str() == "(" && (!iscast(tok, state.cpp) || Token::Match(tok->previous(), "if|while|for|switch|catch"))) { Token* tok2 = tok; tok = tok->next(); const bool opPrevTopSquare = !state.op.empty() && state.op.top() && state.op.top()->str() == "["; const std::size_t oldOpSize = state.op.size(); compileExpression(tok, state); tok = tok2; if ((oldOpSize > 0 && (isNew || Token::simpleMatch(tok->previous(), "} ("))) || (tok->previous() && tok->previous()->isName() && !Token::Match(tok->previous(), "return|case") && (!state.cpp || !Token::Match(tok->previous(), "throw|delete"))) || (tok->strAt(-1) == "]" && (!state.cpp || !Token::Match(tok->linkAt(-1)->previous(), "new|delete"))) || (tok->strAt(-1) == ">" && tok->linkAt(-1)) || (tok->strAt(-1) == ")" && !iscast(tok->linkAt(-1), state.cpp)) // Don't treat brackets to clarify precedence as function calls || (tok->strAt(-1) == "}" && opPrevTopSquare)) { const bool operandInside = oldOpSize < state.op.size(); if (operandInside) compileBinOp(tok, state, nullptr); else compileUnaryOp(tok, state, nullptr); } tok = tok->link()->next(); if (Token::simpleMatch(tok, "::")) compileBinOp(tok, state, compileTerm); } else if (iscast(tok, state.cpp) && Token::simpleMatch(tok->link(), ") {") && Token::simpleMatch(tok->link()->linkAt(1), "} [")) { Token *cast = tok; tok = tok->link()->next(); Token *tok1 = tok; compileUnaryOp(tok, state, compileExpression); cast->astOperand1(tok1); tok = tok1->link()->next(); } else if (state.cpp && tok->str() == "{" && iscpp11init(tok)) { Token* end = tok->link(); if (Token::simpleMatch(tok, "{ }")) { compileUnaryOp(tok, state, nullptr); tok = tok->next(); } else { compileBinOp(tok, state, compileExpression); } if (tok == end) tok = end->next(); else throw InternalError(tok, "Syntax error. Unexpected tokens in initializer.", InternalError::AST); } else break; } } static void compilePrecedence3(Token *&tok, AST_state& state) { compilePrecedence2(tok, state); while (tok) { if ((Token::Match(tok, "[+-!~*&]") || tok->tokType() == Token::eIncDecOp) && isPrefixUnary(tok, state.cpp)) { if (Token::Match(tok, "* [*,)]")) { Token* tok2 = tok->next(); while (tok2->next() && tok2->str() == "*") tok2 = tok2->next(); if (Token::Match(tok2, "[>),]")) { tok = tok2; continue; } } compileUnaryOp(tok, state, compilePrecedence3); } else if (tok->str() == "(" && iscast(tok, state.cpp)) { Token* castTok = tok; castTok->isCast(true); tok = tok->link()->next(); const int inArrayAssignment = state.inArrayAssignment; if (tok && tok->str() == "{") state.inArrayAssignment = 1; compilePrecedence3(tok, state); state.inArrayAssignment = inArrayAssignment; compileUnaryOp(castTok, state, nullptr); } else if (state.cpp && Token::Match(tok, "new %name%|::|(")) { Token* newtok = tok; tok = tok->next(); bool innertype = false; if (tok->str() == "(") { if (Token::Match(tok, "( &| %name%") && Token::Match(tok->link(), ") ( %type%") && Token::simpleMatch(tok->link()->linkAt(1), ") (")) tok = tok->link()->next(); if (Token::Match(tok->link(), ") ::| %type%")) { if (Token::Match(tok, "( !!)")) { Token *innerTok = tok->next(); AST_state innerState(true); compileExpression(innerTok, innerState); } tok = tok->link()->next(); } else if (Token::Match(tok, "( %type%") && Token::Match(tok->link(), ") [();,[]")) { tok = tok->next(); innertype = true; } else if (Token::Match(tok, "( &| %name%") && Token::simpleMatch(tok->link(), ") (")) { tok = tok->next(); innertype = true; } else { /* bad code */ continue; } } Token* leftToken = tok; if (Token::simpleMatch(tok, "::")) { tok->astOperand1(tok->next()); tok = tok->next(); } else { while (Token::Match(tok->next(), ":: %name%")) { Token* scopeToken = tok->next(); //The :: scopeToken->astOperand1(leftToken); scopeToken->astOperand2(scopeToken->next()); leftToken = scopeToken; tok = scopeToken->next(); } } state.op.push(tok); while (Token::Match(tok, "%name%|*|&|<|::")) { if (tok->link()) tok = tok->link(); tok = tok->next(); } if (Token::Match(tok, "( const| %type% ) (")) { state.op.push(tok->next()); tok = tok->link()->next(); compileBinOp(tok, state, compilePrecedence2); } else if (Token::Match(tok, "(|{|[")) compilePrecedence2(tok, state); else if (innertype && Token::simpleMatch(tok, ") [")) { tok = tok->next(); compilePrecedence2(tok, state); } compileUnaryOp(newtok, state, nullptr); if (Token::simpleMatch(newtok->previous(), ":: new")) { newtok->previous()->astOperand1(newtok); state.op.pop(); } if (innertype && Token::simpleMatch(tok, ") ,")) tok = tok->next(); } else if (state.cpp && Token::Match(tok, "delete %name%|*|&|::|(|[")) { Token* tok2 = tok; tok = tok->next(); if (tok && tok->str() == "[") tok = tok->link()->next(); compilePrecedence3(tok, state); compileUnaryOp(tok2, state, nullptr); if (Token::simpleMatch(tok2->previous(), ":: delete")) { tok2->previous()->astOperand1(tok2); state.op.pop(); } } // TODO: Handle sizeof else break; } } static void compilePointerToElem(Token *&tok, AST_state& state) { compilePrecedence3(tok, state); while (tok) { if (Token::simpleMatch(tok, ". *")) { compileBinOp(tok, state, compilePrecedence3); } else break; } } static void compileMulDiv(Token *&tok, AST_state& state) { compilePointerToElem(tok, state); while (tok) { if (Token::Match(tok, "[/%]") || (tok->str() == "*" && !tok->astOperand1() && !isQualifier(tok))) { if (Token::Match(tok, "* [*,)]")) { Token* tok2 = tok->next(); while (tok2->next() && tok2->str() == "*") tok2 = tok2->next(); if (Token::Match(tok2, "[>),]")) { tok = tok2; break; } } compileBinOp(tok, state, compilePointerToElem); } else break; } } static void compileAddSub(Token *&tok, AST_state& state) { compileMulDiv(tok, state); while (tok) { if (Token::Match(tok, "+|-") && !tok->astOperand1()) { compileBinOp(tok, state, compileMulDiv); } else break; } } static void compileShift(Token *&tok, AST_state& state) { compileAddSub(tok, state); while (tok) { if (Token::Match(tok, "<<|>>")) { compileBinOp(tok, state, compileAddSub); } else break; } } static void compileThreewayComp(Token *&tok, AST_state& state) { compileShift(tok, state); while (tok) { if (tok->str() == "<=>") { compileBinOp(tok, state, compileShift); } else break; } } static void compileRelComp(Token *&tok, AST_state& state) { compileThreewayComp(tok, state); while (tok) { if (Token::Match(tok, "<|<=|>=|>") && !tok->link()) { compileBinOp(tok, state, compileThreewayComp); } else break; } } static void compileEqComp(Token *&tok, AST_state& state) { compileRelComp(tok, state); while (tok) { if (Token::Match(tok, "==|!=")) { compileBinOp(tok, state, compileRelComp); } else break; } } static void compileAnd(Token *&tok, AST_state& state) { compileEqComp(tok, state); while (tok) { if (tok->str() == "&" && !tok->astOperand1() && !isQualifier(tok)) { Token* tok2 = tok->next(); if (!tok2) break; if (tok2->str() == "&") tok2 = tok2->next(); if (state.cpp && Token::Match(tok2, ",|)")) { tok = tok2; break; // rValue reference } compileBinOp(tok, state, compileEqComp); } else break; } } static void compileXor(Token *&tok, AST_state& state) { compileAnd(tok, state); while (tok) { if (tok->str() == "^") { compileBinOp(tok, state, compileAnd); } else break; } } static void compileOr(Token *&tok, AST_state& state) { compileXor(tok, state); while (tok) { if (tok->str() == "|") { compileBinOp(tok, state, compileXor); } else break; } } static void compileLogicAnd(Token *&tok, AST_state& state) { compileOr(tok, state); while (tok) { if (tok->str() == "&&" && !isQualifier(tok)) { if (!tok->astOperand1()) { Token* tok2 = tok->next(); if (!tok2) break; if (state.cpp && Token::Match(tok2, ",|)")) { tok = tok2; break; // rValue reference } } compileBinOp(tok, state, compileOr); } else break; } } static void compileLogicOr(Token *&tok, AST_state& state) { compileLogicAnd(tok, state); while (tok) { if (tok->str() == "||") { compileBinOp(tok, state, compileLogicAnd); } else break; } } static void compileAssignTernary(Token *&tok, AST_state& state) { compileLogicOr(tok, state); while (tok) { if (tok->isAssignmentOp()) { state.assign++; const Token *tok1 = tok->next(); compileBinOp(tok, state, compileAssignTernary); if (Token::simpleMatch(tok1, "{") && tok == tok1->link() && tok->next()) tok = tok->next(); if (state.assign > 0) state.assign--; } else if (tok->str() == "?") { // http://en.cppreference.com/w/cpp/language/operator_precedence says about ternary operator: // "The expression in the middle of the conditional operator (between ? and :) is parsed as if parenthesized: its precedence relative to ?: is ignored." // Hence, we rely on Tokenizer::prepareTernaryOpForAST() to add such parentheses where necessary. const bool stopAtColon = state.stopAtColon; state.stopAtColon = false; if (tok->strAt(1) == ":") { state.op.push(nullptr); } const int assign = state.assign; state.assign = 0; compileBinOp(tok, state, compileAssignTernary); state.assign = assign; state.stopAtColon = stopAtColon; } else if (tok->str() == ":") { if (state.depth == 1U && state.inCase) { state.inCase = false; tok = tok->next(); break; } if (state.stopAtColon) break; if (state.assign > 0) break; compileBinOp(tok, state, compileAssignTernary); } else break; } } static void compileComma(Token *&tok, AST_state& state) { compileAssignTernary(tok, state); while (tok) { if (tok->str() == ",") { if (Token::simpleMatch(tok, ", }")) tok = tok->next(); else compileBinOp(tok, state, compileAssignTernary); } else if (tok->str() == ";" && state.functionCallEndPar && tok->index() < state.functionCallEndPar->index()) { compileBinOp(tok, state, compileAssignTernary); } else break; } } static void compileExpression(Token *&tok, AST_state& state) { if (state.depth > AST_MAX_DEPTH) throw InternalError(tok, "maximum AST depth exceeded", InternalError::AST); // ticket #5592 if (tok) compileComma(tok, state); } const Token* isLambdaCaptureList(const Token * tok) { // a lambda expression '[x](y){}' is compiled as: // [ // `-( <<-- optional // `-{ // see compilePrecedence2 if (!Token::simpleMatch(tok, "[")) return nullptr; if (!Token::Match(tok->link(), "] (|{")) return nullptr; if (Token::simpleMatch(tok->astOperand1(), "{") && tok->astOperand1() == tok->link()->next()) return tok->astOperand1(); if (!tok->astOperand1() || tok->astOperand1()->str() != "(") return nullptr; const Token * params = tok->astOperand1(); if (!Token::simpleMatch(params->astOperand1(), "{")) return nullptr; return params->astOperand1(); } const Token* findLambdaEndTokenWithoutAST(const Token* tok) { if (!(Token::simpleMatch(tok, "[") && tok->link())) return nullptr; tok = tok->link()->next(); if (Token::simpleMatch(tok, "(") && tok->link()) tok = tok->link()->next(); if (Token::simpleMatch(tok, ".")) { // trailing return type tok = tok->next(); while (Token::Match(tok, "%type%|%name%|::|&|&&|*|<|(")) { if (tok->link()) tok = tok->link()->next(); else tok = tok->next(); } } if (!(Token::simpleMatch(tok, "{") && tok->link())) return nullptr; return tok->link()->next(); } static Token * createAstAtToken(Token *tok); // Compile inner expressions inside inner ({..}) and lambda bodies static void createAstAtTokenInner(Token * const tok1, const Token *endToken, bool cpp) { for (Token* tok = tok1; precedes(tok, endToken); tok = tok ? tok->next() : nullptr) { if (tok->str() == "{" && !iscpp11init(tok)) { const Token * const endToken2 = tok->link(); bool hasAst = false; for (const Token *inner = tok->next(); inner != endToken2; inner = inner->next()) { if (inner->astOperand1()) { hasAst = true; break; } if (tok->isConstOp()) break; if (inner->str() == "{") inner = inner->link(); } if (!hasAst) { for (; tok && tok != endToken && tok != endToken2; tok = tok ? tok->next() : nullptr) tok = createAstAtToken(tok); } } else if (cpp && tok->str() == "[") { if (isLambdaCaptureList(tok)) { tok = tok->astOperand1(); if (tok->str() == "(") tok = tok->astOperand1(); const Token * const endToken2 = tok->link(); tok = tok->next(); for (; tok && tok != endToken && tok != endToken2; tok = tok ? tok->next() : nullptr) tok = createAstAtToken(tok); } } else if (Token::simpleMatch(tok, "( * ) [")) { bool hasAst = false; for (const Token* tok2 = tok->linkAt(3); tok2 != tok; tok2 = tok2->previous()) { if (tok2->astParent() || tok2->astOperand1() || tok2->astOperand2()) { hasAst = true; break; } } if (!hasAst) { Token *const startTok = tok = tok->tokAt(4); const Token* const endtok = startTok->linkAt(-1); AST_state state(cpp); compileExpression(tok, state); createAstAtTokenInner(startTok, endtok, cpp); } } } } static Token * findAstTop(Token *tok1, const Token *tok2) { for (Token *tok = tok1; tok && (tok != tok2); tok = tok->next()) { if (tok->astParent() || tok->astOperand1() || tok->astOperand2()) { while (tok->astParent() && tok->astParent()->index() >= tok1->index() && tok->astParent()->index() <= tok2->index()) tok = tok->astParent(); return tok; } if (Token::simpleMatch(tok, "( {")) tok = tok->link(); } for (Token *tok = tok1; tok && (tok != tok2); tok = tok->next()) { if (tok->isName() || tok->isNumber()) return tok; if (Token::simpleMatch(tok, "( {")) tok = tok->link(); } return nullptr; } static Token * createAstAtToken(Token *tok) { const bool cpp = tok->isCpp(); // skip function pointer declaration if (Token::Match(tok, "%type% %type%") && !Token::Match(tok, "return|throw|new|delete")) { Token* tok2 = tok->tokAt(2); // skip type tokens and qualifiers etc while (Token::Match(tok2, "%type%|*|&")) tok2 = tok2->next(); if (Token::Match(tok2, "%var% [;,)]")) return tok2; } if (Token::Match(tok, "%type%") && !Token::Match(tok, "return|throw|if|while|new|delete")) { bool isStandardTypeOrQualifier = false; Token* type = tok; while (Token::Match(type, "%type%|*|&|<")) { if (type->isName() && (type->isStandardType() || Token::Match(type, "const|mutable|static|volatile"))) isStandardTypeOrQualifier = true; if (type->str() == "<") { if (type->link()) type = type->link(); else break; } type = type->next(); } if (isStandardTypeOrQualifier && Token::Match(type, "%var% [;,)]")) return type; if (Token::Match(type, "( * *| %var%") && Token::Match(type->link()->previous(), "%var%|] ) (") && Token::Match(type->link()->linkAt(1), ") [;,)]")) return type->link()->linkAt(1)->next(); } if (Token::simpleMatch(tok, "for (")) { if (cpp && Token::Match(tok, "for ( const| auto &|&&| [")) { Token *decl = Token::findsimplematch(tok, "["); if (Token::simpleMatch(decl->link(), "] :")) { AST_state state1(cpp); while (decl->str() != "]") { if (Token::Match(decl, "%name% ,|]")) { state1.op.push(decl); } else if (decl->str() == ",") { if (!state1.op.empty()) { decl->astOperand1(state1.op.top()); state1.op.pop(); } if (!state1.op.empty()) { state1.op.top()->astOperand2(decl); state1.op.pop(); } state1.op.push(decl); } decl = decl->next(); } if (state1.op.size() > 1) { Token *lastName = state1.op.top(); state1.op.pop(); state1.op.top()->astOperand2(lastName); } decl = decl->next(); Token *colon = decl; compileExpression(decl, state1); tok->next()->astOperand1(tok); tok->next()->astOperand2(colon); return decl; } } std::vector<Token*> inner; Token* tok2 = skipDecl(tok->tokAt(2), &inner); for (Token* tok3 : inner) { AST_state state1(cpp); compileExpression(tok3, state1); } Token *init1 = nullptr; Token * const endPar = tok->linkAt(1); if (tok2 == tok->tokAt(2) && Token::Match(tok2, "%op%|(")) { init1 = tok2; AST_state state1(cpp); compileExpression(tok2, state1); if (Token::Match(init1, "( !!{")) { for (Token *tok3 = init1; tok3 && tok3 != tok3->link(); tok3 = tok3->next()) { if (tok3->astParent()) { while (tok3->astParent()) tok3 = tok3->astParent(); init1 = tok3; break; } if (!Token::Match(tok3, "%op%|(|[")) init1 = tok3; } } } else { while (tok2 && tok2 != endPar && tok2->str() != ";") { if (tok2->str() == "<" && tok2->link()) { tok2 = tok2->link(); } else if (Token::Match(tok2, "%name% )| %op%|(|[|{|.|:|::") || Token::Match(tok2->previous(), "[(;{}] %cop%|(")) { init1 = tok2; AST_state state1(cpp); compileExpression(tok2, state1); if (Token::Match(tok2, ";|)")) break; init1 = nullptr; } if (!tok2) // #7109 invalid code return nullptr; tok2 = tok2->next(); } } if (!tok2 || tok2->str() != ";") { if (tok2 == endPar && init1) { createAstAtTokenInner(init1->next(), endPar, cpp); tok->next()->astOperand2(init1); tok->next()->astOperand1(tok); } return tok2; } Token * const init = init1 ? init1 : tok2; Token * const semicolon1 = tok2; tok2 = tok2->next(); AST_state state2(cpp); compileExpression(tok2, state2); Token * const semicolon2 = tok2; if (!semicolon2) return nullptr; // invalid code #7235 if (semicolon2->str() == ";") { tok2 = tok2->next(); AST_state state3(cpp); if (Token::simpleMatch(tok2, "( {")) { state3.op.push(tok2->next()); tok2 = tok2->link()->next(); } compileExpression(tok2, state3); tok2 = findAstTop(semicolon1->next(), semicolon2); if (tok2) semicolon2->astOperand1(tok2); tok2 = findAstTop(semicolon2->next(), endPar); if (tok2) semicolon2->astOperand2(tok2); else if (!state3.op.empty()) semicolon2->astOperand2(state3.op.top()); semicolon1->astOperand2(semicolon2); } else { if (!cpp || state2.op.empty() || !Token::simpleMatch(state2.op.top(), ":")) throw InternalError(tok, "syntax error", InternalError::SYNTAX); semicolon1->astOperand2(state2.op.top()); } if (init != semicolon1) semicolon1->astOperand1(init->astTop()); tok->next()->astOperand1(tok); tok->next()->astOperand2(semicolon1); createAstAtTokenInner(endPar->link(), endPar, cpp); return endPar; } if (Token::simpleMatch(tok, "( {")) return tok; if (Token::Match(tok, "%type% <") && tok->linkAt(1) && !Token::Match(tok->linkAt(1), "> [({]")) return tok->linkAt(1); if (cpp && !tok->isKeyword() && Token::Match(tok, "%type% ::|<|%name%")) { Token *tok2 = tok; while (true) { if (Token::Match(tok2, "%name%|> :: %name%")) tok2 = tok2->tokAt(2); else if (Token::Match(tok2, "%name% <") && tok2->linkAt(1)) tok2 = tok2->linkAt(1); else break; } if (Token::Match(tok2, "%name%|> %name% {") && tok2->next()->varId() && iscpp11init(tok2->tokAt(2))) { Token *const tok1 = tok = tok2->next(); AST_state state(cpp); compileExpression(tok, state); createAstAtTokenInner(tok1->next(), tok1->linkAt(1), cpp); return tok; } } if (Token::Match(tok, "%type% %name%|*|&|::") && !Token::Match(tok, "return|new|delete")) { int typecount = 0; Token *typetok = tok; while (Token::Match(typetok, "%type%|::|*|&")) { if (typetok->isName() && !Token::simpleMatch(typetok->previous(), "::")) typecount++; typetok = typetok->next(); } if (Token::Match(typetok, "%var% =") && typetok->varId()) tok = typetok; // Do not create AST for function declaration if (typetok && typecount >= 2 && !Token::Match(tok, "return|throw") && Token::Match(typetok->previous(), "%name% ( !!*") && typetok->previous()->varId() == 0 && !typetok->previous()->isKeyword() && (Token::Match(typetok->link(), ") const|;|{") || Token::Match(typetok->link(), ") const| = delete ;"))) return typetok; } if (Token::Match(tok, "return|case") || (cpp && tok->str() == "throw") || !tok->previous() || Token::Match(tok, "%name% %op%|(|[|.|::|<|?|;") || (cpp && Token::Match(tok, "%name% {") && iscpp11init(tok->next())) || Token::Match(tok->previous(), "[;{}] %cop%|++|--|( !!{") || Token::Match(tok->previous(), "[;{}] %num%|%str%|%char%") || Token::Match(tok->previous(), "[;{}] delete new")) { if (cpp && (Token::Match(tok->tokAt(-2), "[;{}] new|delete %name%") || Token::Match(tok->tokAt(-3), "[;{}] :: new|delete %name%"))) tok = tok->previous(); Token * const tok1 = tok; AST_state state(cpp); if (Token::Match(tok, "%name% (")) state.functionCallEndPar = tok->linkAt(1); if (Token::simpleMatch(tok->tokAt(-1), "::") && (!tok->tokAt(-2) || !tok->tokAt(-2)->isName())) tok = tok->tokAt(-1); compileExpression(tok, state); Token * const endToken = tok; if (endToken == tok1 || !endToken) return tok1; createAstAtTokenInner(tok1->next(), endToken, cpp); return endToken->previous(); } if (cpp && tok->str() == "{" && iscpp11init(tok)) { Token * const tok1 = tok; AST_state state(cpp); compileExpression(tok, state); Token* const endToken = tok; if (endToken == tok1 || !endToken) return tok1; createAstAtTokenInner(tok1->next(), endToken, cpp); return endToken->previous(); } return tok; } void TokenList::createAst() const { for (Token *tok = mTokensFrontBack.front; tok; tok = tok ? tok->next() : nullptr) { Token* const nextTok = createAstAtToken(tok); if (precedes(nextTok, tok)) throw InternalError(tok, "Syntax Error: Infinite loop when creating AST.", InternalError::AST); tok = nextTok; } } namespace { struct OnException { std::function<void()> f; ~OnException() { #ifndef _MSC_VER if (std::uncaught_exception()) f(); #endif } }; } void TokenList::validateAst(bool print) const { OnException oe{[&] { if (print) mTokensFrontBack.front->printOut(std::cout); }}; // Check for some known issues in AST to avoid crash/hang later on std::set<const Token*> safeAstTokens; // list of "safe" AST tokens without endless recursion for (const Token *tok = mTokensFrontBack.front; tok; tok = tok->next()) { // Syntax error if binary operator only has 1 operand if ((tok->isAssignmentOp() || tok->isComparisonOp() || Token::Match(tok,"[|^/%]")) && tok->astOperand1() && !tok->astOperand2()) throw InternalError(tok, "Syntax Error: AST broken, binary operator has only one operand.", InternalError::AST); // Syntax error if we encounter "?" with operand2 that is not ":" if (tok->str() == "?") { if (!tok->astOperand1() || !tok->astOperand2()) throw InternalError(tok, "AST broken, ternary operator missing operand(s)", InternalError::AST); if (tok->astOperand2()->str() != ":") throw InternalError(tok, "Syntax Error: AST broken, ternary operator lacks ':'.", InternalError::AST); } // Check for endless recursion const Token* parent = tok->astParent(); if (parent) { std::set<const Token*> astTokens; // list of ancestors astTokens.insert(tok); do { if (safeAstTokens.find(parent) != safeAstTokens.end()) break; if (astTokens.find(parent) != astTokens.end()) throw InternalError(tok, "AST broken: endless recursion from '" + tok->str() + "'", InternalError::AST); astTokens.insert(parent); } while ((parent = parent->astParent()) != nullptr); safeAstTokens.insert(astTokens.cbegin(), astTokens.cend()); } else if (tok->str() == ";") { safeAstTokens.clear(); } else { safeAstTokens.insert(tok); } // Don't check templates if (tok->str() == "<" && tok->link()) { tok = tok->link(); continue; } if (tok->isCast()) { if (!tok->astOperand2() && precedes(tok->astOperand1(), tok)) throw InternalError(tok, "AST broken: '" + tok->str() + "' has improper operand.", InternalError::AST); if (tok->astOperand1() && tok->link()) { // skip casts (not part of the AST) tok = tok->link(); continue; } } if (findLambdaEndToken(tok)) { // skip lambda captures tok = tok->link(); continue; } // Check binary operators if (Token::Match(tok, "%or%|%oror%|%assign%|%comp%")) { // Skip pure virtual functions if (Token::simpleMatch(tok->previous(), ") = 0")) continue; // Skip operator definitions if (Token::simpleMatch(tok->previous(), "operator")) continue; // Skip incomplete code if (!tok->astOperand1() && !tok->astOperand2() && !tok->astParent()) continue; // Skip lambda assignment and/or initializer if (Token::Match(tok, "= {|^|[")) continue; // FIXME: Workaround broken AST assignment in type aliases if (Token::Match(tok->previous(), "%name% = %name%")) continue; if (!tok->astOperand1() || !tok->astOperand2()) throw InternalError(tok, "Syntax Error: AST broken, binary operator '" + tok->str() + "' doesn't have two operands.", InternalError::AST); } if (Token::Match(tok, "++|--") && !tok->astOperand1()) { throw InternalError(tok, "Syntax Error: AST broken, operator '" + tok->str() + "' doesn't have an operand.", InternalError::AST); } // Check control blocks and asserts if (Token::Match(tok->previous(), "if|while|for|switch|assert|ASSERT (")) { if (!tok->astOperand1() || !tok->astOperand2()) throw InternalError(tok, "Syntax Error: AST broken, '" + tok->strAt(-1) + "' doesn't have two operands.", InternalError::AST); } if (tok->str() == "case" && !tok->astOperand1()) { throw InternalError(tok, "Syntax Error: AST broken, 'case' doesn't have an operand.", InternalError::AST); } // Check member access if (Token::Match(tok, "%var% .")) { if (!tok->astParent()) { throw InternalError( tok, "Syntax Error: AST broken, '" + tok->str() + "' doesn't have a parent.", InternalError::AST); } if (!tok->next()->astOperand1() || !tok->next()->astOperand2()) { const std::string& op = tok->next()->originalName().empty() ? tok->strAt(1) : tok->next()->originalName(); throw InternalError( tok, "Syntax Error: AST broken, '" + op + "' doesn't have two operands.", InternalError::AST); } } } } std::string TokenList::getOrigFile(const Token *tok) const { return mOrigFiles.at(tok->fileIndex()); } const std::string& TokenList::file(const Token *tok) const { return mFiles.at(tok->fileIndex()); } std::string TokenList::fileLine(const Token *tok) const { return ErrorMessage::FileLocation(tok, this).stringify(); } bool TokenList::validateToken(const Token* tok) const { if (!tok) return true; for (const Token *t = mTokensFrontBack.front; t; t = t->next()) { if (tok==t) return true; } return false; } void TokenList::simplifyPlatformTypes() { if (!mSettings) return; const bool isCPP11 = isCPP() && (mSettings->standards.cpp >= Standards::CPP11); enum : std::uint8_t { isLongLong, isLong, isInt } type; /** @todo This assumes a flat address space. Not true for segmented address space (FAR *). */ if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_long) type = isLong; else if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_long_long) type = isLongLong; else if (mSettings->platform.sizeof_size_t == mSettings->platform.sizeof_int) type = isInt; else return; for (Token *tok = front(); tok; tok = tok->next()) { // pre-check to reduce unneeded match calls if (!Token::Match(tok, "std| ::| %type%")) continue; bool isUnsigned; if (Token::Match(tok, "std| ::| size_t|uintptr_t|uintmax_t")) { if (isCPP11 && tok->strAt(-1) == "using" && tok->strAt(1) == "=") continue; isUnsigned = true; } else if (Token::Match(tok, "std| ::| ssize_t|ptrdiff_t|intptr_t|intmax_t")) { if (isCPP11 && tok->strAt(-1) == "using" && tok->strAt(1) == "=") continue; isUnsigned = false; } else continue; bool inStd = false; if (tok->str() == "::") { tok->deleteThis(); } else if (tok->str() == "std") { if (tok->strAt(1) != "::") continue; inStd = true; tok->deleteNext(); tok->deleteThis(); } if (inStd) tok->originalName("std::" + tok->str()); else tok->originalName(tok->str()); if (isUnsigned) tok->isUnsigned(true); switch (type) { case isLongLong: tok->isLong(true); tok->str("long"); break; case isLong: tok->str("long"); break; case isInt: tok->str("int"); break; } } const std::string platform_type(mSettings->platform.toString()); for (Token *tok = front(); tok; tok = tok->next()) { if (tok->tokType() != Token::eType && tok->tokType() != Token::eName) continue; const Library::PlatformType * const platformtype = mSettings->library.platform_type(tok->str(), platform_type); if (platformtype) { // check for namespace if (tok->strAt(-1) == "::") { const Token * tok1 = tok->tokAt(-2); // skip when non-global namespace defined if (tok1 && tok1->tokType() == Token::eName) continue; tok = tok->previous(); tok->deleteThis(); } tok->originalName(tok->str()); const bool isFunctionalPtrCast = (platformtype->mConstPtr || platformtype->mPointer || platformtype->mPtrPtr) && Token::Match(tok, "%name% [({]") && !Token::simpleMatch(tok->linkAt(1), ") ("); Token* start = isFunctionalPtrCast ? tok->tokAt(1) : nullptr; Token* end = isFunctionalPtrCast ? tok->linkAt(1) : nullptr; Token *typeToken; if (platformtype->mConstPtr) { tok->str("const"); tok->isSimplifiedTypedef(true); tok->insertToken("*")->isSimplifiedTypedef(true); tok->insertToken(platformtype->mType)->isSimplifiedTypedef(true); typeToken = tok; } else if (platformtype->mPointer) { tok->str(platformtype->mType); tok->isSimplifiedTypedef(true); typeToken = tok; tok->insertToken("*")->isSimplifiedTypedef(true); } else if (platformtype->mPtrPtr) { tok->str(platformtype->mType); tok->isSimplifiedTypedef(true); typeToken = tok; tok->insertToken("*")->isSimplifiedTypedef(true); tok->insertToken("*")->isSimplifiedTypedef(true); } else { tok->str(platformtype->mType); tok->isSimplifiedTypedef(true); typeToken = tok; } if (platformtype->mSigned) typeToken->isSigned(true); if (platformtype->mUnsigned) typeToken->isUnsigned(true); if (platformtype->mLong) typeToken->isLong(true); if (isFunctionalPtrCast) { start->str("("); end->str(")"); if (end == start->tokAt(1)) end->insertTokenBefore("0"); end = start->insertTokenBefore(")"); start = tok->insertTokenBefore("("); start->isSimplifiedTypedef(true); Token::createMutualLinks(start, end); } } } } void TokenList::simplifyStdType() { auto isVarDeclC = [](const Token* tok) -> bool { if (!Token::simpleMatch(tok, "}")) return false; tok = tok->link()->previous(); while (Token::Match(tok, "%name%")) { if (Token::Match(tok, "struct|union|enum")) return true; tok = tok->previous(); } return false; }; for (Token *tok = front(); tok; tok = tok->next()) { if (isC() && Token::Match(tok, "const|extern *|&|%name%") && (!tok->previous() || Token::Match(tok->previous(), "[;{}]"))) { if (Token::Match(tok->next(), "%name% !!;")) continue; if (isVarDeclC(tok->previous())) continue; tok->insertToken("int"); tok->next()->isImplicitInt(true); continue; } if (Token::Match(tok, "char|short|int|long|unsigned|signed|double|float") || (isC() && (!mSettings || (mSettings->standards.c >= Standards::C99)) && Token::Match(tok, "complex|_Complex"))) { bool isFloat= false; bool isSigned = false; bool isUnsigned = false; bool isComplex = false; int countLong = 0; Token* typeSpec = nullptr; Token* tok2 = tok; for (; tok2->next(); tok2 = tok2->next()) { if (tok2->str() == "long") { countLong++; if (!isFloat) typeSpec = tok2; } else if (tok2->str() == "short") { typeSpec = tok2; } else if (tok2->str() == "unsigned") isUnsigned = true; else if (tok2->str() == "signed") isSigned = true; else if (Token::Match(tok2, "float|double")) { isFloat = true; typeSpec = tok2; } else if (isC() && (!mSettings || (mSettings->standards.c >= Standards::C99)) && Token::Match(tok2, "complex|_Complex")) isComplex = !isFloat || tok2->str() == "_Complex" || Token::Match(tok2->next(), "*|&|%name%"); // Ensure that "complex" is not the variables name else if (Token::Match(tok2, "char|int")) { if (!typeSpec) typeSpec = tok2; } else break; } if (!typeSpec) { // unsigned i; or similar declaration if (!isComplex) { // Ensure that "complex" is not the variables name tok->str("int"); tok->isSigned(isSigned); tok->isUnsigned(isUnsigned); tok->isImplicitInt(true); } } else { typeSpec->isLong(typeSpec->isLong() || (isFloat && countLong == 1) || countLong > 1); typeSpec->isComplex(typeSpec->isComplex() || (isFloat && isComplex)); typeSpec->isSigned(typeSpec->isSigned() || isSigned); typeSpec->isUnsigned(typeSpec->isUnsigned() || isUnsigned); // Remove specifiers const Token* tok3 = tok->previous(); tok2 = tok2->previous(); while (tok3 != tok2) { if (tok2 != typeSpec && (isComplex || !Token::Match(tok2, "complex|_Complex"))) // Ensure that "complex" is not the variables name tok2->deleteThis(); tok2 = tok2->previous(); } } } } } bool TokenList::isKeyword(const std::string &str) const { if (isCPP()) { // TODO: integrate into keywords? // types and literals are not handled as keywords static const std::unordered_set<std::string> cpp_types = {"bool", "false", "true"}; if (cpp_types.find(str) != cpp_types.end()) return false; if (mSettings) { const auto &cpp_keywords = Keywords::getAll(mSettings->standards.cpp); return cpp_keywords.find(str) != cpp_keywords.end(); } static const auto& latest_cpp_keywords = Keywords::getAll(Standards::cppstd_t::CPPLatest); return latest_cpp_keywords.find(str) != latest_cpp_keywords.end(); } // TODO: integrate into Keywords? // types are not handled as keywords static const std::unordered_set<std::string> c_types = {"char", "double", "float", "int", "long", "short"}; if (c_types.find(str) != c_types.end()) return false; if (mSettings) { const auto &c_keywords = Keywords::getAll(mSettings->standards.c); return c_keywords.find(str) != c_keywords.end(); } static const auto& latest_c_keywords = Keywords::getAll(Standards::cstd_t::CLatest); return latest_c_keywords.find(str) != latest_c_keywords.end(); } bool TokenList::isC() const { ASSERT_LANG(mLang != Standards::Language::None); // TODO: remove the fallback if (mLang == Standards::Language::None) return false; // treat as C++ by default return mLang == Standards::Language::C; } bool TokenList::isCPP() const { ASSERT_LANG(mLang != Standards::Language::None); // TODO: remove the fallback if (mLang == Standards::Language::None) return true; // treat as C++ by default return mLang == Standards::Language::CPP; } void TokenList::setLang(Standards::Language lang, bool force) { ASSERT_LANG(lang != Standards::Language::None); if (!force) { ASSERT_LANG(mLang == Standards::Language::None); } mLang = lang; }
83,167
C++
.cpp
2,014
30.800397
198
0.511745
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,164
checkunusedvar.cpp
danmar_cppcheck/lib/checkunusedvar.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkunusedvar.h" #include "astutils.h" #include "errortypes.h" #include "fwdanalysis.h" #include "library.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "utils.h" #include "valueflow.h" #include <algorithm> #include <cstdint> #include <list> #include <set> #include <utility> #include <vector> //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckUnusedVar instance; } static const CWE CWE563(563U); // Assignment to Variable without Use ('Unused Variable') static const CWE CWE665(665U); // Improper Initialization /** Is scope a raii class scope */ static bool isRaiiClassScope(const Scope *classScope) { return classScope && classScope->getDestructor() != nullptr; } /** Is ValueType a raii class? */ static bool isRaiiClass(const ValueType *valueType, bool cpp, bool defaultReturn = true) { if (!cpp) return false; if (!valueType) return defaultReturn; if ((valueType->smartPointerType && isRaiiClassScope(valueType->smartPointerType->classScope)) || (!valueType->smartPointerType && valueType->type == ValueType::Type::SMART_POINTER)) return true; switch (valueType->type) { case ValueType::Type::UNKNOWN_TYPE: case ValueType::Type::NONSTD: return defaultReturn; case ValueType::Type::RECORD: if (isRaiiClassScope(valueType->typeScope)) return true; return defaultReturn; case ValueType::Type::POD: case ValueType::Type::SMART_POINTER: case ValueType::Type::CONTAINER: case ValueType::Type::ITERATOR: case ValueType::Type::VOID: case ValueType::Type::BOOL: case ValueType::Type::CHAR: case ValueType::Type::SHORT: case ValueType::Type::WCHAR_T: case ValueType::Type::INT: case ValueType::Type::LONG: case ValueType::Type::LONGLONG: case ValueType::Type::UNKNOWN_INT: case ValueType::Type::FLOAT: case ValueType::Type::DOUBLE: case ValueType::Type::LONGDOUBLE: return false; } return defaultReturn; } /** * @brief This class is used create a list of variables within a function. */ class Variables { public: enum VariableType : std::uint8_t { standard, array, pointer, reference, pointerArray, referenceArray, pointerPointer, none }; /** Store information about variable usage */ class VariableUsage { public: explicit VariableUsage(const Variable *var = nullptr, VariableType type = standard, bool read = false, bool write = false, bool modified = false, bool allocateMemory = false) : _var(var), _lastAccess(var ? var->nameToken() : nullptr), mType(type), _read(read), _write(write), _modified(modified), _allocateMemory(allocateMemory) {} /** variable is used.. set both read+write */ void use() { _read = true; _write = true; } /** is variable unused? */ bool unused() const { return (!_read && !_write); } std::set<nonneg int> _aliases; std::set<const Scope*> _assignments; const Variable* _var; const Token* _lastAccess; VariableType mType; bool _read; bool _write; bool _modified; // read/modify/write bool _allocateMemory; }; void clear() { mVarUsage.clear(); } const std::map<nonneg int, VariableUsage> &varUsage() const { return mVarUsage; } void addVar(const Variable *var, VariableType type, bool write_); void allocateMemory(nonneg int varid, const Token* tok); void read(nonneg int varid, const Token* tok); void readAliases(nonneg int varid, const Token* tok); void readAll(nonneg int varid, const Token* tok); void write(nonneg int varid, const Token* tok); void writeAliases(nonneg int varid, const Token* tok); void writeAll(nonneg int varid, const Token* tok); void use(nonneg int varid, const Token* tok); void modified(nonneg int varid, const Token* tok); VariableUsage *find(nonneg int varid); void alias(nonneg int varid1, nonneg int varid2, bool replace); void erase(nonneg int varid) { mVarUsage.erase(varid); } void eraseAliases(nonneg int varid); void eraseAll(nonneg int varid); void clearAliases(nonneg int varid); private: std::map<nonneg int, VariableUsage> mVarUsage; }; /** * Alias the 2 given variables. Either replace the existing aliases if * they exist or merge them. You would replace an existing alias when this * assignment is in the same scope as the previous assignment. You might * merge the aliases when this assignment is in a different scope from the * previous assignment depending on the relationship of the 2 scopes. */ void Variables::alias(nonneg int varid1, nonneg int varid2, bool replace) { VariableUsage *var1 = find(varid1); VariableUsage *var2 = find(varid2); if (!var1 || !var2) return; // alias to self if (varid1 == varid2) { var1->use(); return; } if (replace) { // remove var1 from all aliases for (auto i = var1->_aliases.cbegin(); i != var1->_aliases.cend(); ++i) { VariableUsage *temp = find(*i); if (temp) temp->_aliases.erase(var1->_var->declarationId()); } // remove all aliases from var1 var1->_aliases.clear(); } // var1 gets all var2s aliases for (auto i = var2->_aliases.cbegin(); i != var2->_aliases.cend(); ++i) { if (*i != varid1) var1->_aliases.insert(*i); } // var2 is an alias of var1 var2->_aliases.insert(varid1); var1->_aliases.insert(varid2); if (var2->mType == Variables::pointer) { var2->_read = true; } } void Variables::clearAliases(nonneg int varid) { VariableUsage *usage = find(varid); if (usage) { // remove usage from all aliases for (auto i = usage->_aliases.cbegin(); i != usage->_aliases.cend(); ++i) { VariableUsage *temp = find(*i); if (temp) temp->_aliases.erase(usage->_var->declarationId()); } // remove all aliases from usage usage->_aliases.clear(); } } void Variables::eraseAliases(nonneg int varid) { VariableUsage *usage = find(varid); if (usage) { for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases) erase(*aliases); } } void Variables::eraseAll(nonneg int varid) { eraseAliases(varid); erase(varid); } void Variables::addVar(const Variable *var, VariableType type, bool write_) { if (var->declarationId() > 0) { mVarUsage.insert(std::make_pair(var->declarationId(), VariableUsage(var, type, false, write_, false))); } } void Variables::allocateMemory(nonneg int varid, const Token* tok) { VariableUsage *usage = find(varid); if (usage) { usage->_allocateMemory = true; usage->_lastAccess = tok; } } void Variables::read(nonneg int varid, const Token* tok) { VariableUsage *usage = find(varid); if (usage) { usage->_read = true; if (tok) usage->_lastAccess = tok; } } void Variables::readAliases(nonneg int varid, const Token* tok) { const VariableUsage *usage = find(varid); if (usage) { for (nonneg int const aliases : usage->_aliases) { VariableUsage *aliased = find(aliases); if (aliased) { aliased->_read = true; aliased->_lastAccess = tok; } } } } void Variables::readAll(nonneg int varid, const Token* tok) { read(varid, tok); readAliases(varid, tok); } void Variables::write(nonneg int varid, const Token* tok) { VariableUsage *usage = find(varid); if (usage) { usage->_write = true; if (!usage->_var->isStatic() && !Token::simpleMatch(tok->next(), "= 0 ;")) usage->_read = false; usage->_lastAccess = tok; } } void Variables::writeAliases(nonneg int varid, const Token* tok) { VariableUsage *usage = find(varid); if (usage) { for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) { aliased->_write = true; aliased->_lastAccess = tok; } } } } void Variables::writeAll(nonneg int varid, const Token* tok) { write(varid, tok); writeAliases(varid, tok); } void Variables::use(nonneg int varid, const Token* tok) { VariableUsage *usage = find(varid); if (usage) { usage->use(); usage->_lastAccess = tok; for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) { aliased->use(); aliased->_lastAccess = tok; } } } } void Variables::modified(nonneg int varid, const Token* tok) { VariableUsage *usage = find(varid); if (usage) { if (!usage->_var->isStatic()) usage->_read = false; usage->_modified = true; usage->_lastAccess = tok; for (auto aliases = usage->_aliases.cbegin(); aliases != usage->_aliases.cend(); ++aliases) { VariableUsage *aliased = find(*aliases); if (aliased) { aliased->_modified = true; aliased->_lastAccess = tok; } } } } Variables::VariableUsage *Variables::find(nonneg int varid) { if (varid) { const std::map<nonneg int, VariableUsage>::iterator i = mVarUsage.find(varid); if (i != mVarUsage.end()) return &i->second; } return nullptr; } static const Token* doAssignment(Variables &variables, const Token *tok, bool dereference, const Scope *scope) { // a = a + b; if (Token::Match(tok, "%var% = %var% !!;")) { const Token* rhsVarTok = tok->tokAt(2); if (tok->varId() == rhsVarTok->varId()) { return rhsVarTok; } } if (Token::Match(tok, "%var% %assign%") && tok->strAt(1) != "=") return tok->next(); const Token* const tokOld = tok; // check for aliased variable const nonneg int varid1 = tok->varId(); Variables::VariableUsage *var1 = variables.find(varid1); if (var1) { // jump behind '=' tok = tok->next(); while (!tok->isAssignmentOp()) { if (tok->varId()) variables.read(tok->varId(), tok); tok = tok->next(); } tok = tok->next(); if (Token::Match(tok, "( const| struct|union| %type% * ) ( (")) tok = tok->link()->next(); if (Token::Match(tok, "( [(<] const| struct|union| %type% *| [>)]")) tok = tok->next(); if (Token::Match(tok, "(| &| %name%") || (Token::Match(tok->next(), "< const| struct|union| %type% *| > ( &| %name%"))) { bool addressOf = false; if (Token::Match(tok, "%var% .")) variables.use(tok->varId(), tok); // use = read + write // check for C style cast if (tok->str() == "(") { tok = tok->next(); if (tok->str() == "const") tok = tok->next(); if (Token::Match(tok, "struct|union")) tok = tok->next(); while ((tok->isName() && tok->varId() == 0) || (tok->str() == "*") || (tok->str() == ")")) tok = tok->next(); if (tok->str() == "&") { addressOf = true; tok = tok->next(); } else if (tok->str() == "(") { tok = tok->next(); if (tok->str() == "&") { addressOf = true; tok = tok->next(); } } else if (Token::Match(tok, "%cop% %var%")) { variables.read(tok->next()->varId(), tok); } } // check for C++ style cast else if (tok->str().find("cast") != std::string::npos && tok->strAt(1) == "<") { tok = tok->tokAt(2); if (tok->str() == "const") tok = tok->next(); if (Token::Match(tok, "struct|union")) tok = tok->next(); tok = tok->next(); if (!tok) return tokOld; if (tok->str() == "*") tok = tok->next(); tok = tok->tokAt(2); if (!tok) return tokOld; if (tok->str() == "&") { addressOf = true; tok = tok->next(); } } // no cast, no ? else if (!Token::Match(tok, "%name% ?")) { if (tok->str() == "&") { addressOf = true; tok = tok->next(); } else if (tok->str() == "new") return tokOld; } // check if variable is local const nonneg int varid2 = tok->varId(); const Variables::VariableUsage* var2 = variables.find(varid2); if (var2) { // local variable (alias or read it) if (var1->mType == Variables::pointer || var1->mType == Variables::pointerArray) { if (dereference) variables.read(varid2, tok); else { if (addressOf || var2->mType == Variables::array || var2->mType == Variables::pointer) { bool replace = true; // pointerArray => don't replace if (var1->mType == Variables::pointerArray) replace = false; // check if variable declared in same scope else if (scope == var1->_var->scope()) replace = true; // not in same scope as declaration else { // no other assignment in this scope if (var1->_assignments.find(scope) == var1->_assignments.end() || scope->type == Scope::eSwitch) { // nothing to replace // cppcheck-suppress duplicateBranch - remove when TODO below is address if (var1->_assignments.empty()) replace = false; // this variable has previous assignments else { // TODO: determine if existing aliases should be replaced or merged replace = false; } } // assignment in this scope else { // replace when only one other assignment, merge them otherwise replace = (var1->_assignments.size() == 1); } } variables.alias(varid1, varid2, replace); } else if (tok->strAt(1) == "?") { if (var2->mType == Variables::reference) variables.readAliases(varid2, tok); else variables.read(varid2, tok); } else { variables.readAll(varid2, tok); } } } else if (var1->mType == Variables::reference) { variables.alias(varid1, varid2, true); } else if (var1->mType == Variables::standard && addressOf) { variables.alias(varid1, varid2, true); } else { if ((var2->mType == Variables::pointer || var2->mType == Variables::pointerArray) && tok->strAt(1) == "[") variables.readAliases(varid2, tok); variables.read(varid2, tok); } } else { // not a local variable (or an unsupported local variable) if (var1->mType == Variables::pointer && !dereference) { // check if variable declaration is in this scope if (var1->_var->scope() == scope) { // If variable is used in RHS then "use" variable for (const Token *rhs = tok; rhs && rhs->str() != ";"; rhs = rhs->next()) { if (rhs->varId() == varid1) { variables.use(varid1, tok); break; } } variables.clearAliases(varid1); } else { // no other assignment in this scope if (var1->_assignments.find(scope) == var1->_assignments.end()) { /** * @todo determine if existing aliases should be discarded */ } // this assignment replaces the last assignment in this scope else { // aliased variables in a larger scope are not supported // remove all aliases variables.clearAliases(varid1); } } } } } else tok = tokOld; var1->_assignments.insert(scope); } // check for alias to struct member // char c[10]; a.b = c; else if (Token::Match(tok->tokAt(-2), "%name% .")) { const Token *rhsVarTok = tok->tokAt(2); if (rhsVarTok && rhsVarTok->varId()) { const nonneg int varid2 = rhsVarTok->varId(); const Variables::VariableUsage *var2 = variables.find(varid2); // struct member aliased to local variable if (var2 && (var2->mType == Variables::array || var2->mType == Variables::pointer)) { // erase aliased variable and all variables that alias it // to prevent false positives variables.eraseAll(varid2); } } } // Possible pointer alias else if (Token::Match(tok, "%name% = %name% ;")) { const nonneg int varid2 = tok->tokAt(2)->varId(); const Variables::VariableUsage *var2 = variables.find(varid2); if (var2 && (var2->mType == Variables::array || var2->mType == Variables::pointer)) { variables.use(varid2,tok); } } return tok; } static bool isPartOfClassStructUnion(const Token* tok) { for (; tok; tok = tok->previous()) { if (tok->str() == "}" || tok->str() == ")") tok = tok->link(); else if (tok->str() == "(") return false; else if (tok->str() == "{") { return (tok->strAt(-1) == "struct" || tok->strAt(-2) == "struct" || tok->strAt(-1) == "class" || tok->strAt(-2) == "class" || tok->strAt(-1) == "union" || tok->strAt(-2) == "union"); } } return false; } static bool isVarDecl(const Token *tok) { return tok && tok->variable() && tok->variable()->nameToken() == tok; } // Skip [ .. ] static const Token * skipBrackets(const Token *tok) { while (tok && tok->str() == "[") tok = tok->link()->next(); return tok; } // Skip [ .. ] . x static const Token * skipBracketsAndMembers(const Token *tok) { while (tok) { if (tok->str() == "[") tok = tok->link()->next(); else if (Token::Match(tok, ". %name%")) tok = tok->tokAt(2); else break; } return tok; } static void useFunctionArgs(const Token *tok, Variables& variables) { // TODO: Match function args to see if they are const or not. Assume that const data is not written. if (!tok) return; if (tok->str() == ",") { useFunctionArgs(tok->astOperand1(), variables); useFunctionArgs(tok->astOperand2(), variables); } else if (Token::Match(tok, "[+:]") && (!tok->valueType() || tok->valueType()->pointer)) { useFunctionArgs(tok->astOperand1(), variables); useFunctionArgs(tok->astOperand2(), variables); } else if (tok->variable() && tok->variable()->isArray()) { variables.use(tok->varId(), tok); } } //--------------------------------------------------------------------------- // Usage of function variables //--------------------------------------------------------------------------- void CheckUnusedVar::checkFunctionVariableUsage_iterateScopes(const Scope* const scope, Variables& variables) { // Find declarations if the scope is executable.. if (scope->isExecutable()) { // Find declarations for (auto i = scope->varlist.cbegin(); i != scope->varlist.cend(); ++i) { if (i->isThrow() || i->isExtern()) continue; Variables::VariableType type = Variables::none; if (i->isArray() && (i->nameToken()->strAt(-1) == "*" || i->nameToken()->strAt(-2) == "*")) type = Variables::pointerArray; else if (i->isArray() && i->nameToken()->strAt(-1) == "&") type = Variables::referenceArray; else if (i->isArray()) type = Variables::array; else if (i->isReference() && !(i->valueType() && i->valueType()->type == ValueType::UNKNOWN_TYPE && Token::simpleMatch(i->typeStartToken(), "auto"))) type = Variables::reference; else if (i->nameToken()->strAt(-1) == "*" && i->nameToken()->strAt(-2) == "*") type = Variables::pointerPointer; else if (i->isPointerToArray()) type = Variables::pointerPointer; else if (i->isPointer()) type = Variables::pointer; else if (mTokenizer->isC() || i->typeEndToken()->isStandardType() || i->isStlType() || isRecordTypeWithoutSideEffects(i->type()) || mSettings->library.detectContainer(i->typeStartToken()) || mSettings->library.getTypeCheck("unusedvar", i->typeStartToken()->str()) == Library::TypeCheck::check) type = Variables::standard; if (type == Variables::none || isPartOfClassStructUnion(i->typeStartToken())) continue; const Token* defValTok = i->nameToken()->next(); if (Token::Match(i->nameToken()->previous(), "* %var% ) (")) // function pointer. Jump behind parameter list. defValTok = defValTok->linkAt(1)->next(); for (; defValTok; defValTok = defValTok->next()) { if (defValTok->str() == "[") defValTok = defValTok->link(); else if (defValTok->str() == "(" || defValTok->str() == "{" || defValTok->str() == "=" || defValTok->str() == ":") { variables.addVar(&*i, type, true); break; } else if (defValTok->str() == ";" || defValTok->str() == "," || defValTok->str() == ")") { variables.addVar(&*i, type, i->isStatic() && i->scope()->type != Scope::eFunction); break; } } if (i->isArray() && i->isClass() && // Array of class/struct members. Initialized by ctor except for std::array !(i->isStlType() && i->valueType() && i->valueType()->containerTypeToken && i->valueType()->containerTypeToken->isStandardType())) variables.write(i->declarationId(), i->nameToken()); if (i->isArray() && Token::Match(i->nameToken(), "%name% [ %var% ]")) // Array index variable read. variables.read(i->nameToken()->tokAt(2)->varId(), i->nameToken()); if (defValTok && defValTok->next()) { // simple assignment "var = 123" if (defValTok->str() == "=" && defValTok->strAt(1) != "{") { doAssignment(variables, i->nameToken(), false, scope); } else { // could be "var = {...}" OR "var{...}" (since C++11) const Token* tokBraceStart = nullptr; if (Token::simpleMatch(defValTok, "= {")) { // "var = {...}" tokBraceStart = defValTok->next(); } else if (defValTok->str() == "{") { // "var{...}" tokBraceStart = defValTok; } if (tokBraceStart) { for (const Token* tok = tokBraceStart->next(); tok && tok != tokBraceStart->link(); tok = tok->next()) { if (tok->varId()) { // Variables used to initialize the array read. variables.read(tok->varId(), i->nameToken()); } } } } } } } // Check variable usage const Token *tok; if (scope->type == Scope::eFunction) tok = scope->bodyStart->next(); else tok = scope->classDef->next(); for (; tok && tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() == "{" && tok != scope->bodyStart && !tok->previous()->varId()) { if (std::any_of(scope->nestedList.cbegin(), scope->nestedList.cend(), [&](const Scope* s) { return s->bodyStart == tok; })) { checkFunctionVariableUsage_iterateScopes(tok->scope(), variables); // Scan child scope tok = tok->link(); } if (!tok) break; } if (Token::Match(tok, "asm ( %str% )")) { variables.clear(); break; } // templates if (tok->isName() && endsWith(tok->str(), '>')) { // TODO: This is a quick fix to handle when constants are used // as template parameters. Try to handle this better, perhaps // only remove constants. variables.clear(); } else if (Token::Match(tok->previous(), "[;{}]")) { for (const Token* tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->varId()) { // Is this a variable declaration? const Variable *var = tok2->variable(); if (!var || var->nameToken() != tok2) continue; // Mark template parameters used in declaration as use.. if (tok2->strAt(-1) == ">") { for (const Token *tok3 = tok; tok3 != tok2; tok3 = tok3->next()) { if (tok3->varId()) variables.use(tok3->varId(), tok3); } } // Skip variable declaration.. tok = tok2->next(); if (Token::Match(tok, "( %name% )")) // Simple initialization through copy ctor tok = tok->next(); else if (Token::Match(tok, "= %var% ;")) { // Simple initialization tok = tok->next(); if (!var->isReference()) variables.read(tok->varId(), tok); } else if (tok->str() == "[" && Token::simpleMatch(skipBrackets(tok),"= {")) { const Token * const rhs1 = skipBrackets(tok)->next(); for (const Token *rhs = rhs1->link(); rhs != rhs1; rhs = rhs->previous()) { if (rhs->varId()) variables.readAll(rhs->varId(), rhs); } } else if (var->typeEndToken()->str() == ">") // Be careful with types like std::vector tok = tok->previous(); break; } if (Token::Match(tok2, "[;({=]")) break; } } // Freeing memory (not considered "using" the pointer if it was also allocated in this function) if ((Token::Match(tok, "%name% ( %var% )") && mSettings->library.getDeallocFuncInfo(tok)) || (tok->isCpp() && (Token::Match(tok, "delete %var% ;") || Token::Match(tok, "delete [ ] %var% ;")))) { nonneg int varid = 0; if (tok->str() != "delete") { const Token *varTok = tok->tokAt(2); varid = varTok->varId(); tok = varTok->next(); } else if (tok->strAt(1) == "[") { const Token *varTok = tok->tokAt(3); varid = varTok->varId(); tok = varTok; } else { varid = tok->next()->varId(); tok = tok->next(); } const Variables::VariableUsage *const var = variables.find(varid); if (var) { if (!var->_aliases.empty()) variables.use(varid, tok); else if (!var->_allocateMemory) variables.readAll(varid, tok); } } else if (Token::Match(tok, "return|throw")) { for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->varId()) variables.readAll(tok2->varId(), tok); else if (tok2->str() == ";") break; } } // assignment else if (Token::Match(tok, "*| ++|--| %name% ++|--| %assign%") || Token::Match(tok, "*| ( const| %type% *| ) %name% %assign%")) { bool dereference = false; bool pre = false; bool post = false; if (tok->str() == "*") { dereference = true; tok = tok->next(); } if (Token::Match(tok, "( const| %type% *| ) %name% %assign%")) tok = tok->link()->next(); else if (tok->str() == "(") tok = tok->next(); if (tok->tokType() == Token::eIncDecOp) { pre = true; tok = tok->next(); } if (tok->next()->tokType() == Token::eIncDecOp) post = true; const nonneg int varid1 = tok->varId(); const Token * const start = tok; // assignment in while head.. bool inwhile = false; { const Token *parent = tok->astParent(); while (parent) { if (Token::simpleMatch(parent->previous(), "while (")) { inwhile = true; break; } parent = parent->astParent(); } } tok = doAssignment(variables, tok, dereference, scope); if (tok && tok->isAssignmentOp() && tok->str() != "=") { variables.use(varid1, tok); if (Token::Match(tok, "%assign% %name%")) { tok = tok->next(); variables.read(tok->varId(), tok); } } if (pre || post) variables.use(varid1, tok); if (dereference) { const Variables::VariableUsage *const var = variables.find(varid1); if (var && var->mType == Variables::array) variables.write(varid1, tok); variables.writeAliases(varid1, tok); variables.read(varid1, tok); } else { const Variables::VariableUsage *const var = variables.find(varid1); if (var && (inwhile || start->strAt(-1) == ",")) { variables.use(varid1, tok); } else if (var && var->mType == Variables::reference) { variables.writeAliases(varid1, tok); variables.read(varid1, tok); } // Consider allocating memory separately because allocating/freeing alone does not constitute using the variable else if (var && var->mType == Variables::pointer && Token::Match(start, "%name% =") && findAllocFuncCallToken(start->next()->astOperand2(), mSettings->library)) { const Token *allocFuncCallToken = findAllocFuncCallToken(start->next()->astOperand2(), mSettings->library); const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(allocFuncCallToken); bool allocateMemory = !allocFunc || Library::ismemory(allocFunc->groupId); if (allocFuncCallToken->str() == "new") { const Token *type = allocFuncCallToken->next(); // skip nothrow if (type->isCpp() && (Token::simpleMatch(type, "( nothrow )") || Token::simpleMatch(type, "( std :: nothrow )"))) type = type->link()->next(); // is it a user defined type? if (!type->isStandardType()) { const Variable *variable = start->variable(); if (!variable || !isRecordTypeWithoutSideEffects(variable->type())) allocateMemory = false; } } if (allocateMemory) variables.allocateMemory(varid1, tok); else variables.write(varid1, tok); } else if (varid1 && Token::Match(tok, "%varid% .", varid1)) { variables.read(varid1, tok); variables.write(varid1, start); } else { variables.write(varid1, tok); } } const Variables::VariableUsage * const var2 = variables.find(tok->varId()); if (var2) { if (var2->mType == Variables::reference) { variables.writeAliases(tok->varId(), tok); variables.read(tok->varId(), tok); } else if (tok->varId() != varid1 && Token::Match(tok, "%name% .|[")) variables.read(tok->varId(), tok); else if (tok->varId() != varid1 && var2->mType == Variables::standard && tok->strAt(-1) != "&") variables.use(tok->varId(), tok); } const Token * const equal = skipBracketsAndMembers(tok->next()); // checked for chained assignments if (tok != start && equal && equal->str() == "=") { const nonneg int varId = tok->varId(); const Variables::VariableUsage * const var = variables.find(varId); if (var && var->mType != Variables::reference) { variables.read(varId,tok); } tok = tok->previous(); } } // assignment else if ((Token::Match(tok, "%name% [") && Token::simpleMatch(skipBracketsAndMembers(tok->next()), "=")) || (tok->isUnaryOp("*") && astIsLHS(tok) && Token::simpleMatch(tok->astParent(), "=") && Token::simpleMatch(tok->astOperand1(), "+"))) { const Token *eq = tok; while (eq && !eq->isAssignmentOp()) eq = eq->astParent(); const bool deref = eq && eq->astOperand1() && eq->astOperand1()->valueType() && eq->astOperand1()->valueType()->pointer == 0U; if (tok->str() == "*") { tok = tok->tokAt(2); if (tok->str() == "(") tok = tok->link()->next(); } const nonneg int varid = tok->varId(); const Variables::VariableUsage *var = variables.find(varid); if (var) { // Consider allocating memory separately because allocating/freeing alone does not constitute using the variable if (var->mType == Variables::pointer && ((tok->isCpp() && Token::simpleMatch(skipBrackets(tok->next()), "= new")) || (Token::Match(skipBrackets(tok->next()), "= %name% (") && mSettings->library.getAllocFuncInfo(tok->tokAt(2))))) { variables.allocateMemory(varid, tok); } else if (var->mType == Variables::pointer || var->mType == Variables::reference) { variables.read(varid, tok); variables.writeAliases(varid, tok); } else if (var->mType == Variables::pointerArray) { tok = doAssignment(variables, tok, deref, scope); } else variables.writeAll(varid, tok); } } else if (tok->isCpp() && Token::Match(tok, "[;{}] %var% <<")) { variables.erase(tok->next()->varId()); } else if (Token::Match(tok, "& %var%")) { if (tok->astOperand2()) { // bitop variables.read(tok->next()->varId(), tok); } else // addressof variables.use(tok->next()->varId(), tok); // use = read + write } else if (Token::Match(tok, ">>|>>= %name%")) { if (isLikelyStreamRead(tok)) variables.use(tok->next()->varId(), tok); // use = read + write else variables.read(tok->next()->varId(), tok); } else if (Token::Match(tok, "%var% >>|&") && Token::Match(tok->previous(), "[{};:]")) { variables.read(tok->varId(), tok); } else if (isLikelyStreamRead(tok->previous())) { variables.use(tok->varId(), tok); } // function parameter else if (Token::Match(tok, "[(,] %var% [")) { variables.use(tok->next()->varId(), tok); // use = read + write } else if (Token::Match(tok, "[(,] %var% [,)]") && tok->strAt(-1) != "*") { variables.use(tok->next()->varId(), tok); // use = read + write } else if (Token::Match(tok, "[(,] & %var% [,)]")) { variables.eraseAll(tok->tokAt(2)->varId()); } else if (Token::Match(tok, "[(,] (") && Token::Match(tok->linkAt(1), ") %var% [,)[]")) { variables.use(tok->linkAt(1)->next()->varId(), tok); // use = read + write } else if (Token::Match(tok, "[(,] *| *| %var%")) { const Token* vartok = tok->next(); while (vartok->str() == "*") vartok = vartok->next(); if (!(vartok->variable() && vartok == vartok->variable()->nameToken()) && !(tok->str() == "(" && !Token::Match(tok->previous(), "%name%"))) variables.use(vartok->varId(), vartok); } // function else if (Token::Match(tok, "%name% (")) { if (tok->varId() && !tok->function()) // operator() variables.use(tok->varId(), tok); else variables.read(tok->varId(), tok); useFunctionArgs(tok->next()->astOperand2(), variables); } else if (Token::Match(tok, "std :: ref ( %var% )")) { variables.eraseAll(tok->tokAt(4)->varId()); } else if (Token::Match(tok->previous(), "[{,] %var% [,}]")) { variables.use(tok->varId(), tok); } else if (tok->varId() && Token::Match(tok, "%var% .")) { variables.use(tok->varId(), tok); // use = read + write } else if (tok->str() == ":" && (!tok->valueType() || tok->valueType()->pointer)) { if (tok->astOperand1()) variables.use(tok->astOperand1()->varId(), tok->astOperand1()); if (tok->astOperand2()) variables.use(tok->astOperand2()->varId(), tok->astOperand2()); } else if (tok->isExtendedOp() && tok->next() && tok->next()->varId() && tok->strAt(2) != "=" && !isVarDecl(tok->next())) { variables.readAll(tok->next()->varId(), tok); } else if (tok->varId() && !isVarDecl(tok) && tok->next() && (tok->strAt(1) == ")" || tok->next()->isExtendedOp())) { if (Token::Match(tok->tokAt(-2), "%name% ( %var% [,)]") && !(tok->tokAt(-2)->variable() && tok->tokAt(-2)->variable()->isReference())) variables.use(tok->varId(), tok); else variables.readAll(tok->varId(), tok); } else if (Token::Match(tok, "%var% ;") && Token::Match(tok->previous(), "[;{}:]")) { variables.readAll(tok->varId(), tok); } // ++|-- else if (tok->next() && tok->next()->tokType() == Token::eIncDecOp && tok->next()->astOperand1() && tok->next()->astOperand1()->varId()) { if (tok->next()->astParent()) variables.use(tok->next()->astOperand1()->varId(), tok); else variables.modified(tok->next()->astOperand1()->varId(), tok); } else if (tok->isAssignmentOp()) { for (const Token *tok2 = tok->next(); tok2 && tok2->str() != ";"; tok2 = tok2->next()) { if (tok2->varId()) { if (tok2->strAt(1) == "=") variables.write(tok2->varId(), tok); else if (tok2->next() && tok2->next()->isAssignmentOp()) variables.use(tok2->varId(), tok); else variables.read(tok2->varId(), tok); } } } else if (tok->variable() && tok->variable()->isClass() && tok->variable()->type() && (tok->variable()->type()->needInitialization == Type::NeedInitialization::False) && tok->strAt(1) == ";") { variables.write(tok->varId(), tok); } } } static bool isReturnedByRef(const Variable* var, const Function* func) { if (!func || !Function::returnsReference(func, true)) return false; const std::vector<const Token*> returns = Function::findReturns(func); return std::any_of(returns.begin(), returns.end(), [var](const Token* tok) { return tok->varId() == var->declarationId(); }); } void CheckUnusedVar::checkFunctionVariableUsage() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->checkLibrary && !mSettings->isPremiumEnabled("unusedVariable")) return; logChecker("CheckUnusedVar::checkFunctionVariableUsage"); // style // Parse all executing scopes.. const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); auto reportLibraryCfgError = [this](const Token* tok, const std::string& typeName) { if (mSettings->checkLibrary) { reportError(tok, Severity::information, "checkLibraryCheckType", "--check-library: Provide <type-checks><unusedvar> configuration for " + typeName); } }; // only check functions for (const Scope * scope : symbolDatabase->functionScopes) { // Bailout when there are lambdas or inline functions // TODO: Handle lambdas and inline functions properly const Token* lambdaOrInlineStart{}; const bool hasLambdaOrInline = scope->hasInlineOrLambdaFunction(&lambdaOrInlineStart); for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (findLambdaEndToken(tok)) // todo: handle lambdas break; if (Token::simpleMatch(tok, "try {")) // todo: check try blocks tok = tok->linkAt(1); const Token *varDecl = nullptr; if (tok->variable() && tok->variable()->nameToken() == tok) { const Token * eq = tok->next(); while (Token::simpleMatch(eq, "[")) eq = eq->link()->next(); if (Token::simpleMatch(eq, ") (") && Token::simpleMatch(eq->linkAt(1), ") =")) eq = eq->linkAt(1)->next(); if (Token::simpleMatch(eq, "=")) { varDecl = tok; tok = eq; } } // not assignment/initialization/increment => continue const bool isAssignment = tok->isAssignmentOp() && tok->astOperand1(); const bool isInitialization = (Token::Match(tok, "%var% (|{") && tok->variable() && tok->variable()->nameToken() == tok); const bool isIncrementOrDecrement = (tok->tokType() == Token::Type::eIncDecOp); if (!isAssignment && !isInitialization && !isIncrementOrDecrement) continue; bool isTrivialInit = false; if (isInitialization && Token::Match(tok, "%var% { }")) // don't warn for trivial initialization isTrivialInit = true; if (isIncrementOrDecrement && tok->astParent() && precedes(tok, tok->astOperand1())) continue; if (tok->str() == "=" && !(tok->valueType() && tok->valueType()->pointer) && isRaiiClass(tok->valueType(), tok->isCpp(), false)) continue; const bool isPointer = tok->valueType() && (tok->valueType()->pointer || tok->valueType()->type == ValueType::SMART_POINTER); if (tok->isName()) { if (isRaiiClass(tok->valueType(), tok->isCpp(), false) || (tok->valueType() && tok->valueType()->type == ValueType::RECORD && (!tok->valueType()->typeScope || !isRecordTypeWithoutSideEffects(tok->valueType()->typeScope->definedType)))) continue; tok = tok->next(); } if (!isInitialization && tok->astParent() && !tok->astParent()->isAssignmentOp() && tok->str() != "(") { const Token *parent = tok->astParent(); while (Token::Match(parent, "%oror%|%comp%|!|&&")) parent = parent->astParent(); if (!parent) continue; if (!Token::simpleMatch(parent->previous(), "if (")) continue; } // Do not warn about assignment with NULL if (isPointer && isNullOperand(tok->astOperand2())) continue; if (!tok->astOperand1()) continue; const Token *iteratorToken = tok->astOperand1(); while (Token::Match(iteratorToken, "[.*]")) iteratorToken = iteratorToken->astOperand1(); if (iteratorToken && iteratorToken->variable() && iteratorToken->variable()->typeEndToken()->str().find("iterator") != std::string::npos) continue; const Token *op1tok = tok->astOperand1(); while (Token::Match(op1tok, ".|[|*")) op1tok = op1tok->astOperand1(); // Assignment in macro => do not warn if (isAssignment && tok->isExpandedMacro() && op1tok && op1tok->isExpandedMacro()) continue; const Variable *op1Var = op1tok ? op1tok->variable() : nullptr; if (!op1Var && Token::Match(tok, "(|{") && tok->previous() && tok->previous()->variable()) op1Var = tok->previous()->variable(); if (hasLambdaOrInline) { if (!op1Var || !lambdaOrInlineStart) continue; if (precedes(op1Var->nameToken(), lambdaOrInlineStart)) continue; } std::string bailoutTypeName; if (op1Var) { if (op1Var->isReference() && op1Var->nameToken() != tok->astOperand1()) // todo: check references continue; if (op1Var->isStatic()) // todo: check static variables continue; if (op1Var->nameToken()->isAttributeUnused()) continue; // Avoid FP for union.. if (op1Var->type() && op1Var->type()->isUnionType()) continue; // Bailout for unknown template classes, we have no idea what side effects such assignments have if (mTokenizer->isCPP() && op1Var->isClass() && (!op1Var->valueType() || op1Var->valueType()->type == ValueType::Type::UNKNOWN_TYPE)) { // Check in the library if we should bailout or not.. std::string typeName = op1Var->getTypeName(); if (startsWith(typeName, "::")) typeName.erase(typeName.begin(), typeName.begin() + 2); switch (mSettings->library.getTypeCheck("unusedvar", typeName)) { case Library::TypeCheck::def: bailoutTypeName = typeName; break; case Library::TypeCheck::check: break; case Library::TypeCheck::suppress: case Library::TypeCheck::checkFiniteLifetime: continue; } } } // Is there a redundant assignment? const Token *start = tok->findExpressionStartEndTokens().second->next(); const Token *expr = varDecl ? varDecl : tok->astOperand1(); if (isInitialization) expr = tok->previous(); // Is variable in lhs a union member? if (tok->previous() && tok->previous()->variable() && tok->previous()->variable()->nameToken()->scope()->type == Scope::eUnion) continue; FwdAnalysis fwdAnalysis(*mSettings); const Token* scopeEnd = ValueFlow::getEndOfExprScope(expr, scope, /*smallest*/ false); if (fwdAnalysis.unusedValue(expr, start, scopeEnd)) { if (!bailoutTypeName.empty()) { if (bailoutTypeName != "auto") reportLibraryCfgError(tok, bailoutTypeName); continue; } if (isTrivialInit && findExpressionChanged(expr, start, scopeEnd, *mSettings)) continue; // warn if (!expr->variable() || !expr->variable()->isMaybeUnused()) unreadVariableError(tok, expr->expressionString(), false); } } // varId, usage {read, write, modified} Variables variables; checkFunctionVariableUsage_iterateScopes(scope, variables); // Check usage of all variables in the current scope.. for (auto it = variables.varUsage().cbegin(); it != variables.varUsage().cend(); ++it) { const Variables::VariableUsage &usage = it->second; // variable has been marked as unused so ignore it if (usage._var->nameToken()->isAttributeUnused() || usage._var->nameToken()->isAttributeUsed()) continue; // skip things that are only partially implemented to prevent false positives if (usage.mType == Variables::pointerPointer || usage.mType == Variables::pointerArray || usage.mType == Variables::referenceArray) continue; const std::string &varname = usage._var->name(); const Variable* var = symbolDatabase->getVariableFromVarId(it->first); // variable has had memory allocated for it, but hasn't done // anything with that memory other than, perhaps, freeing it if (usage.unused() && !usage._modified && usage._allocateMemory) allocatedButUnusedVariableError(usage._lastAccess, varname); // variable has not been written, read, or modified else if (usage.unused() && !usage._modified) { if (!usage._var->isMaybeUnused()) { unusedVariableError(usage._var->nameToken(), varname); } } // variable has not been written but has been modified else if (usage._modified && !usage._write && !usage._allocateMemory && var && !var->isStlType()) { if (var->isStatic()) // static variables are initialized by default continue; unassignedVariableError(usage._var->nameToken(), varname); } // variable has been read but not written else if (!usage._write && !usage._allocateMemory && var && !var->isStlType() && !isEmptyType(var->type()) && !(var->type() && var->type()->needInitialization == Type::NeedInitialization::False) && !(var->valueType() && var->valueType()->container) && !(var->isStatic() && isReturnedByRef(var, scope->function))) unassignedVariableError(usage._var->nameToken(), varname); else if (!usage._var->isMaybeUnused() && !usage._modified && !usage._read && var) { const Token* vnt = var->nameToken(); bool error = false; if (vnt->next()->isSplittedVarDeclEq() || (!var->isReference() && vnt->strAt(1) == "=")) { const Token* nextStmt = vnt->tokAt(2); if (nextStmt->isExpandedMacro()) { const Token* parent = nextStmt; while (parent->astParent() && parent == parent->astParent()->astOperand1()) parent = parent->astParent(); if (parent->isAssignmentOp() && parent->isExpandedMacro()) continue; } while (nextStmt && nextStmt->str() != ";") nextStmt = nextStmt->next(); error = precedes(usage._lastAccess, nextStmt); } if (error) { if (mTokenizer->isCPP() && var->isClass() && (!var->valueType() || var->valueType()->type == ValueType::Type::UNKNOWN_TYPE)) { const std::string typeName = var->getTypeName(); switch (mSettings->library.getTypeCheck("unusedvar", typeName)) { case Library::TypeCheck::def: reportLibraryCfgError(vnt, typeName); break; case Library::TypeCheck::check: break; case Library::TypeCheck::suppress: case Library::TypeCheck::checkFiniteLifetime: error = false; } } if (error) unreadVariableError(vnt, varname, false); } } } } } void CheckUnusedVar::unusedVariableError(const Token *tok, const std::string &varname) { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable")) return; reportError(tok, Severity::style, "unusedVariable", "$symbol:" + varname + "\nUnused variable: $symbol", CWE563, Certainty::normal); } void CheckUnusedVar::allocatedButUnusedVariableError(const Token *tok, const std::string &varname) { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable")) return; reportError(tok, Severity::style, "unusedAllocatedMemory", "$symbol:" + varname + "\nVariable '$symbol' is allocated memory that is never used.", CWE563, Certainty::normal); } void CheckUnusedVar::unreadVariableError(const Token *tok, const std::string &varname, bool modified) { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable")) return; if (modified) reportError(tok, Severity::style, "unreadVariable", "$symbol:" + varname + "\nVariable '$symbol' is modified but its new value is never used.", CWE563, Certainty::normal); else reportError(tok, Severity::style, "unreadVariable", "$symbol:" + varname + "\nVariable '$symbol' is assigned a value that is never used.", CWE563, Certainty::normal); } void CheckUnusedVar::unassignedVariableError(const Token *tok, const std::string &varname) { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedVariable")) return; reportError(tok, Severity::style, "unassignedVariable", "$symbol:" + varname + "\nVariable '$symbol' is not assigned a value.", CWE665, Certainty::normal); } //--------------------------------------------------------------------------- // Check that all struct members are used //--------------------------------------------------------------------------- void CheckUnusedVar::checkStructMemberUsage() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("unusedStructMember") && !mSettings->isPremiumEnabled("unusedVariable")) return; logChecker("CheckUnusedVar::checkStructMemberUsage"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eStruct && scope.type != Scope::eClass && scope.type != Scope::eUnion) continue; if (scope.bodyStart->fileIndex() != 0 || scope.className.empty()) continue; if (scope.classDef->isExpandedMacro()) continue; // Packed struct => possibly used by lowlevel code. Struct members might be required by hardware. if (scope.bodyEnd->isAttributePacked()) continue; if (mTokenizer->isPacked(scope.bodyStart)) continue; // Bail out for template struct, members might be used in non-matching instantiations if (scope.className.find('<') != std::string::npos) continue; // bail out if struct is inherited const bool isInherited = std::any_of(symbolDatabase->scopeList.cbegin(), symbolDatabase->scopeList.cend(), [&](const Scope& derivedScope) { const Type* dType = derivedScope.definedType; return dType && std::any_of(dType->derivedFrom.cbegin(), dType->derivedFrom.cend(), [&](const Type::BaseInfo& derivedFrom) { return derivedFrom.type == scope.definedType && derivedFrom.access != AccessControl::Private; }); }); // bail out for extern/global struct bool bailout = false; for (const Variable* var : symbolDatabase->variableList()) { if (var && (var->isExtern() || (var->isGlobal() && !var->isStatic())) && var->typeEndToken()->str() == scope.className) { bailout = true; break; } if (bailout) break; } if (bailout) continue; // Bail out if some data is casted to struct.. const std::string castPattern("( struct| " + scope.className + " * ) &| %name%"); if (Token::findmatch(scope.bodyEnd, castPattern.c_str())) continue; // (struct S){..} const std::string initPattern("( struct| " + scope.className + " ) {"); if (Token::findmatch(scope.bodyEnd, initPattern.c_str())) continue; // Bail out if struct is used in sizeof.. for (const Token *tok = scope.bodyEnd; nullptr != (tok = Token::findsimplematch(tok, "sizeof ("));) { tok = tok->tokAt(2); if (Token::Match(tok, ("struct| " + scope.className).c_str())) { bailout = true; break; } } if (bailout) continue; for (const Variable &var : scope.varlist) { // only warn for variables without side effects if (!var.typeStartToken()->isStandardType() && !var.isPointer() && !astIsContainer(var.nameToken()) && !isRecordTypeWithoutSideEffects(var.type())) continue; if (isInherited && !var.isPrivate()) continue; // Check if the struct member variable is used anywhere in the file bool use = false; for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, ". %name%") && !tok->next()->variable() && !tok->next()->function() && tok->strAt(1) == var.name()) { // not known => assume variable is used use = true; break; } if (tok->variable() != &var) continue; if (tok != var.nameToken()) { use = true; break; } } if (!use) { std::string prefix = "struct"; if (scope.type == Scope::ScopeType::eClass) prefix = "class"; else if (scope.type == Scope::ScopeType::eUnion) prefix = "union"; unusedStructMemberError(var.nameToken(), scope.className, var.name(), prefix); } } } } void CheckUnusedVar::unusedStructMemberError(const Token* tok, const std::string& structname, const std::string& varname, const std::string& prefix) { reportError(tok, Severity::style, "unusedStructMember", "$symbol:" + structname + "::" + varname + '\n' + prefix + " member '$symbol' is never used.", CWE563, Certainty::normal); } bool CheckUnusedVar::isRecordTypeWithoutSideEffects(const Type* type) { // a type that has no side effects (no constructors and no members with constructors) /** @todo false negative: check constructors for side effects */ const std::pair<std::map<const Type *,bool>::iterator,bool> found=mIsRecordTypeWithoutSideEffectsMap.insert( std::pair<const Type *,bool>(type,false)); //Initialize with side effects for possible recursions bool & withoutSideEffects = found.first->second; if (!found.second) return withoutSideEffects; // unknown types are assumed to have side effects if (!type || !type->classScope) return (withoutSideEffects = false); // Non-empty constructors => possible side effects for (const Function& f : type->classScope->functionList) { if (!f.isConstructor() && !f.isDestructor()) continue; if (f.argDef && Token::simpleMatch(f.argDef->link(), ") =")) continue; // ignore default/deleted constructors const bool emptyBody = (f.functionScope && Token::simpleMatch(f.functionScope->bodyStart, "{ }")); const Token* nextToken = f.argDef ? f.argDef->link() : nullptr; if (Token::simpleMatch(nextToken, ") :")) { // validating initialization list nextToken = nextToken->next(); // goto ":" for (const Token *initListToken = nextToken; Token::Match(initListToken, "[:,] %var% [({]"); initListToken = initListToken->linkAt(2)->next()) { const Token* varToken = initListToken->next(); const Variable* variable = varToken->variable(); if (variable && !isVariableWithoutSideEffects(*variable)) { return withoutSideEffects = false; } const Token* valueEnd = initListToken->linkAt(2); for (const Token* valueToken = initListToken->tokAt(3); valueToken != valueEnd; valueToken = valueToken->next()) { const Variable* initValueVar = valueToken->variable(); if (initValueVar && !isVariableWithoutSideEffects(*initValueVar)) { return withoutSideEffects = false; } if ((valueToken->tokType() == Token::Type::eName) || (valueToken->tokType() == Token::Type::eLambda) || (valueToken->tokType() == Token::Type::eOther)) { return withoutSideEffects = false; } const Function* initValueFunc = valueToken->function(); if (initValueFunc && !isFunctionWithoutSideEffects(*initValueFunc, valueToken, std::list<const Function*> {})) { return withoutSideEffects = false; } } } } if (!emptyBody) return (withoutSideEffects = false); } // Derived from type that has side effects? if (std::any_of(type->derivedFrom.cbegin(), type->derivedFrom.cend(), [this](const Type::BaseInfo& derivedFrom) { return !isRecordTypeWithoutSideEffects(derivedFrom.type); })) return (withoutSideEffects = false); // Is there a member variable with possible side effects for (const Variable& var : type->classScope->varlist) { withoutSideEffects = isVariableWithoutSideEffects(var, type); if (!withoutSideEffects) { return withoutSideEffects; } } return (withoutSideEffects = true); } bool CheckUnusedVar::isVariableWithoutSideEffects(const Variable& var, const Type* type) { const Type* variableType = var.type(); if (variableType && variableType != type) { if (!isRecordTypeWithoutSideEffects(variableType)) return false; } else { if (WRONG_DATA(!var.valueType(), var.typeStartToken())) return false; const ValueType::Type valueType = var.valueType()->type; if ((valueType == ValueType::Type::UNKNOWN_TYPE) || (valueType == ValueType::Type::NONSTD)) return false; } return true; } bool CheckUnusedVar::isEmptyType(const Type* type) { // a type that has no variables and no constructor const std::pair<std::map<const Type *,bool>::iterator,bool> found=mIsEmptyTypeMap.insert( std::pair<const Type *,bool>(type,false)); bool & emptyType=found.first->second; if (!found.second) return emptyType; if (type && type->classScope && type->classScope->numConstructors == 0 && (type->classScope->varlist.empty())) { return (emptyType = std::all_of(type->derivedFrom.cbegin(), type->derivedFrom.cend(), [this](const Type::BaseInfo& bi) { return isEmptyType(bi.type); })); } // unknown types are assumed to be nonempty return (emptyType = false); } bool CheckUnusedVar::isFunctionWithoutSideEffects(const Function& func, const Token* functionUsageToken, std::list<const Function*> checkedFuncs) { // no body to analyze if (!func.hasBody()) { return false; } for (const Token* argsToken = functionUsageToken->next(); !Token::simpleMatch(argsToken, ")"); argsToken = argsToken->next()) { const Variable* argVar = argsToken->variable(); if (argVar && argVar->isGlobal()) { return false; // TODO: analyze global variable usage } } bool sideEffectReturnFound = false; std::set<const Variable*> pointersToGlobals; for (const Token* bodyToken = func.functionScope->bodyStart->next(); bodyToken != func.functionScope->bodyEnd; bodyToken = bodyToken->next()) { // check variable inside function body const Variable* bodyVariable = bodyToken->variable(); if (bodyVariable) { if (!isVariableWithoutSideEffects(*bodyVariable)) { return false; } // check if global variable is changed if (bodyVariable->isGlobal() || (pointersToGlobals.find(bodyVariable) != pointersToGlobals.end())) { const int indirect = bodyVariable->isArray() ? bodyVariable->dimensions().size() : bodyVariable->isPointer(); if (isVariableChanged(bodyToken, indirect, *mSettings)) { return false; } // check if pointer to global variable assigned to another variable (another_var = &global_var) if (Token::simpleMatch(bodyToken->tokAt(-1), "&") && Token::simpleMatch(bodyToken->tokAt(-2), "=")) { const Token* assigned_var_token = bodyToken->tokAt(-3); if (assigned_var_token && assigned_var_token->variable()) { pointersToGlobals.insert(assigned_var_token->variable()); } } } } // check nested function const Function* bodyFunction = bodyToken->function(); if (bodyFunction) { if (std::find(checkedFuncs.cbegin(), checkedFuncs.cend(), bodyFunction) != checkedFuncs.cend()) { // recursion found continue; } checkedFuncs.push_back(bodyFunction); if (!isFunctionWithoutSideEffects(*bodyFunction, bodyToken, checkedFuncs)) { return false; } } // check returned value if (Token::simpleMatch(bodyToken, "return")) { const Token* returnValueToken = bodyToken->next(); // TODO: handle complex return expressions if (!Token::simpleMatch(returnValueToken->next(), ";")) { sideEffectReturnFound = true; continue; } // simple one-token return const Variable* returnVariable = returnValueToken->variable(); if (returnValueToken->isLiteral() || (returnVariable && isVariableWithoutSideEffects(*returnVariable))) { continue; } sideEffectReturnFound = true; } // unknown name if (bodyToken->isNameOnly()) { return false; } } return !sideEffectReturnFound; }
72,326
C++
.cpp
1,528
34.192408
194
0.517439
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,165
checkuninitvar.cpp
danmar_cppcheck/lib/checkuninitvar.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "checkuninitvar.h" #include "astutils.h" #include "ctu.h" #include "errorlogger.h" #include "library.h" #include "mathlib.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "checknullpointer.h" // CheckNullPointer::isPointerDeref #include <algorithm> #include <cassert> #include <functional> #include <initializer_list> #include <list> #include <map> #include <unordered_set> #include <vector> namespace tinyxml2 { class XMLElement; } //--------------------------------------------------------------------------- // CWE ids used: static const CWE CWE_USE_OF_UNINITIALIZED_VARIABLE(457U); // Register this check class (by creating a static instance of it) namespace { CheckUninitVar instance; } //--------------------------------------------------------------------------- // get ast parent, skip possible address-of and casts static const Token *getAstParentSkipPossibleCastAndAddressOf(const Token *vartok, bool *unknown) { if (unknown) *unknown = false; if (!vartok) return nullptr; const Token *parent = vartok->astParent(); while (Token::Match(parent, ".|::")) parent = parent->astParent(); if (!parent) return nullptr; if (parent->isUnaryOp("&")) parent = parent->astParent(); else if (parent->str() == "&" && vartok == parent->astOperand2() && Token::Match(parent->astOperand1()->previous(), "( %type% )")) { parent = parent->astParent(); if (unknown) *unknown = true; } while (parent && parent->isCast()) parent = parent->astParent(); return parent; } static std::map<nonneg int, VariableValue> getVariableValues(const Token* tok) { std::map<nonneg int, VariableValue> ret; if (!tok || !tok->scope()->isExecutable()) return ret; while (tok && tok->str() != "{") { if (tok->str() == "}") { if (tok->link()->isBinaryOp()) tok = tok->link()->previous(); else break; } if (Token::Match(tok, "%var% =|{") && tok->next()->isBinaryOp() && tok->varId() && ret.count(tok->varId()) == 0) { const Token* rhs = tok->next()->astOperand2(); if (rhs && rhs->hasKnownIntValue()) ret[tok->varId()] = VariableValue(rhs->getKnownIntValue()); } tok = tok->previous(); } return ret; } bool CheckUninitVar::diag(const Token* tok) { if (!tok) return true; while (Token::Match(tok->astParent(), "*|&|.")) tok = tok->astParent(); return !mUninitDiags.insert(tok).second; } void CheckUninitVar::check() { logChecker("CheckUninitVar::check"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); std::set<std::string> arrayTypeDefs; for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "%name% [") && tok->variable() && Token::Match(tok->variable()->typeStartToken(), "%type% %var% ;")) arrayTypeDefs.insert(tok->variable()->typeStartToken()->str()); } // check every executable scope for (const Scope &scope : symbolDatabase->scopeList) { if (scope.isExecutable()) { checkScope(&scope, arrayTypeDefs); } } } void CheckUninitVar::checkScope(const Scope* scope, const std::set<std::string> &arrayTypeDefs) { for (const Variable &var : scope->varlist) { if ((mTokenizer->isCPP() && var.type() && !var.isPointer() && var.type()->needInitialization != Type::NeedInitialization::True) || var.isStatic() || var.isExtern() || var.isReference()) continue; // don't warn for try/catch exception variable if (var.isThrow()) continue; if (Token::Match(var.nameToken()->next(), "[({:]")) continue; if (Token::Match(var.nameToken(), "%name% =")) { // Variable is initialized, but Rhs might be not checkRhs(var.nameToken(), var, NO_ALLOC, 0U, emptyString); continue; } if (Token::Match(var.nameToken(), "%name% ) (") && Token::simpleMatch(var.nameToken()->linkAt(2), ") =")) { // Function pointer is initialized, but Rhs might be not checkRhs(var.nameToken()->linkAt(2)->next(), var, NO_ALLOC, 0U, emptyString); continue; } if (var.isArray() || var.isPointerToArray()) { const Token *tok = var.nameToken()->next(); if (var.isPointerToArray()) tok = tok->next(); while (Token::simpleMatch(tok->link(), "] [")) tok = tok->link()->next(); if (Token::Match(tok->link(), "] =|{|(")) continue; } bool stdtype = var.typeStartToken()->isC() && arrayTypeDefs.find(var.typeStartToken()->str()) == arrayTypeDefs.end(); const Token* tok = var.typeStartToken(); for (; tok != var.nameToken() && tok->str() != "<"; tok = tok->next()) { if (tok->isStandardType() || tok->isEnumType()) stdtype = true; } if (var.isArray() && !stdtype) { // std::array if (!(var.isStlType() && Token::simpleMatch(var.typeStartToken(), "std :: array") && var.valueType() && var.valueType()->containerTypeToken && var.valueType()->containerTypeToken->isStandardType())) continue; } while (tok && tok->str() != ";") tok = tok->next(); if (!tok) continue; if (tok->astParent() && Token::simpleMatch(tok->astParent()->previous(), "for (") && Token::simpleMatch(tok->astParent()->link()->next(), "{") && checkLoopBody(tok->astParent()->link()->next(), var, var.isArray() ? ARRAY : NO_ALLOC, emptyString, true)) continue; if (var.isArray()) { bool init = false; for (const Token *parent = var.nameToken(); parent; parent = parent->astParent()) { if (parent->str() == "=") { init = true; break; } } if (!init) { Alloc alloc = ARRAY; std::map<nonneg int, VariableValue> variableValue = getVariableValues(var.typeStartToken()); checkScopeForVariable(tok, var, nullptr, nullptr, &alloc, emptyString, variableValue); } continue; } if (stdtype || var.isPointer()) { Alloc alloc = NO_ALLOC; std::map<nonneg int, VariableValue> variableValue = getVariableValues(var.typeStartToken()); checkScopeForVariable(tok, var, nullptr, nullptr, &alloc, emptyString, variableValue); } if (var.type()) checkStruct(tok, var); } if (scope->function) { for (const Variable &arg : scope->function->argumentList) { if (arg.declarationId() && Token::Match(arg.typeStartToken(), "%type% * %name% [,)]")) { // Treat the pointer as initialized until it is assigned by malloc for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "[;{}] %varid% =", arg.declarationId())) continue; const Token *allocFuncCallToken = findAllocFuncCallToken(tok->tokAt(2)->astOperand2(), mSettings->library); if (!allocFuncCallToken) continue; const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(allocFuncCallToken); if (!allocFunc || allocFunc->initData) continue; if (arg.typeStartToken()->strAt(-1) == "struct" || (arg.type() && arg.type()->isStructType())) checkStruct(tok, arg); else if (arg.typeStartToken()->isStandardType() || arg.typeStartToken()->isEnumType()) { Alloc alloc = NO_ALLOC; std::map<nonneg int, VariableValue> variableValue; checkScopeForVariable(tok->next(), arg, nullptr, nullptr, &alloc, emptyString, variableValue); } } } } } } void CheckUninitVar::checkStruct(const Token *tok, const Variable &structvar) { const Token *typeToken = structvar.typeStartToken(); while (Token::Match(typeToken, "%name% ::")) typeToken = typeToken->tokAt(2); const SymbolDatabase * symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope2 : symbolDatabase->classAndStructScopes) { if (scope2->className == typeToken->str() && scope2->numConstructors == 0U) { for (const Variable &var : scope2->varlist) { if (var.isStatic() || var.hasDefault() || var.isArray() || (!mTokenizer->isC() && var.isClass() && (!var.type() || var.type()->needInitialization != Type::NeedInitialization::True))) continue; // is the variable declared in a inner union? bool innerunion = false; for (const Scope *innerScope : scope2->nestedList) { if (innerScope->type == Scope::eUnion) { if (var.typeStartToken()->linenr() >= innerScope->bodyStart->linenr() && var.typeStartToken()->linenr() <= innerScope->bodyEnd->linenr()) { innerunion = true; break; } } } if (!innerunion) { Alloc alloc = NO_ALLOC; const Token *tok2 = tok; if (tok->str() == "}") tok2 = tok2->next(); std::map<nonneg int, VariableValue> variableValue = getVariableValues(structvar.typeStartToken()); checkScopeForVariable(tok2, structvar, nullptr, nullptr, &alloc, var.name(), variableValue); } } } } } static VariableValue operator!(VariableValue v) { v.notEqual = !v.notEqual; return v; } static bool operator==(const VariableValue & v, MathLib::bigint i) { return v.notEqual ? (i != v.value) : (i == v.value); } static bool operator!=(const VariableValue & v, MathLib::bigint i) { return v.notEqual ? (i == v.value) : (i != v.value); } static void conditionAlwaysTrueOrFalse(const Token *tok, const std::map<nonneg int, VariableValue> &variableValue, bool *alwaysTrue, bool *alwaysFalse) { if (!tok) return; if (tok->hasKnownIntValue()) { if (tok->getKnownIntValue() == 0) *alwaysFalse = true; else *alwaysTrue = true; return; } if (tok->isName() || tok->str() == ".") { while (tok && tok->str() == ".") tok = tok->astOperand2(); const std::map<nonneg int, VariableValue>::const_iterator it = variableValue.find(tok ? tok->varId() : ~0U); if (it != variableValue.end()) { *alwaysTrue = (it->second != 0LL); *alwaysFalse = (it->second == 0LL); } } else if (tok->isComparisonOp()) { if (variableValue.empty()) { return; } const Token *vartok, *numtok; if (tok->astOperand2() && tok->astOperand2()->isNumber()) { vartok = tok->astOperand1(); numtok = tok->astOperand2(); } else if (tok->astOperand1() && tok->astOperand1()->isNumber()) { vartok = tok->astOperand2(); numtok = tok->astOperand1(); } else { return; } while (vartok && vartok->str() == ".") vartok = vartok->astOperand2(); const std::map<nonneg int, VariableValue>::const_iterator it = variableValue.find(vartok ? vartok->varId() : ~0U); if (it == variableValue.end()) return; if (tok->str() == "==") *alwaysTrue = (it->second == MathLib::toBigNumber(numtok->str())); else if (tok->str() == "!=") *alwaysTrue = (it->second != MathLib::toBigNumber(numtok->str())); else return; *alwaysFalse = !(*alwaysTrue); } else if (tok->str() == "!") { bool t=false,f=false; conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t, &f); if (t || f) { *alwaysTrue = !t; *alwaysFalse = !f; } } else if (tok->str() == "||") { bool t1=false, f1=false; conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t1, &f1); bool t2=false, f2=false; if (!t1) conditionAlwaysTrueOrFalse(tok->astOperand2(), variableValue, &t2, &f2); *alwaysTrue = (t1 || t2); *alwaysFalse = (f1 && f2); } else if (tok->str() == "&&") { bool t1=false, f1=false; conditionAlwaysTrueOrFalse(tok->astOperand1(), variableValue, &t1, &f1); bool t2=false, f2=false; if (!f1) conditionAlwaysTrueOrFalse(tok->astOperand2(), variableValue, &t2, &f2); *alwaysTrue = (t1 && t2); *alwaysFalse = (f1 || f2); } } static bool isVariableUsed(const Token *tok, const Variable& var) { if (!tok) return false; if (tok->str() == "&" && !tok->astOperand2()) return false; if (tok->isConstOp()) return isVariableUsed(tok->astOperand1(),var) || isVariableUsed(tok->astOperand2(),var); if (tok->varId() != var.declarationId()) return false; if (!var.isArray()) return true; const Token *parent = tok->astParent(); while (Token::Match(parent, "[?:]")) parent = parent->astParent(); // no dereference, then array is not "used" if (!Token::Match(parent, "*|[")) return false; const Token *parent2 = parent->astParent(); // TODO: handle function calls. There is a TODO assertion in TestUninitVar::uninitvar_arrays return !parent2 || parent2->isConstOp() || (parent2->str() == "=" && parent2->astOperand2() == parent); } bool CheckUninitVar::checkScopeForVariable(const Token *tok, const Variable& var, bool * const possibleInit, bool * const noreturn, Alloc* const alloc, const std::string &membervar, std::map<nonneg int, VariableValue>& variableValue) { const bool suppressErrors(possibleInit && *possibleInit); // Assume that this is a variable declaration, rather than a fundef const bool printDebug = mSettings->debugwarnings; if (possibleInit) *possibleInit = false; int number_of_if = 0; if (var.declarationId() == 0U) return true; for (; tok; tok = tok->next()) { // End of scope.. if (tok->str() == "}") { if (number_of_if && possibleInit) *possibleInit = true; // might be a noreturn function.. if (mTokenizer->isScopeNoReturn(tok)) { if (noreturn) *noreturn = true; return false; } break; } // Unconditional inner scope, try, lambda, init list if (tok->str() == "{" && Token::Match(tok->previous(), ",|;|{|}|]|try")) { bool possibleInitInner = false; if (checkScopeForVariable(tok->next(), var, &possibleInitInner, noreturn, alloc, membervar, variableValue)) return true; tok = tok->link(); if (possibleInitInner) { number_of_if = 1; if (possibleInit) *possibleInit = true; } continue; } // track values of other variables.. if (Token::Match(tok->previous(), "[;{}.] %var% =")) { if (tok->next()->astOperand2() && tok->next()->astOperand2()->hasKnownIntValue()) variableValue[tok->varId()] = VariableValue(tok->next()->astOperand2()->getKnownIntValue()); else if (Token::Match(tok->previous(), "[;{}] %var% = - %name% ;")) variableValue[tok->varId()] = !VariableValue(0); else variableValue.erase(tok->varId()); } // Inner scope.. else if (Token::simpleMatch(tok, "if (")) { bool alwaysTrue = false; bool alwaysFalse = false; // Is variable assigned in condition? if (!membervar.empty()) { for (const Token *cond = tok->linkAt(1); cond != tok; cond = cond->previous()) { if (cond->varId() == var.declarationId() && isMemberVariableAssignment(cond, membervar)) return true; } } conditionAlwaysTrueOrFalse(tok->next()->astOperand2(), variableValue, &alwaysTrue, &alwaysFalse); // initialization / usage in condition.. if (!alwaysTrue && checkIfForWhileHead(tok->next(), var, suppressErrors, (number_of_if == 0), *alloc, membervar)) return true; // checking if a not-zero variable is zero => bail out nonneg int condVarId = 0; VariableValue condVarValue(0); const Token *condVarTok = nullptr; if (alwaysFalse) ; else if (astIsVariableComparison(tok->next()->astOperand2(), "!=", "0", &condVarTok)) { const std::map<nonneg int,VariableValue>::const_iterator it = variableValue.find(condVarTok->varId()); if (it != variableValue.cend() && it->second != 0) return true; // this scope is not fully analysed => return true condVarId = condVarTok->varId(); condVarValue = !VariableValue(0); } else if (Token::Match(tok->next()->astOperand2(), "==|!=")) { const Token *condition = tok->next()->astOperand2(); const Token *lhs = condition->astOperand1(); const Token *rhs = condition->astOperand2(); const Token *vartok = (lhs && lhs->hasKnownIntValue()) ? rhs : lhs; const Token *numtok = (lhs == vartok) ? rhs : lhs; while (Token::simpleMatch(vartok, ".")) vartok = vartok->astOperand2(); if (vartok && vartok->varId() && numtok && numtok->hasKnownIntValue()) { const std::map<nonneg int,VariableValue>::const_iterator it = variableValue.find(vartok->varId()); if (it != variableValue.cend() && it->second != numtok->getKnownIntValue()) return true; // this scope is not fully analysed => return true condVarId = vartok->varId(); condVarValue = VariableValue(numtok->getKnownIntValue()); if (condition->str() == "!=") condVarValue = !condVarValue; } } // goto the { tok = tok->linkAt(1)->next(); if (!tok) break; if (tok->str() == "{") { bool possibleInitIf((!alwaysTrue && number_of_if > 0) || suppressErrors); bool noreturnIf = false; std::map<nonneg int, VariableValue> varValueIf(variableValue); const bool initif = !alwaysFalse && checkScopeForVariable(tok->next(), var, &possibleInitIf, &noreturnIf, alloc, membervar, varValueIf); // bail out for such code: // if (a) x=0; // conditional initialization // if (b) return; // cppcheck doesn't know if b can be false when a is false. // x++; // it's possible x is always initialized if (!alwaysTrue && noreturnIf && number_of_if > 0) { if (printDebug) { std::string condition; for (const Token *tok2 = tok->linkAt(-1); tok2 != tok; tok2 = tok2->next()) { condition += tok2->str(); if (tok2->isName() && tok2->next()->isName()) condition += ' '; } reportError(tok, Severity::debug, "bailoutUninitVar", "bailout uninitialized variable checking for '" + var.name() + "'. can't determine if this condition can be false when previous condition is false: " + condition); } return true; } if (alwaysTrue && (initif || noreturnIf)) return true; if (!alwaysFalse && !initif && !noreturnIf) variableValue = varValueIf; if (initif && condVarId > 0) variableValue[condVarId] = !condVarValue; // goto the } tok = tok->link(); if (!Token::simpleMatch(tok, "} else {")) { if (initif || possibleInitIf) { ++number_of_if; if (number_of_if >= 2) return true; } } else { // goto the { tok = tok->tokAt(2); bool possibleInitElse((!alwaysFalse && number_of_if > 0) || suppressErrors); bool noreturnElse = false; std::map<nonneg int, VariableValue> varValueElse(variableValue); const bool initelse = !alwaysTrue && checkScopeForVariable(tok->next(), var, &possibleInitElse, &noreturnElse, alloc, membervar, varValueElse); if (!alwaysTrue && !initelse && !noreturnElse) variableValue = varValueElse; if (initelse && condVarId > 0 && !noreturnIf && !noreturnElse) variableValue[condVarId] = condVarValue; // goto the } tok = tok->link(); if ((alwaysFalse || initif || noreturnIf) && (alwaysTrue || initelse || noreturnElse)) return true; if (initif || initelse || possibleInitElse) ++number_of_if; if (!initif && !noreturnIf) variableValue.insert(varValueIf.cbegin(), varValueIf.cend()); if (!initelse && !noreturnElse) variableValue.insert(varValueElse.cbegin(), varValueElse.cend()); } } } // = { .. } else if (Token::simpleMatch(tok, "= {") || (Token::Match(tok, "%name% {") && tok->variable() && tok == tok->variable()->nameToken())) { // end token const Token *end = tok->linkAt(1); // If address of variable is taken in the block then bail out if (var.isPointer() || var.isArray()) { if (Token::findmatch(tok->tokAt(2), "%varid%", end, var.declarationId())) return true; } else if (Token::findmatch(tok->tokAt(2), "& %varid%", end, var.declarationId())) { return true; } const Token *errorToken = nullptr; visitAstNodes(tok->next(), [&](const Token *child) { if (child->isUnaryOp("&")) return ChildrenToVisit::none; if (child->str() == "," || child->str() == "{" || child->isConstOp()) return ChildrenToVisit::op1_and_op2; if (child->str() == "." && Token::Match(child->astOperand1(), "%varid%", var.declarationId()) && child->astOperand2() && child->astOperand2()->str() == membervar) { errorToken = child; return ChildrenToVisit::done; } return ChildrenToVisit::none; }); if (errorToken) { uninitStructMemberError(errorToken->astOperand2(), errorToken->astOperand1()->str() + "." + membervar); return true; } // Skip block tok = end; continue; } // skip sizeof / offsetof if (isUnevaluated(tok)) tok = tok->linkAt(1); // for/while.. else if (Token::Match(tok, "for|while (") || Token::simpleMatch(tok, "do {")) { const bool forwhile = Token::Match(tok, "for|while ("); // is variable initialized in for-head? if (forwhile && checkIfForWhileHead(tok->next(), var, tok->str() == "for", false, *alloc, membervar)) return true; // goto the { const Token *tok2 = forwhile ? tok->linkAt(1)->next() : tok->next(); if (tok2 && tok2->str() == "{") { const bool init = checkLoopBody(tok2, var, *alloc, membervar, (number_of_if > 0) || suppressErrors); // variable is initialized in the loop.. if (init) return true; // is variable used in for-head? bool initcond = false; if (!suppressErrors) { const Token *startCond = forwhile ? tok->next() : tok->linkAt(1)->tokAt(2); initcond = checkIfForWhileHead(startCond, var, false, (number_of_if == 0), *alloc, membervar); } // goto "}" tok = tok2->link(); // do-while => goto ")" if (!forwhile) { // Assert that the tokens are '} while (' if (!Token::simpleMatch(tok, "} while (")) { if (printDebug) reportError(tok,Severity::debug,emptyString,"assertion failed '} while ('"); break; } // Goto ')' tok = tok->linkAt(2); if (!tok) // bailout : invalid code / bad tokenizer break; if (initcond) // variable is initialized in while-condition return true; } } } // Unknown or unhandled inner scope else if (Token::simpleMatch(tok, ") {") || (Token::Match(tok, "%name% {") && tok->str() != "try" && !(tok->variable() && tok == tok->variable()->nameToken()))) { if (tok->str() == "struct" || tok->str() == "union") { tok = tok->linkAt(1); continue; } return true; } // bailout if there is ({ if (Token::simpleMatch(tok, "( {")) { return true; } // bailout if there is assembler code or setjmp if (Token::Match(tok, "asm|setjmp (")) { return true; } // bailout if there is a goto label if (Token::Match(tok, "[;{}] %name% :")) { return true; } // bailout if there is a pointer to member if (Token::Match(tok, "%varid% . *", var.declarationId())) { return true; } if (tok->str() == "?") { if (!tok->astOperand2()) return true; const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var); const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var); const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0); if (err) uninitvarError(tok, var.nameToken()->str(), *alloc); // Todo: skip expression if there is no error return true; } if (Token::Match(tok, "return|break|continue|throw|goto")) { if (noreturn) *noreturn = true; tok = tok->next(); while (tok && tok->str() != ";") { // variable is seen.. if (tok->varId() == var.declarationId()) { if (!membervar.empty()) { if (!suppressErrors && Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar && Token::Match(tok->next()->astParent(), "%cop%|return|throw|?")) uninitStructMemberError(tok, tok->str() + "." + membervar); else if (tok->isCpp() && !suppressErrors && Token::Match(tok, "%name%") && Token::Match(tok->astParent(), "return|throw|?")) { if (std::any_of(tok->values().cbegin(), tok->values().cend(), [](const ValueFlow::Value& v) { return v.isUninitValue() && !v.isInconclusive(); })) uninitStructMemberError(tok, tok->str() + "." + membervar); } } // Use variable else if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc)) uninitvarError(tok, tok->str(), *alloc); return true; } if (isUnevaluated(tok)) tok = tok->linkAt(1); else if (tok->str() == "?") { if (!tok->astOperand2()) return true; const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var); const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var); const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0); if (err) uninitvarError(tok, var.nameToken()->str(), *alloc); return true; } tok = tok->next(); } return (noreturn == nullptr); } // variable is seen.. if (tok->varId() == var.declarationId()) { // calling function that returns uninit data through pointer.. if (var.isPointer() && Token::simpleMatch(tok->next(), "=")) { const Token *rhs = tok->next()->astOperand2(); while (rhs && rhs->isCast()) rhs = rhs->astOperand2() ? rhs->astOperand2() : rhs->astOperand1(); if (rhs && Token::Match(rhs->previous(), "%name% (")) { const Library::AllocFunc *allocFunc = mSettings->library.getAllocFuncInfo(rhs->astOperand1()); if (allocFunc && !allocFunc->initData) { *alloc = NO_CTOR_CALL; continue; } } } if (mTokenizer->isCPP() && var.isPointer() && (var.typeStartToken()->isStandardType() || var.typeStartToken()->isEnumType() || (var.type() && var.type()->needInitialization == Type::NeedInitialization::True)) && Token::simpleMatch(tok->next(), "= new")) { *alloc = CTOR_CALL; // type has constructor(s) if (var.typeScope() && var.typeScope()->numConstructors > 0) return true; // standard or enum type: check if new initializes the allocated memory if (var.typeStartToken()->isStandardType() || var.typeStartToken()->isEnumType()) { // scalar new with initialization if (Token::Match(tok->next(), "= new %type% (")) return true; // array new if (Token::Match(tok->next(), "= new %type% [") && Token::simpleMatch(tok->linkAt(4), "] (")) return true; } continue; } if (!membervar.empty()) { if (isMemberVariableAssignment(tok, membervar)) { checkRhs(tok, var, *alloc, number_of_if, membervar); return true; } if (isMemberVariableUsage(tok, var.isPointer(), *alloc, membervar)) { uninitStructMemberError(tok, tok->str() + "." + membervar); return true; } if (Token::Match(tok->previous(), "[(,] %name% [,)]")) return true; if (Token::Match(tok->previous(), "= %var% . %var% ;") && membervar == tok->strAt(2)) return true; } else { // Use variable if (!suppressErrors && isVariableUsage(tok, var.isPointer(), *alloc)) { uninitvarError(tok, tok->str(), *alloc); return true; } const Token *parent = tok; while (parent->astParent() && ((astIsLHS(parent) && parent->astParent()->str() == "[") || parent->astParent()->isUnaryOp("*"))) { parent = parent->astParent(); if (parent->str() == "[") { if (const Token *errorToken = checkExpr(parent->astOperand2(), var, *alloc, number_of_if==0)) { if (!suppressErrors) uninitvarError(errorToken, errorToken->expressionString(), *alloc); return true; } } } if (Token::simpleMatch(parent->astParent(), "=") && astIsLHS(parent)) { const Token *eq = parent->astParent(); if (const Token *errorToken = checkExpr(eq->astOperand2(), var, *alloc, number_of_if==0)) { if (!suppressErrors) uninitvarError(errorToken, errorToken->expressionString(), *alloc); return true; } } // assume that variable is assigned return true; } } } return false; } const Token* CheckUninitVar::checkExpr(const Token* tok, const Variable& var, const Alloc alloc, bool known, bool* bailout) const { if (!tok) return nullptr; if (isUnevaluated(tok->previous())) return nullptr; if (tok->astOperand1()) { bool bailout1 = false; const Token *errorToken = checkExpr(tok->astOperand1(), var, alloc, known, &bailout1); if (bailout && bailout1) *bailout = true; if (errorToken) return errorToken; if ((bailout1 || !known) && Token::Match(tok, "%oror%|&&|?")) return nullptr; } if (tok->astOperand2()) return checkExpr(tok->astOperand2(), var, alloc, known, bailout); if (tok->varId() == var.declarationId()) { const Token *errorToken = isVariableUsage(tok, var.isPointer(), alloc); if (errorToken) return errorToken; if (bailout) *bailout = true; } return nullptr; } bool CheckUninitVar::checkIfForWhileHead(const Token *startparentheses, const Variable& var, bool suppressErrors, bool isuninit, Alloc alloc, const std::string &membervar) { const Token * const endpar = startparentheses->link(); if (Token::Match(startparentheses, "( ! %name% %oror%") && startparentheses->tokAt(2)->getValue(0)) suppressErrors = true; for (const Token *tok = startparentheses->next(); tok && tok != endpar; tok = tok->next()) { if (tok->varId() == var.declarationId()) { if (Token::Match(tok, "%name% . %name%")) { if (membervar.empty()) return true; if (tok->strAt(2) == membervar) { if (isMemberVariableAssignment(tok, membervar)) return true; if (!suppressErrors && isMemberVariableUsage(tok, var.isPointer(), alloc, membervar)) uninitStructMemberError(tok, tok->str() + "." + membervar); } continue; } if (const Token *errorToken = isVariableUsage(tok, var.isPointer(), alloc)) { if (suppressErrors) continue; uninitvarError(errorToken, errorToken->expressionString(), alloc); } return true; } // skip sizeof / offsetof if (isUnevaluated(tok)) tok = tok->linkAt(1); if ((!isuninit || !membervar.empty()) && tok->str() == "&&") suppressErrors = true; } return false; } /** recursively check loop, return error token */ const Token* CheckUninitVar::checkLoopBodyRecursive(const Token *start, const Variable& var, const Alloc alloc, const std::string &membervar, bool &bailout, bool &alwaysReturns) const { assert(start->str() == "{"); const Token *errorToken = nullptr; const Token *const end = start->link(); for (const Token *tok = start->next(); tok != end; tok = tok->next()) { // skip sizeof / offsetof if (isUnevaluated(tok)) { tok = tok->linkAt(1); continue; } if (Token::Match(tok, "asm ( %str% ) ;")) { bailout = true; return nullptr; } // for loop; skip third expression until loop body has been analyzed.. if (tok->str() == ";" && Token::simpleMatch(tok->astParent(), ";") && Token::simpleMatch(tok->astParent()->astParent(), "(")) { const Token *top = tok->astParent()->astParent(); if (!Token::simpleMatch(top->previous(), "for (") || !Token::simpleMatch(top->link(), ") {")) continue; const Token *bodyStart = top->link()->next(); const Token *errorToken1 = checkLoopBodyRecursive(bodyStart, var, alloc, membervar, bailout, alwaysReturns); if (!errorToken) errorToken = errorToken1; bailout |= alwaysReturns; if (bailout) return nullptr; } // for loop; skip loop body if there is third expression if (Token::simpleMatch(tok, ") {") && Token::simpleMatch(tok->link()->previous(), "for (") && Token::simpleMatch(tok->link()->astOperand2(), ";") && Token::simpleMatch(tok->link()->astOperand2()->astOperand2(), ";")) { tok = tok->linkAt(1); } if (tok->str() == "{") { // switch => bailout if (tok->scope() && tok->scope()->type == Scope::ScopeType::eSwitch) { bailout = true; return nullptr; } bool alwaysReturnsUnused; const Token *errorToken1 = checkLoopBodyRecursive(tok, var, alloc, membervar, bailout, alwaysReturnsUnused); tok = tok->link(); if (Token::simpleMatch(tok, "} else {")) { const Token *elseBody = tok->tokAt(2); const Token *errorToken2 = checkLoopBodyRecursive(elseBody, var, alloc, membervar, bailout, alwaysReturnsUnused); tok = elseBody->link(); if (errorToken1 && errorToken2) return errorToken1; if (errorToken2) errorToken = errorToken2; } if (bailout) return nullptr; if (!errorToken) errorToken = errorToken1; } if (Token::simpleMatch(tok, "return")) { bool returnWithoutVar = true; while (tok && !Token::simpleMatch(tok, ";")) { if (tok->isVariable() && tok->variable() == &var) { returnWithoutVar = false; break; } tok = tok->next(); } if (returnWithoutVar) { alwaysReturns = true; return nullptr; } } if (!tok) break; if (tok->varId() != var.declarationId()) continue; bool conditionalUsage = false; for (const Token* parent = tok; parent; parent = parent->astParent()) { if (Token::Match(parent->astParent(), "%oror%|&&|?") && astIsRHS(parent)) { conditionalUsage = true; break; } } if (!membervar.empty()) { if (isMemberVariableAssignment(tok, membervar)) { bool assign = true; bool rhs = false; // Used for tracking if an ")" is inner or outer const Token *rpar = nullptr; for (const Token *tok2 = tok->next(); tok2; tok2 = tok2->next()) { if (tok2->str() == "=") rhs = true; // Look at inner expressions but not outer expressions if (!rpar && tok2->str() == "(") rpar = tok2->link(); else if (tok2->str() == ")") { // No rpar => this is an outer right parenthesis if (!rpar) break; if (rpar == tok2) rpar = nullptr; } if (tok2->str() == ";" || (!rpar && tok2->str() == ",")) break; if (rhs && tok2->varId() == var.declarationId() && isMemberVariableUsage(tok2, var.isPointer(), alloc, membervar)) { assign = false; break; } } if (assign) { bailout = true; return nullptr; } } if (isMemberVariableUsage(tok, var.isPointer(), alloc, membervar)) { if (!conditionalUsage) return tok; if (!errorToken) errorToken = tok; } else if (Token::Match(tok->previous(), "[(,] %name% [,)]")) { bailout = true; return nullptr; } } else { if (const Token *errtok = isVariableUsage(tok, var.isPointer(), alloc)) { if (!conditionalUsage) return errtok; if (!errorToken) errorToken = errtok; } else if (tok->strAt(1) == "=") { bool varIsUsedInRhs = false; visitAstNodes(tok->next()->astOperand2(), [&](const Token * t) { if (!t) return ChildrenToVisit::none; if (t->varId() == var.declarationId()) { varIsUsedInRhs = true; return ChildrenToVisit::done; } if (isUnevaluated(t->previous())) return ChildrenToVisit::none; return ChildrenToVisit::op1_and_op2; }); if (!varIsUsedInRhs) { bailout = true; return nullptr; } } else { bailout = true; return nullptr; } } } return errorToken; } bool CheckUninitVar::checkLoopBody(const Token *tok, const Variable& var, const Alloc alloc, const std::string &membervar, const bool suppressErrors) { bool bailout = false; bool alwaysReturns = false; const Token *errorToken = checkLoopBodyRecursive(tok, var, alloc, membervar, bailout, alwaysReturns); if (!suppressErrors && !bailout && !alwaysReturns && errorToken) { if (membervar.empty()) uninitvarError(errorToken, errorToken->expressionString(), alloc); else uninitStructMemberError(errorToken, errorToken->expressionString() + "." + membervar); return true; } return bailout || alwaysReturns; } void CheckUninitVar::checkRhs(const Token *tok, const Variable &var, Alloc alloc, nonneg int number_of_if, const std::string &membervar) { bool rhs = false; int indent = 0; while (nullptr != (tok = tok->next())) { if (tok->str() == "=") rhs = true; else if (rhs && tok->varId() == var.declarationId()) { if (membervar.empty() && isVariableUsage(tok, var.isPointer(), alloc)) uninitvarError(tok, tok->str(), alloc); else if (!membervar.empty() && isMemberVariableUsage(tok, var.isPointer(), alloc, membervar)) uninitStructMemberError(tok, tok->str() + "." + membervar); else if (Token::Match(tok, "%var% =")) break; else if (Token::Match(tok->previous(), "[(,&]")) break; } else if (tok->str() == ";" || (indent==0 && tok->str() == ",")) break; else if (tok->str() == "(") ++indent; else if (tok->str() == ")") { if (indent == 0) break; --indent; } else if (tok->str() == "?" && tok->astOperand2()) { const bool used1 = isVariableUsed(tok->astOperand2()->astOperand1(), var); const bool used0 = isVariableUsed(tok->astOperand2()->astOperand2(), var); const bool err = (number_of_if == 0) ? (used1 || used0) : (used1 && used0); if (err) uninitvarError(tok, var.nameToken()->str(), alloc); break; } else if (isUnevaluated(tok)) tok = tok->linkAt(1); } } static bool astIsLhs(const Token *tok) { return tok && tok->astParent() && tok == tok->astParent()->astOperand1(); } static bool astIsRhs(const Token *tok) { return tok && tok->astParent() && tok == tok->astParent()->astOperand2(); } static bool isVoidCast(const Token *tok) { return Token::simpleMatch(tok, "(") && tok->isCast() && tok->valueType() && tok->valueType()->type == ValueType::Type::VOID && tok->valueType()->pointer == 0; } const Token* CheckUninitVar::isVariableUsage(const Token *vartok, const Library& library, bool pointer, Alloc alloc, int indirect) { const bool cpp = vartok->isCpp(); const Token *valueExpr = vartok; // non-dereferenced , no address of value as variable while (Token::Match(valueExpr->astParent(), ".|::") && astIsRhs(valueExpr)) valueExpr = valueExpr->astParent(); // stuff we ignore.. while (valueExpr->astParent()) { // *&x if (valueExpr->astParent()->isUnaryOp("&") && valueExpr->astParent()->astParent() && valueExpr->astParent()->astParent()->isUnaryOp("*")) valueExpr = valueExpr->astParent()->astParent(); // (type &)x else if (valueExpr->astParent()->isCast() && valueExpr->astParent()->isUnaryOp("(") && Token::simpleMatch(valueExpr->astParent()->link()->previous(), "& )")) valueExpr = valueExpr->astParent(); // designated initializers: {.x | { ... , .x else if (Token::simpleMatch(valueExpr->astParent(), ".") && Token::Match(valueExpr->astParent()->previous(), ",|{")) valueExpr = valueExpr->astParent(); else break; } if (!pointer) { if (Token::Match(vartok, "%name% [.(]") && vartok->variable() && !vartok->variable()->isPointer()) return nullptr; while (Token::simpleMatch(valueExpr->astParent(), ".") && astIsLhs(valueExpr) && valueExpr->astParent()->valueType() && valueExpr->astParent()->valueType()->pointer == 0) valueExpr = valueExpr->astParent(); } const Token *derefValue = nullptr; // dereferenced value expression if (alloc != NO_ALLOC) { const int arrayDim = (vartok->variable() && vartok->variable()->isArray()) ? vartok->variable()->dimensions().size() : 1; int deref = 0; derefValue = valueExpr; while (Token::Match(derefValue->astParent(), "+|-|*|[|.") || (derefValue->astParent() && derefValue->astParent()->isCast()) || (deref < arrayDim && Token::simpleMatch(derefValue->astParent(), "&") && derefValue->astParent()->isBinaryOp())) { const Token * const derefValueParent = derefValue->astParent(); if (derefValueParent->str() == "*") { if (derefValueParent->isUnaryOp("*")) ++deref; else break; } else if (derefValueParent->str() == "[") { if (astIsLhs(derefValue)) ++deref; else break; } else if (Token::Match(derefValueParent, "[+-]")) { if (deref >= arrayDim) break; } else if (derefValueParent->str() == ".") ++deref; derefValue = derefValueParent; if (deref < arrayDim) valueExpr = derefValue; } if (deref < arrayDim) { // todo compare deref with array dimensions derefValue = nullptr; } } else if (vartok->astParent() && vartok->astParent()->isUnaryOp("&")) { const Token *child = vartok->astParent(); const Token *parent = child->astParent(); while (parent && (parent->isCast() || parent->str() == "+")) { child = parent; parent = child->astParent(); } if (parent && (parent->isUnaryOp("*") || (parent->str() == "[" && astIsLhs(child)))) derefValue = parent; } if (!valueExpr->astParent()) return nullptr; // FIXME handle address of!! if (derefValue && derefValue->astParent() && derefValue->astParent()->isUnaryOp("&")) return nullptr; // BAILOUT for binary & without parent if (Token::simpleMatch(valueExpr->astParent(), "&") && astIsRhs(valueExpr) && Token::Match(valueExpr->astParent()->tokAt(-3), "( %name% ) &")) return nullptr; // safe operations if (isVoidCast(valueExpr->astParent())) return nullptr; if (Token::simpleMatch(valueExpr->astParent(), ".")) { const Token *parent = valueExpr->astParent(); while (Token::simpleMatch(parent, ".")) parent = parent->astParent(); if (isVoidCast(parent)) return nullptr; } if (alloc != NO_ALLOC) { if (Token::Match(valueExpr->astParent(), "%comp%|%oror%|&&|?|!")) return nullptr; if (Token::Match(valueExpr->astParent(), "%or%|&") && valueExpr->astParent()->isBinaryOp()) return nullptr; if (alloc == CTOR_CALL && derefValue && Token::simpleMatch(derefValue->astParent(), "(") && astIsLhs(derefValue)) return nullptr; if (Token::simpleMatch(valueExpr->astParent(), "return")) return nullptr; } // Passing variable to function.. if (Token::Match(valueExpr->astParent(), "[(,]") && (valueExpr->astParent()->str() == "," || astIsRhs(valueExpr))) { const Token *parent = valueExpr->astParent(); while (Token::simpleMatch(parent, ",")) parent = parent->astParent(); if (Token::simpleMatch(parent, "{")) return valueExpr; const int use = isFunctionParUsage(valueExpr, library, pointer, alloc, indirect); return (use>0) ? valueExpr : nullptr; } if (derefValue && Token::Match(derefValue->astParent(), "[(,]") && (derefValue->astParent()->str() == "," || astIsRhs(derefValue))) { const int use = isFunctionParUsage(derefValue, library, false, NO_ALLOC, indirect); return (use>0) ? derefValue : nullptr; } if (valueExpr->astParent()->isUnaryOp("&")) { const Token *parent = valueExpr->astParent(); if (Token::Match(parent->astParent(), "[(,]") && (parent->astParent()->str() == "," || astIsRhs(parent))) { const int use = isFunctionParUsage(valueExpr, library, pointer, alloc, indirect); return (use>0) ? valueExpr : nullptr; } return nullptr; } // Assignments; // * Is this LHS in assignment // * Passing address in RHS to pointer variable { const Token *tok = derefValue ? derefValue : valueExpr; if (alloc == NO_ALLOC) { while (tok->valueType() && tok->valueType()->pointer == 0 && Token::simpleMatch(tok->astParent(), ".")) tok = tok->astParent(); } if (Token::simpleMatch(tok->astParent(), "=")) { if (astIsLhs(tok)) { if (alloc == ARRAY || !derefValue || !derefValue->isUnaryOp("*") || !pointer) return nullptr; const Token* deref = derefValue->astOperand1(); while (deref && deref->isCast()) deref = deref->astOperand1(); if (deref == vartok || Token::simpleMatch(deref, "+")) return nullptr; } if (alloc != NO_ALLOC && astIsRhs(valueExpr)) return nullptr; } } // Initialize reference variable if (Token::Match((derefValue ? derefValue : vartok)->astParent(), "(|=") && astIsRhs(derefValue ? derefValue : vartok)) { const Token *rhstok = derefValue ? derefValue : vartok; const Token *lhstok = rhstok->astParent()->astOperand1(); const Variable *lhsvar = lhstok ? lhstok->variable() : nullptr; if (lhsvar && lhsvar->isReference() && lhsvar->nameToken() == lhstok) return nullptr; } // range for loop if (Token::simpleMatch(valueExpr->astParent(), ":") && valueExpr->astParent()->astParent() && Token::simpleMatch(valueExpr->astParent()->astParent()->previous(), "for (")) { if (astIsLhs(valueExpr)) return nullptr; // Taking value by reference? const Token *lhs = valueExpr->astParent()->astOperand1(); if (lhs && lhs->variable() && lhs->variable()->nameToken() == lhs && lhs->variable()->isReference()) return nullptr; } // Stream read/write // FIXME this code is a hack!! if (cpp && Token::Match(valueExpr->astParent(), "<<|>>")) { if (isLikelyStreamRead(vartok->previous())) return nullptr; if (const auto* vt = valueExpr->valueType()) { if (vt->type == ValueType::Type::VOID) return nullptr; // passing a char* to a stream will dereference it if ((alloc == CTOR_CALL || alloc == ARRAY) && vt->pointer && vt->type != ValueType::Type::CHAR && vt->type != ValueType::Type::WCHAR_T) return nullptr; } } if (astIsRhs(derefValue) && isLikelyStreamRead(derefValue->astParent())) return nullptr; // Assignment with overloaded & if (cpp && Token::simpleMatch(valueExpr->astParent(), "&") && astIsRhs(valueExpr)) { const Token *parent = valueExpr->astParent(); while (Token::simpleMatch(parent, "&") && parent->isBinaryOp()) parent = parent->astParent(); if (!parent) { const Token *lhs = valueExpr->astParent(); while (Token::simpleMatch(lhs, "&") && lhs->isBinaryOp()) lhs = lhs->astOperand1(); if (lhs && lhs->isName() && (!lhs->valueType() || lhs->valueType()->type <= ValueType::Type::CONTAINER)) return nullptr; // <- possible assignment } } return derefValue ? derefValue : valueExpr; } const Token* CheckUninitVar::isVariableUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect) const { return isVariableUsage(vartok, mSettings->library, pointer, alloc, indirect); } /*** * Is function parameter "used" so a "usage of uninitialized variable" can * be written? If parameter is passed "by value" then it is "used". If it * is passed "by reference" then it is not necessarily "used". * @return -1 => unknown 0 => not used 1 => used */ int CheckUninitVar::isFunctionParUsage(const Token *vartok, const Library& library, bool pointer, Alloc alloc, int indirect) { bool unknown = false; const Token *parent = getAstParentSkipPossibleCastAndAddressOf(vartok, &unknown); if (unknown || !Token::Match(parent, "[(,]")) return -1; // locate start parentheses in function call.. int argumentNumber = 0; const Token *start = vartok; while (start && !Token::Match(start, "[;{}(]")) { if (start->str() == ")") start = start->link(); else if (start->str() == ",") ++argumentNumber; start = start->previous(); } if (!start) return -1; if (Token::simpleMatch(start->link(), ") {") && Token::Match(start->previous(), "if|for|while|switch")) return (!pointer || alloc == NO_ALLOC); // is this a function call? if (Token::Match(start->previous(), "%name% (")) { const bool address(vartok->strAt(-1) == "&"); const bool array(vartok->variable() && vartok->variable()->isArray()); // check how function handle uninitialized data arguments.. const Function *func = start->previous()->function(); if (func) { const Variable *arg = func->getArgumentVar(argumentNumber); if (arg) { const Token *argStart = arg->typeStartToken(); if (!address && !array && Token::Match(argStart, "%type% %name%| [,)]")) return 1; if (pointer && !address && alloc == NO_ALLOC && Token::Match(argStart, "%type% * %name% [,)]")) return 1; while (argStart->previous() && argStart->previous()->isName()) argStart = argStart->previous(); if (Token::Match(argStart, "const %type% & %name% [,)]")) { // If it's a record it's ok to pass a partially uninitialized struct. if (vartok->variable() && vartok->variable()->valueType() && vartok->variable()->valueType()->type == ValueType::Type::RECORD) return -1; return 1; } if ((pointer || address) && Token::Match(argStart, "const %type% %name% [") && Token::Match(argStart->linkAt(3), "] [,)]")) return 1; } } else if (Token::Match(start->previous(), "if|while|for")) { // control-flow statement reading the variable "by value" return alloc == NO_ALLOC; } else { const bool isnullbad = library.isnullargbad(start->previous(), argumentNumber + 1); if (indirect == 0 && pointer && !address && isnullbad && alloc == NO_ALLOC) return 1; bool hasIndirect = false; const bool isuninitbad = library.isuninitargbad(start->previous(), argumentNumber + 1, indirect, &hasIndirect); if (alloc != NO_ALLOC) return (isnullbad || hasIndirect) && isuninitbad; return isuninitbad && (!address || isnullbad); } } // unknown return -1; } int CheckUninitVar::isFunctionParUsage(const Token *vartok, bool pointer, Alloc alloc, int indirect) const { return CheckUninitVar::isFunctionParUsage(vartok, mSettings->library, pointer, alloc, indirect); } bool CheckUninitVar::isMemberVariableAssignment(const Token *tok, const std::string &membervar) const { if (Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar) { if (Token::Match(tok->tokAt(3), "[=.[]")) return true; if (Token::Match(tok->tokAt(-2), "[(,=] &")) return true; if (isLikelyStreamRead(tok->previous())) return true; if ((tok->previous() && tok->previous()->isConstOp()) || Token::Match(tok->previous(), "[|=")) ; // member variable usage else if (tok->tokAt(3)->isConstOp()) ; // member variable usage else if (Token::Match(tok->previous(), "[(,] %name% . %name% [,)]") && 1 == isFunctionParUsage(tok, false, NO_ALLOC)) { return false; } else return true; } else if (tok->strAt(1) == "=") return true; else if (Token::Match(tok, "%var% . %name% (")) { const Token *ftok = tok->tokAt(2); if (!ftok->function() || !ftok->function()->isConst()) // TODO: Try to determine if membervar is assigned in method return true; } else if (tok->strAt(-1) == "&") { if (Token::Match(tok->tokAt(-2), "[(,] & %name%")) { // locate start parentheses in function call.. int argumentNumber = 0; const Token *ftok = tok; while (ftok && !Token::Match(ftok, "[;{}(]")) { if (ftok->str() == ")") ftok = ftok->link(); else if (ftok->str() == ",") ++argumentNumber; ftok = ftok->previous(); } // is this a function call? ftok = ftok ? ftok->previous() : nullptr; if (Token::Match(ftok, "%name% (")) { // check how function handle uninitialized data arguments.. const Function *function = ftok->function(); if (!function && mSettings) { // Function definition not seen, check if direction is specified in the library configuration const Library::ArgumentChecks::Direction argDirection = mSettings->library.getArgDirection(ftok, 1 + argumentNumber); if (argDirection == Library::ArgumentChecks::Direction::DIR_IN) return false; if (argDirection == Library::ArgumentChecks::Direction::DIR_OUT) return true; } const Variable *arg = function ? function->getArgumentVar(argumentNumber) : nullptr; const Token *argStart = arg ? arg->typeStartToken() : nullptr; while (argStart && argStart->previous() && argStart->previous()->isName()) argStart = argStart->previous(); if (Token::Match(argStart, "const struct| %type% * const| %name% [,)]")) return false; } else if (ftok && Token::simpleMatch(ftok->previous(), "= * (")) return false; } return true; } return false; } bool CheckUninitVar::isMemberVariableUsage(const Token *tok, bool isPointer, Alloc alloc, const std::string &membervar) const { if (Token::Match(tok->previous(), "[(,] %name% . %name% [,)]") && tok->strAt(2) == membervar) { const int use = isFunctionParUsage(tok, isPointer, alloc); if (use == 1) return true; } if (isMemberVariableAssignment(tok, membervar)) return false; if (Token::Match(tok, "%name% . %name%") && tok->strAt(2) == membervar && !(tok->tokAt(-2)->variable() && tok->tokAt(-2)->variable()->isReference())) { const Token *parent = tok->next()->astParent(); return !parent || !parent->isUnaryOp("&"); } if (!isPointer && !Token::simpleMatch(tok->astParent(), ".") && Token::Match(tok->previous(), "[(,] %name% [,)]") && isVariableUsage(tok, isPointer, alloc)) return true; if (!isPointer && Token::Match(tok->previous(), "= %name% ;")) { const Token* lhs = tok->previous()->astOperand1(); return !(lhs && lhs->variable() && lhs->variable()->isReference() && lhs == lhs->variable()->nameToken()); } // = *(&var); if (!isPointer && Token::simpleMatch(tok->astParent(),"&") && Token::simpleMatch(tok->astParent()->astParent(),"*") && Token::Match(tok->astParent()->astParent()->astParent(), "= * (| &") && tok->astParent()->astParent()->astParent()->astOperand2() == tok->astParent()->astParent()) return true; // TODO: this used to be experimental - enable or remove see #5586 if ((false) && // NOLINT(readability-simplify-boolean-expr) !isPointer && Token::Match(tok->tokAt(-2), "[(,] & %name% [,)]") && isVariableUsage(tok, isPointer, alloc)) return true; return false; } void CheckUninitVar::uninitdataError(const Token *tok, const std::string &varname) { reportError(tok, Severity::error, "uninitdata", "$symbol:" + varname + "\nMemory is allocated but not initialized: $symbol", CWE_USE_OF_UNINITIALIZED_VARIABLE, Certainty::normal); } void CheckUninitVar::uninitvarError(const Token *tok, const std::string &varname, ErrorPath errorPath) { if (diag(tok)) return; errorPath.emplace_back(tok, ""); reportError(errorPath, Severity::error, "legacyUninitvar", "$symbol:" + varname + "\nUninitialized variable: $symbol", CWE_USE_OF_UNINITIALIZED_VARIABLE, Certainty::normal); } void CheckUninitVar::uninitvarError(const Token* tok, const ValueFlow::Value& v) { if (!mSettings->isEnabled(&v)) return; if (diag(tok)) return; const Token* ltok = tok; if (tok && Token::simpleMatch(tok->astParent(), ".") && astIsRHS(tok)) ltok = tok->astParent(); const std::string& varname = ltok ? ltok->expressionString() : "x"; ErrorPath errorPath = v.errorPath; errorPath.emplace_back(tok, ""); auto severity = v.isKnown() ? Severity::error : Severity::warning; auto certainty = v.isInconclusive() ? Certainty::inconclusive : Certainty::normal; if (v.subexpressions.empty()) { reportError(errorPath, severity, "uninitvar", "$symbol:" + varname + "\nUninitialized variable: $symbol", CWE_USE_OF_UNINITIALIZED_VARIABLE, certainty); return; } std::string vars = v.subexpressions.size() == 1 ? "variable: " : "variables: "; std::string prefix; for (const std::string& var : v.subexpressions) { vars += prefix + varname + "." + var; prefix = ", "; } reportError(errorPath, severity, "uninitvar", "$symbol:" + varname + "\nUninitialized " + vars, CWE_USE_OF_UNINITIALIZED_VARIABLE, certainty); } void CheckUninitVar::uninitStructMemberError(const Token *tok, const std::string &membername) { reportError(tok, Severity::error, "uninitStructMember", "$symbol:" + membername + "\nUninitialized struct member: $symbol", CWE_USE_OF_UNINITIALIZED_VARIABLE, Certainty::normal); } void CheckUninitVar::valueFlowUninit() { logChecker("CheckUninitVar::valueFlowUninit"); const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); std::unordered_set<nonneg int> ids; for (const bool subfunction : {false, true}) { // check every executable scope for (const Scope* scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (isUnevaluated(tok)) { tok = tok->linkAt(1); continue; } if (ids.count(tok->exprId()) > 0) continue; if (!tok->variable() && !tok->isUnaryOp("*") && !tok->isUnaryOp("&")) continue; if (Token::Match(tok, "%name% (")) continue; const Token* parent = tok->astParent(); while (Token::simpleMatch(parent, ".")) parent = parent->astParent(); if (parent && parent->isUnaryOp("&")) continue; if (isVoidCast(parent)) continue; auto v = std::find_if( tok->values().cbegin(), tok->values().cend(), std::mem_fn(&ValueFlow::Value::isUninitValue)); if (v == tok->values().cend()) continue; if (v->tokvalue && ids.count(v->tokvalue->exprId()) > 0) continue; if (subfunction == (v->path == 0)) continue; if (v->isInconclusive()) continue; if (v->indirect > 1 || v->indirect < 0) continue; bool uninitderef = false; if (tok->variable()) { bool unknown; const bool isarray = tok->variable()->isArray(); if (isarray && tok->variable()->isMember()) continue; // Todo: this is a bailout if (isarray && tok->variable()->isStlType() && Token::simpleMatch(tok->astParent(), ".")) { const auto yield = astContainerYield(tok); if (yield != Library::Container::Yield::AT_INDEX && yield != Library::Container::Yield::ITEM) continue; } const bool deref = CheckNullPointer::isPointerDeRef(tok, unknown, *mSettings); uninitderef = deref && v->indirect == 0; const bool isleaf = isLeafDot(tok) || uninitderef; if (!isleaf && Token::Match(tok->astParent(), ". %name%") && (tok->astParent()->next()->varId() || tok->astParent()->next()->isEnumerator())) continue; } const ExprUsage usage = getExprUsage(tok, v->indirect, *mSettings); if (usage == ExprUsage::NotUsed || usage == ExprUsage::Inconclusive) continue; if (!v->subexpressions.empty() && usage == ExprUsage::PassedByReference) continue; if (usage != ExprUsage::Used) { if (!(Token::Match(tok->astParent(), ". %name% (|[") && uninitderef) && isVariableChanged(tok, v->indirect, *mSettings)) continue; bool inconclusive = false; if (isVariableChangedByFunctionCall(tok, v->indirect, *mSettings, &inconclusive) || inconclusive) continue; } uninitvarError(tok, *v); ids.insert(tok->exprId()); if (v->tokvalue) ids.insert(v->tokvalue->exprId()); } } } } // NOLINTNEXTLINE(readability-non-const-parameter) - used as callback so we need to preserve the signature static bool isVariableUsage(const Settings &settings, const Token *vartok, MathLib::bigint *value) { (void)value; return CheckUninitVar::isVariableUsage(vartok, settings.library, true, CheckUninitVar::Alloc::ARRAY); } // a Clang-built executable will crash when using the anonymous MyFileInfo later on - so put it in a unique namespace for now // see https://trac.cppcheck.net/ticket/12108 for more details #ifdef __clang__ inline namespace CheckUninitVar_internal #else namespace #endif { /* data for multifile checking */ class MyFileInfo : public Check::FileInfo { public: /** function arguments that data are unconditionally read */ std::list<CTU::FileInfo::UnsafeUsage> unsafeUsage; /** Convert data into xml string */ std::string toString() const override { return CTU::toString(unsafeUsage); } }; } Check::FileInfo *CheckUninitVar::getFileInfo(const Tokenizer &tokenizer, const Settings &settings) const { const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::getUnsafeUsage(tokenizer, settings, ::isVariableUsage); if (unsafeUsage.empty()) return nullptr; auto *fileInfo = new MyFileInfo; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } Check::FileInfo * CheckUninitVar::loadFileInfoFromXml(const tinyxml2::XMLElement *xmlElement) const { const std::list<CTU::FileInfo::UnsafeUsage> &unsafeUsage = CTU::loadUnsafeUsageListFromXml(xmlElement); if (unsafeUsage.empty()) return nullptr; auto *fileInfo = new MyFileInfo; fileInfo->unsafeUsage = unsafeUsage; return fileInfo; } bool CheckUninitVar::analyseWholeProgram(const CTU::FileInfo *ctu, const std::list<Check::FileInfo*> &fileInfo, const Settings& settings, ErrorLogger &errorLogger) { if (!ctu) return false; bool foundErrors = false; (void)settings; // This argument is unused const std::map<std::string, std::list<const CTU::FileInfo::CallBase *>> callsMap = ctu->getCallsMap(); for (const Check::FileInfo* fi1 : fileInfo) { const auto *fi = dynamic_cast<const MyFileInfo*>(fi1); if (!fi) continue; for (const CTU::FileInfo::UnsafeUsage &unsafeUsage : fi->unsafeUsage) { const CTU::FileInfo::FunctionCall *functionCall = nullptr; const std::list<ErrorMessage::FileLocation> &locationList = CTU::FileInfo::getErrorPath(CTU::FileInfo::InvalidValueType::uninit, unsafeUsage, callsMap, "Using argument ARG", &functionCall, false, settings.maxCtuDepth); if (locationList.empty()) continue; const ErrorMessage errmsg(locationList, emptyString, Severity::error, "Using argument " + unsafeUsage.myArgumentName + " that points at uninitialized variable " + functionCall->callArgumentExpression, "ctuuninitvar", CWE_USE_OF_UNINITIALIZED_VARIABLE, Certainty::normal); errorLogger.reportErr(errmsg); foundErrors = true; } } return foundErrors; }
75,016
C++
.cpp
1,587
34.850032
267
0.529251
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,166
vf_globalstaticvar.cpp
danmar_cppcheck/lib/vf_globalstaticvar.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_globalstaticvar.h" #include "astutils.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <list> #include <map> #include <utility> namespace ValueFlow { void analyzeGlobalStaticVar(TokenList &tokenList, const Settings &settings) { // Get variable values... std::map<const Variable *, Value> vars; for (const Token *tok = tokenList.front(); tok; tok = tok->next()) { if (!tok->variable()) continue; // Initialization... if (tok == tok->variable()->nameToken() && tok->variable()->isStatic() && !tok->variable()->isConst() && tok->valueType() && tok->valueType()->isIntegral() && tok->valueType()->pointer == 0 && tok->valueType()->constness == 0 && Token::Match(tok, "%name% =") && tok->next()->astOperand2() && tok->next()->astOperand2()->hasKnownIntValue()) { vars[tok->variable()] = tok->next()->astOperand2()->values().front(); } else { // If variable is written anywhere in TU then remove it from vars if (!tok->astParent()) continue; if (Token::Match(tok->astParent(), "++|--|&") && !tok->astParent()->astOperand2()) vars.erase(tok->variable()); else if (tok->astParent()->isAssignmentOp()) { if (tok == tok->astParent()->astOperand1()) vars.erase(tok->variable()); else if (tok->isCpp() && Token::Match(tok->astParent()->tokAt(-2), "& %name% =")) vars.erase(tok->variable()); } else if (isLikelyStreamRead(tok->astParent())) { vars.erase(tok->variable()); } else if (Token::Match(tok->astParent(), "[(,]")) vars.erase(tok->variable()); } } // Set values.. for (Token *tok = tokenList.front(); tok; tok = tok->next()) { if (!tok->variable()) continue; const std::map<const Variable *, Value>::const_iterator var = vars.find(tok->variable()); if (var == vars.end()) continue; setTokenValue(tok, var->second, settings); } } }
3,227
C++
.cpp
76
32.644737
101
0.557711
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,167
pathmatch.cpp
danmar_cppcheck/lib/pathmatch.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "pathmatch.h" #include "path.h" #include "utils.h" #include <cstddef> #include <utility> PathMatch::PathMatch(std::vector<std::string> paths, bool caseSensitive) : mPaths(std::move(paths)), mCaseSensitive(caseSensitive) { for (std::string& p : mPaths) { p = Path::fromNativeSeparators(p); if (!mCaseSensitive) strTolower(p); } // TODO: also make lowercase? mWorkingDirectory.push_back(Path::fromNativeSeparators(Path::getCurrentPath())); } bool PathMatch::match(const std::string &path) const { if (path.empty()) return false; std::string findpath = Path::fromNativeSeparators(path); if (!mCaseSensitive) strTolower(findpath); const bool is_absolute = Path::isAbsolute(path); // TODO: align the match logic with ImportProject::ignorePaths() for (std::vector<std::string>::const_iterator i = mPaths.cbegin(); i != mPaths.cend(); ++i) { const std::string pathToMatch((!is_absolute && Path::isAbsolute(*i)) ? Path::getRelativePath(*i, mWorkingDirectory) : *i); // Filtering directory name if (endsWith(pathToMatch,'/')) { if (!endsWith(findpath,'/')) findpath = removeFilename(findpath); if (pathToMatch.length() > findpath.length()) continue; // Match relative paths starting with mask // -isrc matches src/foo.cpp if (findpath.compare(0, pathToMatch.size(), pathToMatch) == 0) return true; // Match only full directory name in middle or end of the path // -isrc matches myproject/src/ but does not match // myproject/srcfiles/ or myproject/mysrc/ if (findpath.find("/" + pathToMatch) != std::string::npos) return true; } // Filtering filename else { if (pathToMatch.length() > findpath.length()) continue; // Check if path ends with mask // -ifoo.cpp matches (./)foo.c, src/foo.cpp and proj/src/foo.cpp // -isrc/file.cpp matches src/foo.cpp and proj/src/foo.cpp if (findpath.compare(findpath.size() - pathToMatch.size(), findpath.size(), pathToMatch) == 0) return true; } } return false; } std::string PathMatch::removeFilename(const std::string &path) { const std::size_t ind = path.find_last_of('/'); return path.substr(0, ind + 1); }
3,234
C++
.cpp
79
34.177215
130
0.645674
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,168
standards.cpp
danmar_cppcheck/lib/standards.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "standards.h" #include "utils.h" #include <utility> #include <simplecpp.h> static Standards::cstd_t mapC(simplecpp::cstd_t cstd) { switch (cstd) { case simplecpp::C89: return Standards::C89; case simplecpp::C99: return Standards::C99; case simplecpp::C11: return Standards::C11; case simplecpp::C17: return Standards::C17; case simplecpp::C23: return Standards::C23; case simplecpp::CUnknown: return Standards::CLatest; } cppcheck::unreachable(); } bool Standards::setC(std::string str) { if (str.empty()) return false; const simplecpp::cstd_t c_new = simplecpp::getCStd(str); const bool b = (c_new != simplecpp::CUnknown); if (b) { c = mapC(c_new); stdValueC = std::move(str); } return b; } std::string Standards::getC() const { return getC(c); } std::string Standards::getC(cstd_t c_std) { switch (c_std) { case C89: return "c89"; case C99: return "c99"; case C11: return "c11"; case C17: return "c17"; case C23: return "c23"; } return ""; } Standards::cstd_t Standards::getC(const std::string &std) { return mapC(simplecpp::getCStd(std)); } static Standards::cppstd_t mapCPP(simplecpp::cppstd_t cppstd) { switch (cppstd) { case simplecpp::CPP03: return Standards::CPP03; case simplecpp::CPP11: return Standards::CPP11; case simplecpp::CPP14: return Standards::CPP14; case simplecpp::CPP17: return Standards::CPP17; case simplecpp::CPP20: return Standards::CPP20; case simplecpp::CPP23: return Standards::CPP23; case simplecpp::CPP26: return Standards::CPP26; case simplecpp::CPPUnknown: return Standards::CPPLatest; } cppcheck::unreachable(); } bool Standards::setCPP(std::string str) { if (str.empty()) return false; const simplecpp::cppstd_t cpp_new = simplecpp::getCppStd(str); const bool b = (cpp_new != simplecpp::CPPUnknown); if (b) { cpp = mapCPP(cpp_new); stdValueCPP = std::move(str); } return b; } std::string Standards::getCPP() const { return getCPP(cpp); } std::string Standards::getCPP(cppstd_t std) { switch (std) { case CPP03: return "c++03"; case CPP11: return "c++11"; case CPP14: return "c++14"; case CPP17: return "c++17"; case CPP20: return "c++20"; case CPP23: return "c++23"; case CPP26: return "c++26"; } return ""; } Standards::cppstd_t Standards::getCPP(const std::string &std) { return mapCPP(simplecpp::getCppStd(std)); } bool Standards::setStd(const std::string& str) { return setC(str) || setCPP(str); }
3,594
C++
.cpp
141
20.843972
72
0.648154
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,169
vf_iterators.cpp
danmar_cppcheck/lib/vf_iterators.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_iterators.h" #include "astutils.h" #include "library.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <utility> namespace ValueFlow { static Library::Container::Yield findIteratorYield(Token* tok, const Token*& ftok, const Settings &settings) { auto yield = astContainerYield(tok, &ftok); if (ftok) return yield; if (!tok->astParent()) return yield; //begin/end free functions return astFunctionYield(tok->astParent()->previous(), settings, &ftok); } void analyzeIterators(TokenList &tokenlist, const Settings &settings) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (!tok->scope()) continue; if (!tok->scope()->isExecutable()) continue; if (!astIsContainer(tok)) continue; const Token* ftok = nullptr; const Library::Container::Yield yield = findIteratorYield(tok, ftok, settings); if (!ftok) continue; Value v(0); v.setKnown(); if (yield == Library::Container::Yield::START_ITERATOR) { v.valueType = Value::ValueType::ITERATOR_START; setTokenValue(const_cast<Token*>(ftok)->next(), std::move(v), settings); } else if (yield == Library::Container::Yield::END_ITERATOR) { v.valueType = Value::ValueType::ITERATOR_END; setTokenValue(const_cast<Token*>(ftok)->next(), std::move(v), settings); } } } }
2,440
C++
.cpp
63
31.571429
112
0.635289
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,170
path.cpp
danmar_cppcheck/lib/path.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #if defined(__GNUC__) && (defined(_WIN32) || defined(__CYGWIN__)) #undef __STRICT_ANSI__ #endif //#define LOG_EMACS_MARKER #include "path.h" #include "utils.h" #include <algorithm> #include <cstdio> #include <cstdlib> #ifdef LOG_EMACS_MARKER #include <iostream> #endif #include <sys/stat.h> #include <unordered_set> #include <utility> #include <simplecpp.h> #ifndef _WIN32 #include <sys/types.h> #include <unistd.h> #else #include <direct.h> #include <windows.h> #endif #if defined(__CYGWIN__) #include <strings.h> #endif #if defined(__APPLE__) #include <mach-o/dyld.h> #endif /** Is the filesystem case insensitive? */ static constexpr bool caseInsensitiveFilesystem() { #if defined(_WIN32) || (defined(__APPLE__) && defined(__MACH__)) // Windows is case insensitive // MacOS is case insensitive by default (also supports case sensitivity) return true; #else // TODO: Non-windows filesystems might be case insensitive return false; #endif } std::string Path::toNativeSeparators(std::string path) { #if defined(_WIN32) constexpr char separ = '/'; constexpr char native = '\\'; #else constexpr char separ = '\\'; constexpr char native = '/'; #endif std::replace(path.begin(), path.end(), separ, native); return path; } std::string Path::fromNativeSeparators(std::string path) { constexpr char nonnative = '\\'; constexpr char newsepar = '/'; std::replace(path.begin(), path.end(), nonnative, newsepar); return path; } std::string Path::simplifyPath(std::string originalPath) { return simplecpp::simplifyPath(std::move(originalPath)); } std::string Path::getPathFromFilename(const std::string &filename) { const std::size_t pos = filename.find_last_of("\\/"); if (pos != std::string::npos) return filename.substr(0, 1 + pos); return ""; } bool Path::sameFileName(const std::string &fname1, const std::string &fname2) { return caseInsensitiveFilesystem() ? (caseInsensitiveStringCompare(fname1, fname2) == 0) : (fname1 == fname2); } std::string Path::removeQuotationMarks(std::string path) { path.erase(std::remove(path.begin(), path.end(), '\"'), path.end()); return path; } std::string Path::getFilenameExtension(const std::string &path, bool lowercase) { const std::string::size_type dotLocation = path.find_last_of('.'); if (dotLocation == std::string::npos) return ""; std::string extension = path.substr(dotLocation); if (lowercase || caseInsensitiveFilesystem()) { // on a case insensitive filesystem the case doesn't matter so // let's return the extension in lowercase strTolower(extension); } return extension; } std::string Path::getFilenameExtensionInLowerCase(const std::string &path) { return getFilenameExtension(path, true); } std::string Path::getCurrentPath() { char currentPath[4096]; #ifndef _WIN32 if (getcwd(currentPath, 4096) != nullptr) #else if (_getcwd(currentPath, 4096) != nullptr) #endif return std::string(currentPath); return ""; } std::string Path::getCurrentExecutablePath(const char* fallback) { char buf[4096] = {}; bool success{}; #ifdef _WIN32 success = (GetModuleFileNameA(nullptr, buf, sizeof(buf)) < sizeof(buf)); #elif defined(__APPLE__) uint32_t size = sizeof(buf); success = (_NSGetExecutablePath(buf, &size) == 0); #else const char* procPath = #ifdef __SVR4 // Solaris "/proc/self/path/a.out"; #elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) || defined(__DragonFly__) "/proc/curproc/file"; #else // Linux "/proc/self/exe"; #endif // readlink does not null-terminate the string if the buffer is too small, therefore write bufsize - 1 success = (readlink(procPath, buf, sizeof(buf) - 1) != -1); #endif return success ? std::string(buf) : std::string(fallback); } bool Path::isAbsolute(const std::string& path) { const std::string& nativePath = toNativeSeparators(path); #ifdef _WIN32 if (path.length() < 2) return false; // On Windows, 'C:\foo\bar' is an absolute path, while 'C:foo\bar' is not return startsWith(nativePath, "\\\\") || (std::isalpha(nativePath[0]) != 0 && nativePath.compare(1, 2, ":\\") == 0); #else return !nativePath.empty() && nativePath[0] == '/'; #endif } std::string Path::getRelativePath(const std::string& absolutePath, const std::vector<std::string>& basePaths) { for (const std::string &bp : basePaths) { if (absolutePath == bp || bp.empty()) // Seems to be a file, or path is empty continue; if (absolutePath.compare(0, bp.length(), bp) != 0) continue; if (endsWith(bp,'/')) return absolutePath.substr(bp.length()); if (absolutePath.size() > bp.size() && absolutePath[bp.length()] == '/') return absolutePath.substr(bp.length() + 1); } return absolutePath; } static const std::unordered_set<std::string> cpp_src_exts = { ".cpp", ".cxx", ".cc", ".c++", ".tpp", ".txx", ".ipp", ".ixx" }; static const std::unordered_set<std::string> c_src_exts = { ".c", ".cl" }; static const std::unordered_set<std::string> header_exts = { ".h", ".hpp", ".h++", ".hxx", ".hh" }; bool Path::acceptFile(const std::string &path, const std::set<std::string> &extra) { bool header = false; return (identify(path, false, &header) != Standards::Language::None && !header) || extra.find(getFilenameExtension(path)) != extra.end(); } static bool hasEmacsCppMarker(const char* path) { // TODO: identify is called three times for each file // Preprocessor::loadFiles() -> createDUI() // Preprocessor::preprocess() -> createDUI() // TokenList::createTokens() -> TokenList::determineCppC() #ifdef LOG_EMACS_MARKER std::cout << path << '\n'; #endif FILE *fp = fopen(path, "rt"); if (!fp) return false; std::string buf(128, '\0'); { // TODO: read the whole first line only const char * const res = fgets(const_cast<char*>(buf.data()), buf.size(), fp); fclose(fp); fp = nullptr; if (!res) return false; // failed to read file } // TODO: replace with regular expression const auto pos1 = buf.find("-*-"); if (pos1 == std::string::npos) return false; // no start marker const auto pos_nl = buf.find_first_of("\r\n"); if (pos_nl != std::string::npos && (pos_nl < pos1)) { #ifdef LOG_EMACS_MARKER std::cout << path << " - Emacs marker not on the first line" << '\n'; #endif return false; // not on first line } const auto pos2 = buf.find("-*-", pos1 + 3); // TODO: make sure we have read the whole line before bailing out if (pos2 == std::string::npos) { #ifdef LOG_EMACS_MARKER std::cout << path << " - Emacs marker not terminated" << '\n'; #endif return false; // no end marker } #ifdef LOG_EMACS_MARKER std::cout << "Emacs marker: '" << buf.substr(pos1, (pos2 + 3) - pos1) << "'" << '\n'; #endif // TODO: support /* */ comments const std::string buf_trim = trim(buf); // trim whitespaces if (buf_trim[0] == '/' && buf_trim[1] == '*') { const auto pos_cmt = buf.find("*/", 2); if (pos_cmt != std::string::npos && pos_cmt < (pos2 + 3)) { #ifdef LOG_EMACS_MARKER std::cout << path << " - Emacs marker not contained in C-style comment block: '" << buf.substr(pos1, (pos2 + 3) - pos1) << "'" << '\n'; #endif return false; // not in a comment } } else if (buf_trim[0] != '/' || buf_trim[1] != '/') { #ifdef LOG_EMACS_MARKER std::cout << path << " - Emacs marker not in a comment: '" << buf.substr(pos1, (pos2 + 3) - pos1) << "'" << '\n'; #endif return false; // not in a comment } // there are more variations with lowercase and no whitespaces // -*- C++ -*- // -*- Mode: C++; -*- // -*- Mode: C++; c-basic-offset: 8 -*- std::string marker = trim(buf.substr(pos1 + 3, pos2 - pos1 - 3), " ;"); // cut off additional attributes const auto pos_semi = marker.find(';'); if (pos_semi != std::string::npos) marker.resize(pos_semi); findAndReplace(marker, "mode:", ""); findAndReplace(marker, "Mode:", ""); marker = trim(marker); if (marker == "C++" || marker == "c++") { // NOLINTNEXTLINE(readability-simplify-boolean-expr) - TODO: FP return true; // C++ marker found } //if (marker == "C" || marker == "c") // return false; #ifdef LOG_EMACS_MARKER std::cout << path << " - unmatched Emacs marker: '" << marker << "'" << '\n'; #endif return false; // marker is not a C++ one } Standards::Language Path::identify(const std::string &path, bool cppHeaderProbe, bool *header) { // cppcheck-suppress uninitvar - TODO: FP if (header) *header = false; std::string ext = getFilenameExtension(path); // standard library headers have no extension if (cppHeaderProbe && ext.empty()) { if (hasEmacsCppMarker(path.c_str())) { if (header) *header = true; return Standards::Language::CPP; } return Standards::Language::None; } if (ext == ".C") return Standards::Language::CPP; if (c_src_exts.find(ext) != c_src_exts.end()) return Standards::Language::C; // cppcheck-suppress knownConditionTrueFalse - TODO: FP if (!caseInsensitiveFilesystem()) strTolower(ext); if (ext == ".h") { if (header) *header = true; if (cppHeaderProbe && hasEmacsCppMarker(path.c_str())) return Standards::Language::CPP; return Standards::Language::C; } if (cpp_src_exts.find(ext) != cpp_src_exts.end()) return Standards::Language::CPP; if (header_exts.find(ext) != header_exts.end()) { if (header) *header = true; return Standards::Language::CPP; } return Standards::Language::None; } bool Path::isHeader(const std::string &path) { bool header; (void)identify(path, false, &header); return header; } std::string Path::getAbsoluteFilePath(const std::string& filePath) { std::string absolute_path; #ifdef _WIN32 char absolute[_MAX_PATH]; if (_fullpath(absolute, filePath.c_str(), _MAX_PATH)) absolute_path = absolute; #elif defined(__linux__) || defined(__sun) || defined(__hpux) || defined(__GNUC__) || defined(__CPPCHECK__) char * absolute = realpath(filePath.c_str(), nullptr); if (absolute) absolute_path = absolute; free(absolute); #else #error Platform absolute path function needed #endif return absolute_path; } std::string Path::stripDirectoryPart(const std::string &file) { #if defined(_WIN32) && !defined(__MINGW32__) constexpr char native = '\\'; #else constexpr char native = '/'; #endif const std::string::size_type p = file.rfind(native); if (p != std::string::npos) { return file.substr(p + 1); } return file; } #ifdef _WIN32 using mode_t = unsigned short; #endif static mode_t file_type(const std::string &path) { struct stat file_stat; if (stat(path.c_str(), &file_stat) == -1) return 0; return file_stat.st_mode & S_IFMT; } bool Path::isFile(const std::string &path) { return file_type(path) == S_IFREG; } bool Path::isDirectory(const std::string &path) { return file_type(path) == S_IFDIR; } std::string Path::join(const std::string& path1, const std::string& path2) { if (path1.empty() || path2.empty()) return path1 + path2; if (path2.front() == '/') return path2; return ((path1.back() == '/') ? path1 : (path1 + "/")) + path2; }
12,507
C++
.cpp
371
29.458221
148
0.635973
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,171
vf_subfunction.cpp
danmar_cppcheck/lib/vf_subfunction.cpp
/* -*- C++ -*- * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_subfunction.h" #include "astutils.h" #include "config.h" #include "forwardanalyzer.h" #include "library.h" #include "mathlib.h" #include "programmemory.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "utils.h" #include "valueptr.h" #include "vfvalue.h" #include "vf_analyzers.h" #include "vf_bailout.h" #include "vf_common.h" #include "vf_settokenvalue.h" #include "checkuninitvar.h" #include <algorithm> #include <iterator> #include <list> #include <string> #include <unordered_map> #include <utility> #include <vector> namespace ValueFlow { static std::list<Value> getFunctionArgumentValues(const Token *argtok) { std::list<Value> argvalues(argtok->values()); removeImpossible(argvalues); if (argvalues.empty() && Token::Match(argtok, "%comp%|%oror%|&&|!")) { argvalues.emplace_back(0); argvalues.emplace_back(1); } return argvalues; } template<class Key, class F> static bool productParams(const Settings& settings, const std::unordered_map<Key, std::list<Value>>& vars, F f) { using Args = std::vector<std::unordered_map<Key, Value>>; Args args(1); // Compute cartesian product of all arguments for (const auto& p:vars) { if (p.second.empty()) continue; args.back()[p.first] = p.second.front(); } bool bail = false; int max = settings.vfOptions.maxSubFunctionArgs; for (const auto& p:vars) { if (args.size() > max) { bail = true; break; } if (p.second.empty()) continue; std::for_each(std::next(p.second.begin()), p.second.end(), [&](const Value& value) { Args new_args; for (auto arg:args) { if (value.path != 0) { for (const auto& q:arg) { if (q.first == p.first) continue; if (q.second.path == 0) continue; if (q.second.path != value.path) return; } } arg[p.first] = value; new_args.push_back(std::move(arg)); } std::copy(new_args.cbegin(), new_args.cend(), std::back_inserter(args)); }); } if (args.size() > max) { bail = true; args.resize(max); // TODO: add bailout message } for (const auto& arg:args) { if (arg.empty()) continue; // Make sure all arguments are the same path const MathLib::bigint path = arg.cbegin()->second.path; if (std::any_of(arg.cbegin(), arg.cend(), [&](const std::pair<Key, Value>& p) { return p.second.path != path; })) continue; f(arg); } return !bail; } static void valueFlowLibraryFunction(Token *tok, const std::string &returnValue, const Settings &settings) { std::unordered_map<nonneg int, std::list<Value>> argValues; int argn = 1; for (const Token *argtok : getArguments(tok->previous())) { argValues[argn] = getFunctionArgumentValues(argtok); argn++; } if (returnValue.find("arg") != std::string::npos && argValues.empty()) return; productParams(settings, argValues, [&](const std::unordered_map<nonneg int, Value>& arg) { Value value = evaluateLibraryFunction(arg, returnValue, settings, tok->isCpp()); if (value.isUninitValue()) return; Value::ValueKind kind = Value::ValueKind::Known; for (auto&& p : arg) { if (p.second.isPossible()) kind = p.second.valueKind; if (p.second.isInconclusive()) { kind = p.second.valueKind; break; } } if (value.isImpossible() && kind != Value::ValueKind::Known) return; if (!value.isImpossible()) value.valueKind = kind; setTokenValue(tok, std::move(value), settings); }); } static void valueFlowInjectParameter(const TokenList& tokenlist, ErrorLogger& errorLogger, const Settings& settings, const Scope* functionScope, const std::unordered_map<const Variable*, std::list<Value>>& vars) { const bool r = productParams(settings, vars, [&](const std::unordered_map<const Variable*, Value>& arg) { auto a = makeMultiValueFlowAnalyzer(arg, settings); valueFlowGenericForward(const_cast<Token*>(functionScope->bodyStart), functionScope->bodyEnd, a, tokenlist, errorLogger, settings); }); if (!r) { std::string fname = "<unknown>"; if (const Function* f = functionScope->function) fname = f->name(); if (settings.debugwarnings) bailout(tokenlist, errorLogger, functionScope->bodyStart, "Too many argument passed to " + fname); } } void analyzeSubFunction(const TokenList& tokenlist, SymbolDatabase& symboldatabase, ErrorLogger& errorLogger, const Settings& settings) { int id = 0; for (auto it = symboldatabase.functionScopes.crbegin(); it != symboldatabase.functionScopes.crend(); ++it) { const Scope* scope = *it; const Function* function = scope->function; if (!function) continue; for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { if (tok->isKeyword() || !Token::Match(tok, "%name% (")) continue; const Function * const calledFunction = tok->function(); if (!calledFunction) { // library function? const std::string& returnValue(settings.library.returnValue(tok)); if (!returnValue.empty()) valueFlowLibraryFunction(tok->next(), returnValue, settings); continue; } const Scope * const calledFunctionScope = calledFunction->functionScope; if (!calledFunctionScope) continue; id++; std::unordered_map<const Variable*, std::list<Value>> argvars; // TODO: Rewrite this. It does not work well to inject 1 argument at a time. const std::vector<const Token *> &callArguments = getArguments(tok); for (int argnr = 0U; argnr < callArguments.size(); ++argnr) { const Token *argtok = callArguments[argnr]; // Get function argument const Variable * const argvar = calledFunction->getArgumentVar(argnr); if (!argvar) break; // passing value(s) to function std::list<Value> argvalues(getFunctionArgumentValues(argtok)); // Remove non-local lifetimes argvalues.remove_if([](const Value& v) { if (v.isLifetimeValue()) return !v.isLocalLifetimeValue() && !v.isSubFunctionLifetimeValue(); return false; }); // Remove uninit values if argument is passed by value if (argtok->variable() && !argtok->variable()->isPointer() && argvalues.size() == 1 && argvalues.front().isUninitValue()) { if (CheckUninitVar::isVariableUsage(argtok, settings.library, false, CheckUninitVar::Alloc::NO_ALLOC, 0)) continue; } if (argvalues.empty()) continue; // Error path.. for (Value &v : argvalues) { const std::string nr = std::to_string(argnr + 1) + getOrdinalText(argnr + 1); v.errorPath.emplace_back(argtok, "Calling function '" + calledFunction->name() + "', " + nr + " argument '" + argtok->expressionString() + "' value is " + v.infoString()); v.path = 256 * v.path + id % 256; // Change scope of lifetime values if (v.isLifetimeValue()) v.lifetimeScope = Value::LifetimeScope::SubFunction; } // passed values are not "known".. lowerToPossible(argvalues); argvars[argvar] = std::move(argvalues); } valueFlowInjectParameter(tokenlist, errorLogger, settings, calledFunctionScope, argvars); } } } }
10,419
C++
.cpp
232
30.400862
143
0.517167
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,173
summaries.cpp
danmar_cppcheck/lib/summaries.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "summaries.h" #include "analyzerinfo.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include <algorithm> #include <fstream> #include <map> #include <sstream> #include <utility> #include <vector> std::string Summaries::create(const Tokenizer &tokenizer, const std::string &cfg) { const SymbolDatabase *symbolDatabase = tokenizer.getSymbolDatabase(); const Settings &settings = tokenizer.getSettings(); std::ostringstream ostr; for (const Scope *scope : symbolDatabase->functionScopes) { const Function *f = scope->function; if (!f) continue; // Summarize function std::set<std::string> noreturn; std::set<std::string> globalVars; std::set<std::string> calledFunctions; for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (tok->variable() && tok->variable()->isGlobal()) globalVars.insert(tok->variable()->name()); if (Token::Match(tok, "%name% (") && !Token::simpleMatch(tok->linkAt(1), ") {")) { calledFunctions.insert(tok->str()); if (Token::simpleMatch(tok->linkAt(1), ") ; }")) noreturn.insert(tok->str()); } } // Write summary for function auto join = [](const std::set<std::string> &data) -> std::string { std::string ret; const char *sep = ""; for (const std::string &d: data) { ret += sep + d; sep = ","; } return ret; }; ostr << f->name(); if (!globalVars.empty()) ostr << " global:[" << join(globalVars) << "]"; if (!calledFunctions.empty()) ostr << " call:[" << join(calledFunctions) << "]"; if (!noreturn.empty()) ostr << " noreturn:[" << join(noreturn) << "]"; ostr << std::endl; } if (!settings.buildDir.empty()) { std::string filename = AnalyzerInformation::getAnalyzerInfoFile(settings.buildDir, tokenizer.list.getSourceFilePath(), cfg); const std::string::size_type pos = filename.rfind(".a"); if (pos != std::string::npos) { filename[pos+1] = 's'; std::ofstream fout(filename); fout << ostr.str(); } } return ostr.str(); } static std::vector<std::string> getSummaryFiles(const std::string &filename) { std::vector<std::string> ret; std::ifstream fin(filename); if (!fin.is_open()) return ret; std::string line; while (std::getline(fin, line)) { const std::string::size_type dotA = line.find(".a"); const std::string::size_type colon = line.find(':'); if (colon > line.size() || dotA > colon) continue; std::string f = line.substr(0,colon); f[dotA + 1] = 's'; ret.push_back(std::move(f)); } return ret; } static std::vector<std::string> getSummaryData(const std::string &line, const std::string &data) { std::vector<std::string> ret; const std::string::size_type start = line.find(" " + data + ":["); if (start == std::string::npos) return ret; const std::string::size_type end = line.find(']', start); if (end >= line.size()) return ret; std::string::size_type pos1 = start + 3 + data.size(); while (pos1 < end) { const std::string::size_type pos2 = line.find_first_of(",]",pos1); ret.push_back(line.substr(pos1, pos2-pos1-1)); pos1 = pos2 + 1; } return ret; } static void removeFunctionCalls(const std::string& calledFunction, std::map<std::string, std::vector<std::string>> &functionCalledBy, std::map<std::string, std::vector<std::string>> &functionCalls, std::vector<std::string> &add) { std::vector<std::string> calledBy = functionCalledBy[calledFunction]; functionCalledBy.erase(calledFunction); for (const std::string &c: calledBy) { std::vector<std::string> &calls = functionCalls[c]; calls.erase(std::remove(calls.begin(), calls.end(), calledFunction), calls.end()); if (calls.empty()) { add.push_back(calledFunction); removeFunctionCalls(c, functionCalledBy, functionCalls, add); } } } void Summaries::loadReturn(const std::string &buildDir, std::set<std::string> &summaryReturn) { if (buildDir.empty()) return; std::vector<std::string> return1; std::map<std::string, std::vector<std::string>> functionCalls; std::map<std::string, std::vector<std::string>> functionCalledBy; // extract "functionNoreturn" and "functionCalledBy" from summaries std::vector<std::string> summaryFiles = getSummaryFiles(buildDir + "/files.txt"); for (const std::string &filename: summaryFiles) { std::ifstream fin(buildDir + '/' + filename); if (!fin.is_open()) continue; std::string line; while (std::getline(fin, line)) { // Get function name constexpr std::string::size_type pos1 = 0; const std::string::size_type pos2 = line.find(' ', pos1); const std::string functionName = (pos2 == std::string::npos) ? line : line.substr(0, pos2); std::vector<std::string> call = getSummaryData(line, "call"); functionCalls[functionName] = call; if (call.empty()) return1.push_back(functionName); else { for (const std::string &c: call) { functionCalledBy[c].push_back(functionName); } } } } summaryReturn.insert(return1.cbegin(), return1.cend()); // recursively set "summaryNoreturn" for (const std::string &f: return1) { std::vector<std::string> return2; removeFunctionCalls(f, functionCalledBy, functionCalls, return2); summaryReturn.insert(return2.cbegin(), return2.cend()); } }
6,901
C++
.cpp
172
32.30814
132
0.601491
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,175
vfvalue.cpp
danmar_cppcheck/lib/vfvalue.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vfvalue.h" #include "errortypes.h" #include "token.h" #include <sstream> #include <string> namespace ValueFlow { Value::Value(const Token *c, long long val, Bound b) : bound(b), intvalue(val), varvalue(val), condition(c) { errorPath.emplace_back(c, "Assuming that condition '" + c->expressionString() + "' is not redundant"); } void Value::assumeCondition(const Token *tok) { condition = tok; errorPath.emplace_back(tok, "Assuming that condition '" + tok->expressionString() + "' is not redundant"); } std::string Value::toString() const { std::stringstream ss; if (this->isImpossible()) ss << "!"; if (this->bound == Bound::Lower) ss << ">="; if (this->bound == Bound::Upper) ss << "<="; switch (this->valueType) { case ValueType::INT: ss << this->intvalue; break; case ValueType::TOK: ss << this->tokvalue->str(); break; case ValueType::FLOAT: ss << this->floatValue; break; case ValueType::MOVED: ss << toString(this->moveKind); break; case ValueType::UNINIT: ss << "Uninit"; break; case ValueType::BUFFER_SIZE: case ValueType::CONTAINER_SIZE: ss << "size=" << this->intvalue; break; case ValueType::ITERATOR_START: ss << "start=" << this->intvalue; break; case ValueType::ITERATOR_END: ss << "end=" << this->intvalue; break; case ValueType::LIFETIME: ss << "lifetime[" << toString(this->lifetimeKind) << "]=(" << this->tokvalue->expressionString() << ")"; break; case ValueType::SYMBOLIC: ss << "symbolic=(" << this->tokvalue->expressionString(); if (this->intvalue > 0) ss << "+" << this->intvalue; else if (this->intvalue < 0) ss << "-" << -this->intvalue; ss << ")"; break; } if (this->indirect > 0) for (int i = 0; i < this->indirect; i++) ss << "*"; if (this->path > 0) ss << "@" << this->path; return ss.str(); } std::string Value::infoString() const { switch (valueType) { case ValueType::INT: return std::to_string(intvalue); case ValueType::TOK: return tokvalue->str(); case ValueType::FLOAT: return MathLib::toString(floatValue); case ValueType::MOVED: return "<Moved>"; case ValueType::UNINIT: return "<Uninit>"; case ValueType::BUFFER_SIZE: case ValueType::CONTAINER_SIZE: return "size=" + std::to_string(intvalue); case ValueType::ITERATOR_START: return "start=" + std::to_string(intvalue); case ValueType::ITERATOR_END: return "end=" + std::to_string(intvalue); case ValueType::LIFETIME: return "lifetime=" + tokvalue->str(); case ValueType::SYMBOLIC: { std::string result = "symbolic=" + tokvalue->expressionString(); if (intvalue > 0) result += "+" + std::to_string(intvalue); else if (intvalue < 0) result += "-" + std::to_string(-intvalue); return result; } } throw InternalError(nullptr, "Invalid ValueFlow Value type"); } const char *Value::toString(MoveKind moveKind) { switch (moveKind) { case MoveKind::NonMovedVariable: return "NonMovedVariable"; case MoveKind::MovedVariable: return "MovedVariable"; case MoveKind::ForwardedVariable: return "ForwardedVariable"; } return ""; } const char *Value::toString(LifetimeKind lifetimeKind) { switch (lifetimeKind) { case LifetimeKind::Object: return "Object"; case LifetimeKind::SubObject: return "SubObject"; case LifetimeKind::Lambda: return "Lambda"; case LifetimeKind::Iterator: return "Iterator"; case LifetimeKind::Address: return "Address"; } return ""; } bool Value::sameToken(const Token *tok1, const Token *tok2) { if (tok1 == tok2) return true; if (!tok1) return false; if (tok1->exprId() == 0 || tok2->exprId() == 0) return false; return tok1->exprId() == tok2->exprId(); } const char *Value::toString(LifetimeScope lifetimeScope) { switch (lifetimeScope) { case LifetimeScope::Local: return "Local"; case LifetimeScope::Argument: return "Argument"; case LifetimeScope::SubFunction: return "SubFunction"; case LifetimeScope::ThisPointer: return "ThisPointer"; case LifetimeScope::ThisValue: return "ThisValue"; } return ""; } const char *Value::toString(Bound bound) { switch (bound) { case Bound::Point: return "Point"; case Bound::Upper: return "Upper"; case Bound::Lower: return "Lower"; } return ""; } }
6,250
C++
.cpp
183
24.874317
114
0.554253
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,176
errorlogger.cpp
danmar_cppcheck/lib/errorlogger.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "errorlogger.h" #include "color.h" #include "cppcheck.h" #include "path.h" #include "settings.h" #include "suppressions.h" #include "token.h" #include "tokenlist.h" #include "utils.h" #include <algorithm> #include <array> #include <cassert> #include <cctype> #include <cstring> #include <fstream> #include <iomanip> #include <sstream> #include <string> #include <unordered_map> #include <utility> #include "xml.h" const std::set<std::string> ErrorLogger::mCriticalErrorIds{ "cppcheckError", "cppcheckLimit", "internalAstError", "instantiationError", "internalError", "premium-internalError", "premium-invalidArgument", "premium-invalidLicense", "preprocessorErrorDirective", "syntaxError", "unknownMacro" }; ErrorMessage::ErrorMessage() : severity(Severity::none), cwe(0U), certainty(Certainty::normal), hash(0) {} // TODO: id and msg are swapped compared to other calls ErrorMessage::ErrorMessage(std::list<FileLocation> callStack, std::string file1, Severity severity, const std::string &msg, std::string id, Certainty certainty) : callStack(std::move(callStack)), // locations for this error message id(std::move(id)), // set the message id file0(std::move(file1)), severity(severity), // severity for this error message cwe(0U), certainty(certainty), hash(0) { // set the summary and verbose messages setmsg(msg); } // TODO: id and msg are swapped compared to other calls ErrorMessage::ErrorMessage(std::list<FileLocation> callStack, std::string file1, Severity severity, const std::string &msg, std::string id, const CWE &cwe, Certainty certainty) : callStack(std::move(callStack)), // locations for this error message id(std::move(id)), // set the message id file0(std::move(file1)), severity(severity), // severity for this error message cwe(cwe.id), certainty(certainty), hash(0) { // set the summary and verbose messages setmsg(msg); } ErrorMessage::ErrorMessage(const std::list<const Token*>& callstack, const TokenList* list, Severity severity, std::string id, const std::string& msg, Certainty certainty) : id(std::move(id)), severity(severity), cwe(0U), certainty(certainty), hash(0) { // Format callstack for (std::list<const Token *>::const_iterator it = callstack.cbegin(); it != callstack.cend(); ++it) { // --errorlist can provide null values here if (!(*it)) continue; callStack.emplace_back(*it, list); } if (list && !list->getFiles().empty()) file0 = list->getFiles()[0]; setmsg(msg); } ErrorMessage::ErrorMessage(const std::list<const Token*>& callstack, const TokenList* list, Severity severity, std::string id, const std::string& msg, const CWE &cwe, Certainty certainty) : id(std::move(id)), severity(severity), cwe(cwe.id), certainty(certainty) { // Format callstack for (const Token *tok: callstack) { // --errorlist can provide null values here if (!tok) continue; callStack.emplace_back(tok, list); } if (list && !list->getFiles().empty()) file0 = list->getFiles()[0]; setmsg(msg); hash = 0; // calculateWarningHash(list, hashWarning.str()); } ErrorMessage::ErrorMessage(const ErrorPath &errorPath, const TokenList *tokenList, Severity severity, const char id[], const std::string &msg, const CWE &cwe, Certainty certainty) : id(id), severity(severity), cwe(cwe.id), certainty(certainty) { // Format callstack for (const ErrorPathItem& e: errorPath) { const Token *tok = e.first; // --errorlist can provide null values here if (!tok) continue; const std::string& path_info = e.second; std::string info; if (startsWith(path_info,"$symbol:") && path_info.find('\n') < path_info.size()) { const std::string::size_type pos = path_info.find('\n'); const std::string symbolName = path_info.substr(8, pos - 8); info = replaceStr(path_info.substr(pos+1), "$symbol", symbolName); } else { info = path_info; } callStack.emplace_back(tok, std::move(info), tokenList); } if (tokenList && !tokenList->getFiles().empty()) file0 = tokenList->getFiles()[0]; setmsg(msg); hash = 0; // calculateWarningHash(tokenList, hashWarning.str()); } ErrorMessage::ErrorMessage(const tinyxml2::XMLElement * const errmsg) : severity(Severity::none), cwe(0U), certainty(Certainty::normal) { const char * const unknown = "<UNKNOWN>"; const char *attr = errmsg->Attribute("id"); id = attr ? attr : unknown; attr = errmsg->Attribute("severity"); severity = attr ? severityFromString(attr) : Severity::none; attr = errmsg->Attribute("cwe"); // cppcheck-suppress templateInstantiation - TODO: fix this - see #11631 cwe.id = attr ? strToInt<unsigned short>(attr) : 0; attr = errmsg->Attribute("inconclusive"); certainty = (attr && (std::strcmp(attr, "true") == 0)) ? Certainty::inconclusive : Certainty::normal; attr = errmsg->Attribute("msg"); mShortMessage = attr ? attr : ""; attr = errmsg->Attribute("verbose"); mVerboseMessage = attr ? attr : ""; attr = errmsg->Attribute("hash"); hash = attr ? strToInt<std::size_t>(attr) : 0; for (const tinyxml2::XMLElement *e = errmsg->FirstChildElement(); e; e = e->NextSiblingElement()) { const char* name = e->Name(); if (std::strcmp(name,"location")==0) { const char *strfile = e->Attribute("file"); const char *strinfo = e->Attribute("info"); const char *strline = e->Attribute("line"); const char *strcolumn = e->Attribute("column"); const char *file = strfile ? strfile : unknown; const char *info = strinfo ? strinfo : ""; const int line = strline ? strToInt<int>(strline) : 0; const int column = strcolumn ? strToInt<int>(strcolumn) : 0; callStack.emplace_front(file, info, line, column); } else if (std::strcmp(name,"symbol")==0) { mSymbolNames += e->GetText(); } } } void ErrorMessage::setmsg(const std::string &msg) { // If a message ends to a '\n' and contains only a one '\n' // it will cause the mVerboseMessage to be empty which will show // as an empty message to the user if --verbose is used. // Even this doesn't cause problems with messages that have multiple // lines, none of the error messages should end into it. assert(!endsWith(msg,'\n')); // The summary and verbose message are separated by a newline // If there is no newline then both the summary and verbose messages // are the given message const std::string::size_type pos = msg.find('\n'); const std::string symbolName = mSymbolNames.empty() ? std::string() : mSymbolNames.substr(0, mSymbolNames.find('\n')); if (pos == std::string::npos) { mShortMessage = replaceStr(msg, "$symbol", symbolName); mVerboseMessage = replaceStr(msg, "$symbol", symbolName); } else if (startsWith(msg,"$symbol:")) { mSymbolNames += msg.substr(8, pos-7); setmsg(msg.substr(pos + 1)); } else { mShortMessage = replaceStr(msg.substr(0, pos), "$symbol", symbolName); mVerboseMessage = replaceStr(msg.substr(pos + 1), "$symbol", symbolName); } } static void serializeString(std::string &oss, const std::string & str) { oss += std::to_string(str.length()); oss += " "; oss += str; } ErrorMessage ErrorMessage::fromInternalError(const InternalError &internalError, const TokenList *tokenList, const std::string &filename, const std::string& msg) { if (internalError.token) assert(tokenList != nullptr); // we need to make sure we can look up the provided token std::list<ErrorMessage::FileLocation> locationList; if (tokenList && internalError.token) { locationList.emplace_back(internalError.token, tokenList); } else { locationList.emplace_back(filename, 0, 0); if (tokenList && (filename != tokenList->getSourceFilePath())) { locationList.emplace_back(tokenList->getSourceFilePath(), 0, 0); } } ErrorMessage errmsg(std::move(locationList), tokenList ? tokenList->getSourceFilePath() : filename, Severity::error, (msg.empty() ? "" : (msg + ": ")) + internalError.errorMessage, internalError.id, Certainty::normal); // TODO: find a better way if (!internalError.details.empty()) errmsg.mVerboseMessage = errmsg.mVerboseMessage + ": " + internalError.details; return errmsg; } std::string ErrorMessage::serialize() const { // Serialize this message into a simple string std::string oss; serializeString(oss, id); serializeString(oss, severityToString(severity)); serializeString(oss, std::to_string(cwe.id)); serializeString(oss, std::to_string(hash)); serializeString(oss, fixInvalidChars(remark)); serializeString(oss, file0); serializeString(oss, (certainty == Certainty::inconclusive) ? "1" : "0"); const std::string saneShortMessage = fixInvalidChars(mShortMessage); const std::string saneVerboseMessage = fixInvalidChars(mVerboseMessage); serializeString(oss, saneShortMessage); serializeString(oss, saneVerboseMessage); oss += std::to_string(callStack.size()); oss += " "; for (std::list<ErrorMessage::FileLocation>::const_iterator loc = callStack.cbegin(); loc != callStack.cend(); ++loc) { std::string frame; frame += std::to_string(loc->line); frame += '\t'; frame += std::to_string(loc->column); frame += '\t'; frame += loc->getfile(false); frame += '\t'; frame += loc->getOrigFile(false); frame += '\t'; frame += loc->getinfo(); serializeString(oss, frame); } return oss; } void ErrorMessage::deserialize(const std::string &data) { // TODO: clear all fields certainty = Certainty::normal; callStack.clear(); std::istringstream iss(data); std::array<std::string, 9> results; std::size_t elem = 0; while (iss.good() && elem < 9) { unsigned int len = 0; if (!(iss >> len)) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid length"); if (iss.get() != ' ') throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid separator"); if (!iss.good()) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data"); std::string temp; if (len > 0) { temp.resize(len); iss.read(&temp[0], len); if (!iss.good()) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data"); } results[elem++] = std::move(temp); } if (!iss.good()) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data"); if (elem != 9) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - insufficient elements"); id = std::move(results[0]); severity = severityFromString(results[1]); cwe.id = 0; if (!results[2].empty()) { std::string err; if (!strToInt(results[2], cwe.id, &err)) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid CWE ID - " + err); } hash = 0; if (!results[3].empty()) { std::string err; if (!strToInt(results[3], hash, &err)) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid hash - " + err); } remark = std::move(results[4]); file0 = std::move(results[5]); if (results[6] == "1") certainty = Certainty::inconclusive; mShortMessage = std::move(results[7]); mVerboseMessage = std::move(results[8]); unsigned int stackSize = 0; if (!(iss >> stackSize)) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid stack size"); if (iss.get() != ' ') throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid separator"); if (stackSize == 0) return; while (iss.good()) { unsigned int len = 0; if (!(iss >> len)) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid length (stack)"); if (iss.get() != ' ') throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - invalid separator (stack)"); std::string temp; if (len > 0) { temp.resize(len); iss.read(&temp[0], len); if (!iss.good()) throw InternalError(nullptr, "Internal Error: Deserialization of error message failed - premature end of data (stack)"); } std::vector<std::string> substrings; substrings.reserve(5); for (std::string::size_type pos = 0; pos < temp.size() && substrings.size() < 5; ++pos) { if (substrings.size() == 4) { substrings.push_back(temp.substr(pos)); break; } const std::string::size_type start = pos; pos = temp.find('\t', pos); if (pos == std::string::npos) { substrings.push_back(temp.substr(start)); break; } substrings.push_back(temp.substr(start, pos - start)); } if (substrings.size() < 4) throw InternalError(nullptr, "Internal Error: Deserializing of error message failed"); // (*loc).line << '\t' << (*loc).column << '\t' << (*loc).getfile(false) << '\t' << loc->getOrigFile(false) << '\t' << loc->getinfo(); std::string info; if (substrings.size() == 5) info = std::move(substrings[4]); ErrorMessage::FileLocation loc(substrings[3], std::move(info), strToInt<int>(substrings[0]), strToInt<unsigned int>(substrings[1])); loc.setfile(std::move(substrings[2])); callStack.push_back(std::move(loc)); if (callStack.size() >= stackSize) break; } } std::string ErrorMessage::getXMLHeader(std::string productName, int xmlVersion) { const auto nameAndVersion = Settings::getNameAndVersion(productName); productName = nameAndVersion.first; const std::string version = nameAndVersion.first.empty() ? CppCheck::version() : nameAndVersion.second; tinyxml2::XMLPrinter printer; // standard xml header printer.PushDeclaration("xml version=\"1.0\" encoding=\"UTF-8\""); // header printer.OpenElement("results", false); printer.PushAttribute("version", xmlVersion); printer.OpenElement("cppcheck", false); if (!productName.empty()) printer.PushAttribute("product-name", productName.c_str()); printer.PushAttribute("version", version.c_str()); printer.CloseElement(false); printer.OpenElement("errors", false); return std::string(printer.CStr()) + '>'; } std::string ErrorMessage::getXMLFooter(int xmlVersion) { return xmlVersion == 3 ? "</results>" : " </errors>\n</results>"; } // There is no utf-8 support around but the strings should at least be safe for to tinyxml2. // See #5300 "Invalid encoding in XML output" and #6431 "Invalid XML created - Invalid encoding of string literal " std::string ErrorMessage::fixInvalidChars(const std::string& raw) { std::string result; result.reserve(raw.length()); std::string::const_iterator from=raw.cbegin(); while (from!=raw.cend()) { if (std::isprint(static_cast<unsigned char>(*from))) { result.push_back(*from); } else { std::ostringstream es; // straight cast to (unsigned) doesn't work out. const unsigned uFrom = (unsigned char)*from; es << '\\' << std::setbase(8) << std::setw(3) << std::setfill('0') << uFrom; result += es.str(); } ++from; } return result; } std::string ErrorMessage::toXML() const { tinyxml2::XMLPrinter printer(nullptr, false, 2); printer.OpenElement("error", false); printer.PushAttribute("id", id.c_str()); printer.PushAttribute("severity", severityToString(severity).c_str()); printer.PushAttribute("msg", fixInvalidChars(mShortMessage).c_str()); printer.PushAttribute("verbose", fixInvalidChars(mVerboseMessage).c_str()); if (cwe.id) printer.PushAttribute("cwe", cwe.id); if (hash) printer.PushAttribute("hash", std::to_string(hash).c_str()); if (certainty == Certainty::inconclusive) printer.PushAttribute("inconclusive", "true"); if (!file0.empty()) printer.PushAttribute("file0", file0.c_str()); if (!remark.empty()) printer.PushAttribute("remark", fixInvalidChars(remark).c_str()); for (std::list<FileLocation>::const_reverse_iterator it = callStack.crbegin(); it != callStack.crend(); ++it) { printer.OpenElement("location", false); printer.PushAttribute("file", it->getfile().c_str()); printer.PushAttribute("line", std::max(it->line,0)); printer.PushAttribute("column", it->column); if (!it->getinfo().empty()) printer.PushAttribute("info", fixInvalidChars(it->getinfo()).c_str()); printer.CloseElement(false); } for (std::string::size_type pos = 0; pos < mSymbolNames.size();) { const std::string::size_type pos2 = mSymbolNames.find('\n', pos); std::string symbolName; if (pos2 == std::string::npos) { symbolName = mSymbolNames.substr(pos); pos = pos2; } else { symbolName = mSymbolNames.substr(pos, pos2-pos); pos = pos2 + 1; } printer.OpenElement("symbol", false); printer.PushText(symbolName.c_str()); printer.CloseElement(false); } printer.CloseElement(false); return printer.CStr(); } // TODO: read info from some shared resource instead? static std::string readCode(const std::string &file, int linenr, int column, const char endl[]) { std::ifstream fin(file); std::string line; while (linenr > 0 && std::getline(fin,line)) { linenr--; } const std::string::size_type endPos = line.find_last_not_of("\r\n\t "); if (endPos + 1 < line.size()) line.erase(endPos + 1); std::string::size_type pos = 0; while ((pos = line.find('\t', pos)) != std::string::npos) line[pos] = ' '; return line + endl + std::string((column>0 ? column-1 : 0), ' ') + '^'; } static void replaceSpecialChars(std::string& source) { // Support a few special characters to allow to specific formatting, see http://sourceforge.net/apps/phpbb/cppcheck/viewtopic.php?f=4&t=494&sid=21715d362c0dbafd3791da4d9522f814 // Substitution should be done first so messages from cppcheck never get translated. static const std::unordered_map<char, std::string> substitutionMap = { {'b', "\b"}, {'n', "\n"}, {'r', "\r"}, {'t', "\t"} }; std::string::size_type index = 0; while ((index = source.find('\\', index)) != std::string::npos) { const char searchFor = source[index+1]; const auto it = substitutionMap.find(searchFor); if (it == substitutionMap.end()) { index += 1; continue; } const std::string& replaceWith = it->second; source.replace(index, 2, replaceWith); index += replaceWith.length(); } } static void replace(std::string& source, const std::unordered_map<std::string, std::string> &substitutionMap) { std::string::size_type index = 0; while ((index = source.find('{', index)) != std::string::npos) { const std::string::size_type end = source.find('}', index); if (end == std::string::npos) break; const std::string searchFor = source.substr(index, end-index+1); const auto it = substitutionMap.find(searchFor); if (it == substitutionMap.end()) { index += 1; continue; } const std::string& replaceWith = it->second; source.replace(index, searchFor.length(), replaceWith); index += replaceWith.length(); } } static void replaceColors(std::string& source) { // TODO: colors are not applied when either stdout or stderr is not a TTY because we resolve them before the stream usage static const std::unordered_map<std::string, std::string> substitutionMap = { {"{reset}", ::toString(Color::Reset)}, {"{bold}", ::toString(Color::Bold)}, {"{dim}", ::toString(Color::Dim)}, {"{red}", ::toString(Color::FgRed)}, {"{green}", ::toString(Color::FgGreen)}, {"{blue}", ::toString(Color::FgBlue)}, {"{magenta}", ::toString(Color::FgMagenta)}, {"{default}", ::toString(Color::FgDefault)}, }; replace(source, substitutionMap); } // TODO: remove default parameters std::string ErrorMessage::toString(bool verbose, const std::string &templateFormat, const std::string &templateLocation) const { // Save this ErrorMessage in plain text. // TODO: should never happen - remove this // No template is given // (not 100%) equivalent templateFormat: {callstack} ({severity}{inconclusive:, inconclusive}) {message} if (templateFormat.empty()) { std::string text; if (!callStack.empty()) { text += ErrorLogger::callStackToString(callStack); text += ": "; } if (severity != Severity::none) { text += '('; text += severityToString(severity); if (certainty == Certainty::inconclusive) text += ", inconclusive"; text += ") "; } text += (verbose ? mVerboseMessage : mShortMessage); return text; } // template is given. Reformat the output according to it std::string result = templateFormat; findAndReplace(result, "{id}", id); std::string::size_type pos1 = result.find("{inconclusive:"); while (pos1 != std::string::npos) { const std::string::size_type pos2 = result.find('}', pos1+1); const std::string replaceFrom = result.substr(pos1,pos2-pos1+1); const std::string replaceWith = (certainty == Certainty::inconclusive) ? result.substr(pos1+14, pos2-pos1-14) : std::string(); findAndReplace(result, replaceFrom, replaceWith); pos1 = result.find("{inconclusive:", pos1); } findAndReplace(result, "{severity}", severityToString(severity)); findAndReplace(result, "{cwe}", std::to_string(cwe.id)); findAndReplace(result, "{message}", verbose ? mVerboseMessage : mShortMessage); findAndReplace(result, "{remark}", remark); if (!callStack.empty()) { if (result.find("{callstack}") != std::string::npos) findAndReplace(result, "{callstack}", ErrorLogger::callStackToString(callStack)); findAndReplace(result, "{file}", callStack.back().getfile()); findAndReplace(result, "{line}", std::to_string(callStack.back().line)); findAndReplace(result, "{column}", std::to_string(callStack.back().column)); if (result.find("{code}") != std::string::npos) { const std::string::size_type pos = result.find('\r'); const char *endl; if (pos == std::string::npos) endl = "\n"; else if (pos+1 < result.size() && result[pos+1] == '\n') endl = "\r\n"; else endl = "\r"; findAndReplace(result, "{code}", readCode(callStack.back().getOrigFile(), callStack.back().line, callStack.back().column, endl)); } } else { static const std::unordered_map<std::string, std::string> callStackSubstitutionMap = { {"{callstack}", ""}, {"{file}", "nofile"}, {"{line}", "0"}, {"{column}", "0"}, {"{code}", ""} }; replace(result, callStackSubstitutionMap); } if (!templateLocation.empty() && callStack.size() >= 2U) { for (const FileLocation &fileLocation : callStack) { std::string text = templateLocation; findAndReplace(text, "{file}", fileLocation.getfile()); findAndReplace(text, "{line}", std::to_string(fileLocation.line)); findAndReplace(text, "{column}", std::to_string(fileLocation.column)); findAndReplace(text, "{info}", fileLocation.getinfo().empty() ? mShortMessage : fileLocation.getinfo()); if (text.find("{code}") != std::string::npos) { const std::string::size_type pos = text.find('\r'); const char *endl; if (pos == std::string::npos) endl = "\n"; else if (pos+1 < text.size() && text[pos+1] == '\n') endl = "\r\n"; else endl = "\r"; findAndReplace(text, "{code}", readCode(fileLocation.getOrigFile(), fileLocation.line, fileLocation.column, endl)); } result += '\n' + text; } } return result; } std::string ErrorLogger::callStackToString(const std::list<ErrorMessage::FileLocation> &callStack) { std::string str; for (std::list<ErrorMessage::FileLocation>::const_iterator tok = callStack.cbegin(); tok != callStack.cend(); ++tok) { str += (tok == callStack.cbegin() ? "" : " -> "); str += tok->stringify(); } return str; } ErrorMessage::FileLocation::FileLocation(const Token* tok, const TokenList* tokenList) : fileIndex(tok->fileIndex()), line(tok->linenr()), column(tok->column()), mOrigFileName(tokenList->getOrigFile(tok)), mFileName(tokenList->file(tok)) {} ErrorMessage::FileLocation::FileLocation(const Token* tok, std::string info, const TokenList* tokenList) : fileIndex(tok->fileIndex()), line(tok->linenr()), column(tok->column()), mOrigFileName(tokenList->getOrigFile(tok)), mFileName(tokenList->file(tok)), mInfo(std::move(info)) {} std::string ErrorMessage::FileLocation::getfile(bool convert) const { if (convert) return Path::toNativeSeparators(mFileName); return mFileName; } std::string ErrorMessage::FileLocation::getOrigFile(bool convert) const { if (convert) return Path::toNativeSeparators(mOrigFileName); return mOrigFileName; } void ErrorMessage::FileLocation::setfile(std::string file) { mFileName = Path::simplifyPath(std::move(file)); } std::string ErrorMessage::FileLocation::stringify() const { std::string str; str += '['; str += Path::toNativeSeparators(mFileName); if (line != SuppressionList::Suppression::NO_LINE) { str += ':'; str += std::to_string(line); } str += ']'; return str; } std::string ErrorLogger::toxml(const std::string &str) { std::string xml; for (const unsigned char c : str) { switch (c) { case '<': xml += "&lt;"; break; case '>': xml += "&gt;"; break; case '&': xml += "&amp;"; break; case '\"': xml += "&quot;"; break; case '\'': xml += "&apos;"; break; case '\0': xml += "\\0"; break; default: if (c >= ' ' && c <= 0x7f) xml += c; else xml += 'x'; break; } } return xml; } std::string ErrorLogger::plistHeader(const std::string &version, const std::vector<std::string> &files) { std::ostringstream ostr; ostr << "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n" << "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\r\n" << "<plist version=\"1.0\">\r\n" << "<dict>\r\n" << " <key>clang_version</key>\r\n" << "<string>cppcheck version " << version << "</string>\r\n" << " <key>files</key>\r\n" << " <array>\r\n"; for (const std::string & file : files) ostr << " <string>" << ErrorLogger::toxml(file) << "</string>\r\n"; ostr << " </array>\r\n" << " <key>diagnostics</key>\r\n" << " <array>\r\n"; return ostr.str(); } static std::string plistLoc(const char indent[], const ErrorMessage::FileLocation &loc) { std::ostringstream ostr; ostr << indent << "<dict>\r\n" << indent << ' ' << "<key>line</key><integer>" << loc.line << "</integer>\r\n" << indent << ' ' << "<key>col</key><integer>" << loc.column << "</integer>\r\n" << indent << ' ' << "<key>file</key><integer>" << loc.fileIndex << "</integer>\r\n" << indent << "</dict>\r\n"; return ostr.str(); } std::string ErrorLogger::plistData(const ErrorMessage &msg) { std::ostringstream plist; plist << " <dict>\r\n" << " <key>path</key>\r\n" << " <array>\r\n"; std::list<ErrorMessage::FileLocation>::const_iterator prev = msg.callStack.cbegin(); for (std::list<ErrorMessage::FileLocation>::const_iterator it = msg.callStack.cbegin(); it != msg.callStack.cend(); ++it) { if (prev != it) { plist << " <dict>\r\n" << " <key>kind</key><string>control</string>\r\n" << " <key>edges</key>\r\n" << " <array>\r\n" << " <dict>\r\n" << " <key>start</key>\r\n" << " <array>\r\n" << plistLoc(" ", *prev) << plistLoc(" ", *prev) << " </array>\r\n" << " <key>end</key>\r\n" << " <array>\r\n" << plistLoc(" ", *it) << plistLoc(" ", *it) << " </array>\r\n" << " </dict>\r\n" << " </array>\r\n" << " </dict>\r\n"; prev = it; } std::list<ErrorMessage::FileLocation>::const_iterator next = it; ++next; const std::string message = (it->getinfo().empty() && next == msg.callStack.cend() ? msg.shortMessage() : it->getinfo()); plist << " <dict>\r\n" << " <key>kind</key><string>event</string>\r\n" << " <key>location</key>\r\n" << plistLoc(" ", *it) << " <key>ranges</key>\r\n" << " <array>\r\n" << " <array>\r\n" << plistLoc(" ", *it) << plistLoc(" ", *it) << " </array>\r\n" << " </array>\r\n" << " <key>depth</key><integer>0</integer>\r\n" << " <key>extended_message</key>\r\n" << " <string>" << ErrorLogger::toxml(message) << "</string>\r\n" << " <key>message</key>\r\n" << " <string>" << ErrorLogger::toxml(message) << "</string>\r\n" << " </dict>\r\n"; } plist << " </array>\r\n" << " <key>description</key><string>" << ErrorLogger::toxml(msg.shortMessage()) << "</string>\r\n" << " <key>category</key><string>" << severityToString(msg.severity) << "</string>\r\n" << " <key>type</key><string>" << ErrorLogger::toxml(msg.shortMessage()) << "</string>\r\n" << " <key>check_name</key><string>" << msg.id << "</string>\r\n" << " <!-- This hash is experimental and going to change! -->\r\n" << " <key>issue_hash_content_of_line_in_context</key><string>" << 0 << "</string>\r\n" << " <key>issue_context_kind</key><string></string>\r\n" << " <key>issue_context</key><string></string>\r\n" << " <key>issue_hash_function_offset</key><string></string>\r\n" << " <key>location</key>\r\n" << plistLoc(" ", msg.callStack.back()) << " </dict>\r\n"; return plist.str(); } std::string replaceStr(std::string s, const std::string &from, const std::string &to) { std::string::size_type pos1 = 0; while (pos1 < s.size()) { pos1 = s.find(from, pos1); if (pos1 == std::string::npos) return s; if (pos1 > 0 && (s[pos1-1] == '_' || std::isalnum(s[pos1-1]))) { pos1++; continue; } const std::string::size_type pos2 = pos1 + from.size(); if (pos2 >= s.size()) return s.substr(0,pos1) + to; if (s[pos2] == '_' || std::isalnum(s[pos2])) { pos1++; continue; } s.replace(pos1, from.size(), to); pos1 += to.size(); } return s; } void substituteTemplateFormatStatic(std::string& templateFormat) { replaceSpecialChars(templateFormat); replaceColors(templateFormat); } void substituteTemplateLocationStatic(std::string& templateLocation) { replaceSpecialChars(templateLocation); replaceColors(templateLocation); }
34,532
C++
.cpp
807
35.221809
187
0.596918
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,177
vf_bailout.cpp
danmar_cppcheck/lib/vf_bailout.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_bailout.h" #include "errorlogger.h" #include "errortypes.h" #include "path.h" #include "tokenlist.h" #include <utility> namespace ValueFlow { void bailoutInternal(const std::string& type, const TokenList &tokenlist, ErrorLogger &errorLogger, const Token *tok, const std::string &what, const std::string &file, int line, std::string function) { if (function.find("operator") != std::string::npos) function = "(valueFlow)"; ErrorMessage::FileLocation loc(tok, &tokenlist); const std::string location = Path::stripDirectoryPart(file) + ":" + std::to_string(line) + ":"; ErrorMessage errmsg({std::move(loc)}, tokenlist.getSourceFilePath(), Severity::debug, (file.empty() ? "" : location) + function + " bailout: " + what, type, Certainty::normal); errorLogger.reportErr(errmsg); } }
1,638
C++
.cpp
36
41.388889
203
0.703379
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,178
vf_symbolicinfer.cpp
danmar_cppcheck/lib/vf_symbolicinfer.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_symbolicinfer.h" #include "astutils.h" #include "infer.h" #include "mathlib.h" #include "symboldatabase.h" #include "token.h" #include "valueptr.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <cassert> #include <utility> #include <vector> namespace ValueFlow { struct SymbolicInferModel : InferModel { const Token* expr; explicit SymbolicInferModel(const Token* tok) : expr(tok) { assert(expr->exprId() != 0); } bool match(const Value& value) const override { return value.isSymbolicValue() && value.tokvalue && value.tokvalue->exprId() == expr->exprId(); } Value yield(MathLib::bigint value) const override { Value result(value); result.valueType = Value::ValueType::SYMBOLIC; result.tokvalue = expr; result.setKnown(); return result; } }; void valueFlowSymbolicInfer(const SymbolDatabase& symboldatabase, const Settings& settings) { for (const Scope* scope : symboldatabase.functionScopes) { for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "-|%comp%")) continue; if (tok->hasKnownIntValue()) continue; if (!tok->astOperand1()) continue; if (!tok->astOperand2()) continue; if (tok->astOperand1()->exprId() == 0) continue; if (tok->astOperand2()->exprId() == 0) continue; if (tok->astOperand1()->hasKnownIntValue()) continue; if (tok->astOperand2()->hasKnownIntValue()) continue; if (astIsFloat(tok->astOperand1(), false)) continue; if (astIsFloat(tok->astOperand2(), false)) continue; SymbolicInferModel leftModel{tok->astOperand1()}; std::vector<Value> values = infer(leftModel, tok->str(), 0, tok->astOperand2()->values()); if (values.empty()) { SymbolicInferModel rightModel{tok->astOperand2()}; values = infer(rightModel, tok->str(), tok->astOperand1()->values(), 0); } for (Value& value : values) { setTokenValue(tok, std::move(value), settings); } } } } }
3,355
C++
.cpp
86
29.232558
110
0.580625
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,179
vf_symbolicoperators.cpp
danmar_cppcheck/lib/vf_symbolicoperators.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_symbolicoperators.h" #include "astutils.h" #include "config.h" #include "infer.h" #include "symboldatabase.h" #include "token.h" #include "vfvalue.h" #include "vf_common.h" #include "vf_settokenvalue.h" #include <algorithm> #include <iterator> #include <list> #include <string> #include <unordered_set> #include <utility> #include <vector> namespace ValueFlow { static const Token* isStrlenOf(const Token* tok, const Token* expr, int depth = 10) { if (depth < 0) return nullptr; if (!tok) return nullptr; if (!expr) return nullptr; if (expr->exprId() == 0) return nullptr; if (Token::simpleMatch(tok->previous(), "strlen (")) { if (tok->astOperand2()->exprId() == expr->exprId()) return tok; } else { for (const Value& v : tok->values()) { if (!v.isSymbolicValue()) continue; if (!v.isKnown()) continue; if (v.intvalue != 0) continue; if (const Token* next = isStrlenOf(v.tokvalue, expr, depth - 1)) return next; } } return nullptr; } void analyzeSymbolicOperators(const SymbolDatabase& symboldatabase, const Settings& settings) { for (const Scope* scope : symboldatabase.functionScopes) { for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { if (tok->hasKnownIntValue()) continue; if (Token::Match(tok, "abs|labs|llabs|fabs|fabsf|fabsl (")) { const Token* arg = tok->next()->astOperand2(); if (!arg) continue; if (arg->exprId() == 0) continue; Value c = inferCondition(">=", arg, 0); if (!c.isKnown()) continue; Value v = makeSymbolic(arg); v.errorPath = c.errorPath; v.errorPath.emplace_back(tok, "Passed to " + tok->str()); if (c.intvalue == 0) v.setImpossible(); else v.setKnown(); setTokenValue(tok->next(), std::move(v), settings); } else if (Token::Match(tok, "*|/|<<|>>|^|+|-|%or%")) { if (!tok->astOperand1()) continue; if (!tok->astOperand2()) continue; if (!astIsIntegral(tok->astOperand1(), false) && !astIsIntegral(tok->astOperand2(), false)) continue; const Value* constant = nullptr; const Token* vartok = nullptr; if (tok->astOperand1()->hasKnownIntValue()) { constant = &tok->astOperand1()->values().front(); vartok = tok->astOperand2(); } if (tok->astOperand2()->hasKnownIntValue()) { constant = &tok->astOperand2()->values().front(); vartok = tok->astOperand1(); } if (!constant) continue; if (!vartok) continue; if (vartok->exprId() == 0) continue; if (Token::Match(tok, "<<|>>|/") && !astIsLHS(vartok)) continue; if (Token::Match(tok, "<<|>>|^|+|-|%or%") && constant->intvalue != 0) continue; if (Token::Match(tok, "*|/") && constant->intvalue != 1) continue; std::vector<Value> values = {makeSymbolic(vartok)}; std::unordered_set<nonneg int> ids = {vartok->exprId()}; std::copy_if(vartok->values().cbegin(), vartok->values().cend(), std::back_inserter(values), [&](const Value& v) { if (!v.isSymbolicValue()) return false; if (!v.tokvalue) return false; return ids.insert(v.tokvalue->exprId()).second; }); for (Value& v : values) setTokenValue(tok, std::move(v), settings); } else if (Token::simpleMatch(tok, "[")) { const Token* arrayTok = tok->astOperand1(); const Token* indexTok = tok->astOperand2(); if (!arrayTok) continue; if (!indexTok) continue; for (const Value& value : indexTok->values()) { if (!value.isSymbolicValue()) continue; if (value.intvalue != 0) continue; const Token* strlenTok = isStrlenOf(value.tokvalue, arrayTok); if (!strlenTok) continue; Value v = value; v.bound = Value::Bound::Point; v.valueType = Value::ValueType::INT; v.errorPath.emplace_back(strlenTok, "Return index of first '\\0' character in string"); setTokenValue(tok, std::move(v), settings); } } } } } }
6,578
C++
.cpp
154
26.993506
111
0.46649
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,180
cppcheck.cpp
danmar_cppcheck/lib/cppcheck.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "cppcheck.h" #include "addoninfo.h" #include "check.h" #include "checkunusedfunctions.h" #include "clangimport.h" #include "color.h" #include "ctu.h" #include "errortypes.h" #include "filesettings.h" #include "library.h" #include "path.h" #include "platform.h" #include "preprocessor.h" #include "standards.h" #include "suppressions.h" #include "timer.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include "utils.h" #include "valueflow.h" #include "version.h" #include <algorithm> #include <cassert> #include <cstdio> #include <cstdint> #include <cstring> #include <cctype> #include <cstdlib> #include <ctime> #include <exception> // IWYU pragma: keep #include <fstream> #include <iostream> #include <new> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "json.h" #include <simplecpp.h> #include "xml.h" #ifdef HAVE_RULES #ifdef _WIN32 #define PCRE_STATIC #endif #include <pcre.h> #endif class SymbolDatabase; static constexpr char Version[] = CPPCHECK_VERSION_STRING; static constexpr char ExtraVersion[] = ""; static constexpr char FILELIST[] = "cppcheck-addon-ctu-file-list"; static TimerResults s_timerResults; // CWE ids used static const CWE CWE398(398U); // Indicator of Poor Code Quality // File deleter namespace { class FilesDeleter { public: FilesDeleter() = default; ~FilesDeleter() { for (const std::string& fileName: mFilenames) std::remove(fileName.c_str()); } void addFile(const std::string& fileName) { mFilenames.push_back(fileName); } private: std::vector<std::string> mFilenames; }; } static std::string cmdFileName(std::string f) { f = Path::toNativeSeparators(std::move(f)); if (f.find(' ') != std::string::npos) return "\"" + f + "\""; return f; } static std::vector<std::string> split(const std::string &str, const std::string &sep=" ") { std::vector<std::string> ret; for (std::string::size_type startPos = 0U; startPos < str.size();) { startPos = str.find_first_not_of(sep, startPos); if (startPos == std::string::npos) break; if (str[startPos] == '\"') { const std::string::size_type endPos = str.find('\"', startPos + 1); ret.push_back(str.substr(startPos + 1, endPos - startPos - 1)); startPos = (endPos < str.size()) ? (endPos + 1) : endPos; continue; } const std::string::size_type endPos = str.find(sep, startPos + 1); ret.push_back(str.substr(startPos, endPos - startPos)); startPos = endPos; } return ret; } static std::string getDumpFileName(const Settings& settings, const std::string& filename) { if (!settings.dumpFile.empty()) return settings.dumpFile; std::string extension; if (settings.dump || !settings.buildDir.empty()) extension = ".dump"; else extension = "." + std::to_string(settings.pid) + ".dump"; if (!settings.dump && !settings.buildDir.empty()) return AnalyzerInformation::getAnalyzerInfoFile(settings.buildDir, filename, emptyString) + extension; return filename + extension; } static std::string getCtuInfoFileName(const std::string &dumpFile) { return dumpFile.substr(0, dumpFile.size()-4) + "ctu-info"; } static void createDumpFile(const Settings& settings, const FileWithDetails& file, std::ofstream& fdump, std::string& dumpFile) { if (!settings.dump && settings.addons.empty()) return; dumpFile = getDumpFileName(settings, file.spath()); fdump.open(dumpFile); if (!fdump.is_open()) return; if (!settings.buildDir.empty()) { std::ofstream fout(getCtuInfoFileName(dumpFile)); } // TODO: enforcedLang should be already applied in FileWithDetails object std::string language; switch (settings.enforcedLang) { case Standards::Language::C: language = " language=\"c\""; break; case Standards::Language::CPP: language = " language=\"cpp\""; break; case Standards::Language::None: { // TODO: get language from FileWithDetails object // TODO: error out on unknown language? const Standards::Language lang = Path::identify(file.spath(), settings.cppHeaderProbe); if (lang == Standards::Language::CPP) language = " language=\"cpp\""; else if (lang == Standards::Language::C) language = " language=\"c\""; break; } } fdump << "<?xml version=\"1.0\"?>\n"; fdump << "<dumps" << language << ">\n"; fdump << " <platform" << " name=\"" << settings.platform.toString() << '\"' << " char_bit=\"" << settings.platform.char_bit << '\"' << " short_bit=\"" << settings.platform.short_bit << '\"' << " int_bit=\"" << settings.platform.int_bit << '\"' << " long_bit=\"" << settings.platform.long_bit << '\"' << " long_long_bit=\"" << settings.platform.long_long_bit << '\"' << " pointer_bit=\"" << (settings.platform.sizeof_pointer * settings.platform.char_bit) << '\"' << " wchar_t_bit=\"" << (settings.platform.sizeof_wchar_t * settings.platform.char_bit) << '\"' << " size_t_bit=\"" << (settings.platform.sizeof_size_t * settings.platform.char_bit) << '\"' << "/>" << '\n'; } static std::string detectPython(const CppCheck::ExecuteCmdFn &executeCommand) { #ifdef _WIN32 const char *py_exes[] = { "python3.exe", "python.exe" }; #else const char *py_exes[] = { "python3", "python" }; #endif for (const char* py_exe : py_exes) { std::string out; #ifdef _MSC_VER // FIXME: hack to avoid debug assertion with _popen() in executeCommand() for non-existing commands const std::string cmd = std::string(py_exe) + " --version >NUL 2>&1"; if (system(cmd.c_str()) != 0) { // TODO: get more detailed error? continue; } #endif if (executeCommand(py_exe, split("--version"), "2>&1", out) == EXIT_SUCCESS && startsWith(out, "Python ") && std::isdigit(out[7])) { return py_exe; } } return ""; } static std::vector<picojson::value> executeAddon(const AddonInfo &addonInfo, const std::string &defaultPythonExe, const std::string &file, const std::string &premiumArgs, const CppCheck::ExecuteCmdFn &executeCommand) { const std::string redirect = "2>&1"; std::string pythonExe; if (!addonInfo.executable.empty()) pythonExe = addonInfo.executable; else if (!addonInfo.python.empty()) pythonExe = cmdFileName(addonInfo.python); else if (!defaultPythonExe.empty()) pythonExe = cmdFileName(defaultPythonExe); else { // store in static variable so we only look this up once static const std::string detectedPythonExe = detectPython(executeCommand); if (detectedPythonExe.empty()) throw InternalError(nullptr, "Failed to auto detect python"); pythonExe = detectedPythonExe; } std::string args; if (addonInfo.executable.empty()) args = cmdFileName(addonInfo.runScript) + " " + cmdFileName(addonInfo.scriptFile); args += std::string(args.empty() ? "" : " ") + "--cli" + addonInfo.args; if (!premiumArgs.empty() && !addonInfo.executable.empty()) args += " " + premiumArgs; const bool is_file_list = (file.find(FILELIST) != std::string::npos); const std::string fileArg = (is_file_list ? " --file-list " : " ") + cmdFileName(file); args += fileArg; std::string result; if (const int exitcode = executeCommand(pythonExe, split(args), redirect, result)) { std::string message("Failed to execute addon '" + addonInfo.name + "' - exitcode is " + std::to_string(exitcode)); std::string details = pythonExe + " " + args; if (result.size() > 2) { details += "\nOutput:\n"; details += result; const auto pos = details.find_last_not_of("\n\r"); if (pos != std::string::npos) details.resize(pos + 1); } throw InternalError(nullptr, std::move(message), std::move(details)); } std::vector<picojson::value> addonResult; // Validate output.. std::istringstream istr(result); std::string line; while (std::getline(istr, line)) { // TODO: also bail out? if (line.empty()) { //std::cout << "addon '" << addonInfo.name << "' result contains empty line" << std::endl; continue; } // TODO: get rid of this if (startsWith(line,"Checking ")) { //std::cout << "addon '" << addonInfo.name << "' result contains 'Checking ' line" << std::endl; continue; } if (line[0] != '{') { //std::cout << "addon '" << addonInfo.name << "' result is not a JSON" << std::endl; result.erase(result.find_last_not_of('\n') + 1, std::string::npos); // Remove trailing newlines throw InternalError(nullptr, "Failed to execute '" + pythonExe + " " + args + "'. " + result); } //std::cout << "addon '" << addonInfo.name << "' result is " << line << std::endl; // TODO: make these failures? picojson::value res; const std::string err = picojson::parse(res, line); if (!err.empty()) { //std::cout << "addon '" << addonInfo.name << "' result is not a valid JSON (" << err << ")" << std::endl; continue; } if (!res.is<picojson::object>()) { //std::cout << "addon '" << addonInfo.name << "' result is not a JSON object" << std::endl; continue; } addonResult.emplace_back(std::move(res)); } // Valid results return addonResult; } static std::string getDefinesFlags(const std::string &semicolonSeparatedString) { std::string flags; for (const std::string &d: split(semicolonSeparatedString, ";")) flags += "-D" + d + " "; return flags; } CppCheck::CppCheck(ErrorLogger &errorLogger, bool useGlobalSuppressions, ExecuteCmdFn executeCommand) : mErrorLogger(errorLogger) , mUseGlobalSuppressions(useGlobalSuppressions) , mExecuteCommand(std::move(executeCommand)) {} CppCheck::~CppCheck() { while (!mFileInfo.empty()) { delete mFileInfo.back(); mFileInfo.pop_back(); } if (mPlistFile.is_open()) { mPlistFile << ErrorLogger::plistFooter(); mPlistFile.close(); } } const char * CppCheck::version() { return Version; } const char * CppCheck::extraVersion() { return ExtraVersion; } static bool reportClangErrors(std::istream &is, const std::function<void(const ErrorMessage&)>& reportErr, std::vector<ErrorMessage> &warnings) { std::string line; while (std::getline(is, line)) { if (line.empty() || line[0] == ' ' || line[0] == '`' || line[0] == '-') continue; std::string::size_type pos3 = line.find(": error: "); if (pos3 == std::string::npos) pos3 = line.find(": fatal error:"); if (pos3 == std::string::npos) pos3 = line.find(": warning:"); if (pos3 == std::string::npos) continue; // file:line:column: error: .... const std::string::size_type pos2 = line.rfind(':', pos3 - 1); const std::string::size_type pos1 = line.rfind(':', pos2 - 1); if (pos1 >= pos2 || pos2 >= pos3) continue; const std::string filename = line.substr(0, pos1); const std::string linenr = line.substr(pos1+1, pos2-pos1-1); const std::string colnr = line.substr(pos2+1, pos3-pos2-1); const std::string msg = line.substr(line.find(':', pos3+1) + 2); const std::string locFile = Path::toNativeSeparators(filename); const int line_i = strToInt<int>(linenr); const int column = strToInt<unsigned int>(colnr); ErrorMessage::FileLocation loc(locFile, line_i, column); ErrorMessage errmsg({std::move(loc)}, locFile, Severity::error, msg, "syntaxError", Certainty::normal); if (line.compare(pos3, 10, ": warning:") == 0) { warnings.push_back(std::move(errmsg)); continue; } reportErr(errmsg); return true; } return false; } std::string CppCheck::getLibraryDumpData() const { std::string out; for (const std::string &s : mSettings.libraries) { out += " <library lib=\"" + s + "\"/>\n"; } return out; } unsigned int CppCheck::checkClang(const FileWithDetails &file) { if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mUnusedFunctionsCheck) mUnusedFunctionsCheck.reset(new CheckUnusedFunctions()); if (!mSettings.quiet) mErrorLogger.reportOut(std::string("Checking ") + file.spath() + " ...", Color::FgGreen); // TODO: get language from FileWithDetails object bool isCpp; if (mSettings.enforcedLang != Standards::None) isCpp = (mSettings.enforcedLang == Standards::CPP); else isCpp = Path::identify(file.spath(), mSettings.cppHeaderProbe) == Standards::Language::CPP; const std::string langOpt = isCpp ? "-x c++" : "-x c"; const std::string analyzerInfo = mSettings.buildDir.empty() ? std::string() : AnalyzerInformation::getAnalyzerInfoFile(mSettings.buildDir, file.spath(), emptyString); const std::string clangcmd = analyzerInfo + ".clang-cmd"; const std::string clangStderr = analyzerInfo + ".clang-stderr"; const std::string clangAst = analyzerInfo + ".clang-ast"; std::string exe = mSettings.clangExecutable; #ifdef _WIN32 // append .exe if it is not a path if (Path::fromNativeSeparators(mSettings.clangExecutable).find('/') == std::string::npos) { exe += ".exe"; } #endif std::string flags(langOpt + " "); if (isCpp && !mSettings.standards.stdValueCPP.empty()) flags += "-std=" + mSettings.standards.stdValueCPP + " "; if (!isCpp && !mSettings.standards.stdValueC.empty()) flags += "-std=" + mSettings.standards.stdValueC + " "; for (const std::string &i: mSettings.includePaths) flags += "-I" + i + " "; flags += getDefinesFlags(mSettings.userDefines); const std::string args2 = "-fsyntax-only -Xclang -ast-dump -fno-color-diagnostics " + flags + file.spath(); const std::string redirect2 = analyzerInfo.empty() ? std::string("2>&1") : ("2> " + clangStderr); if (!mSettings.buildDir.empty()) { std::ofstream fout(clangcmd); fout << exe << " " << args2 << " " << redirect2 << std::endl; } if (mSettings.verbose && !mSettings.quiet) { mErrorLogger.reportOut(exe + " " + args2); } std::string output2; const int exitcode = mExecuteCommand(exe,split(args2),redirect2,output2); if (exitcode != EXIT_SUCCESS) { // TODO: report as proper error std::cerr << "Failed to execute '" << exe << " " << args2 << " " << redirect2 << "' - (exitcode: " << exitcode << " / output: " << output2 << ")" << std::endl; return 0; // TODO: report as failure? } if (output2.find("TranslationUnitDecl") == std::string::npos) { // TODO: report as proper error std::cerr << "Failed to execute '" << exe << " " << args2 << " " << redirect2 << "' - (no TranslationUnitDecl in output)" << std::endl; return 0; // TODO: report as failure? } // Ensure there are not syntax errors... std::vector<ErrorMessage> compilerWarnings; if (!mSettings.buildDir.empty()) { std::ifstream fin(clangStderr); auto reportError = [this](const ErrorMessage& errorMessage) { reportErr(errorMessage); }; if (reportClangErrors(fin, reportError, compilerWarnings)) return 0; } else { std::istringstream istr(output2); auto reportError = [this](const ErrorMessage& errorMessage) { reportErr(errorMessage); }; if (reportClangErrors(istr, reportError, compilerWarnings)) return 0; } if (!mSettings.buildDir.empty()) { std::ofstream fout(clangAst); fout << output2 << std::endl; } try { Tokenizer tokenizer(mSettings, *this); tokenizer.list.appendFileIfNew(file.spath()); std::istringstream ast(output2); clangimport::parseClangAstDump(tokenizer, ast); ValueFlow::setValues(tokenizer.list, const_cast<SymbolDatabase&>(*tokenizer.getSymbolDatabase()), *this, mSettings, &s_timerResults); if (mSettings.debugnormal) tokenizer.printDebugOutput(1, std::cout); checkNormalTokens(tokenizer); // create dumpfile std::ofstream fdump; std::string dumpFile; createDumpFile(mSettings, file, fdump, dumpFile); if (fdump.is_open()) { // TODO: use tinyxml2 to create XML fdump << "<dump cfg=\"\">\n"; for (const ErrorMessage& errmsg: compilerWarnings) fdump << " <clang-warning file=\"" << toxml(errmsg.callStack.front().getfile()) << "\" line=\"" << errmsg.callStack.front().line << "\" column=\"" << errmsg.callStack.front().column << "\" message=\"" << toxml(errmsg.shortMessage()) << "\"/>\n"; fdump << " <standards>\n"; fdump << " <c version=\"" << mSettings.standards.getC() << "\"/>\n"; fdump << " <cpp version=\"" << mSettings.standards.getCPP() << "\"/>\n"; fdump << " </standards>\n"; fdump << getLibraryDumpData(); tokenizer.dump(fdump); fdump << "</dump>\n"; fdump << "</dumps>\n"; fdump.close(); } // run addons executeAddons(dumpFile, file); } catch (const InternalError &e) { const ErrorMessage errmsg = ErrorMessage::fromInternalError(e, nullptr, file.spath(), "Bailing out from analysis: Processing Clang AST dump failed"); reportErr(errmsg); } catch (const TerminateException &) { // Analysis is terminated return mExitCode; } catch (const std::exception &e) { internalError(file.spath(), std::string("Processing Clang AST dump failed: ") + e.what()); } return mExitCode; } unsigned int CppCheck::check(const FileWithDetails &file) { if (mSettings.clang) return checkClang(file); return checkFile(file, emptyString); } unsigned int CppCheck::check(const FileWithDetails &file, const std::string &content) { std::istringstream iss(content); return checkFile(file, emptyString, &iss); } unsigned int CppCheck::check(const FileSettings &fs) { // TODO: move to constructor when CppCheck no longer owns the settings if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mUnusedFunctionsCheck) mUnusedFunctionsCheck.reset(new CheckUnusedFunctions()); CppCheck temp(mErrorLogger, mUseGlobalSuppressions, mExecuteCommand); temp.mSettings = mSettings; if (!temp.mSettings.userDefines.empty()) temp.mSettings.userDefines += ';'; if (mSettings.clang) temp.mSettings.userDefines += fs.defines; else temp.mSettings.userDefines += fs.cppcheckDefines(); temp.mSettings.includePaths = fs.includePaths; temp.mSettings.userUndefs.insert(fs.undefs.cbegin(), fs.undefs.cend()); if (fs.standard.find("++") != std::string::npos) temp.mSettings.standards.setCPP(fs.standard); else if (!fs.standard.empty()) temp.mSettings.standards.setC(fs.standard); if (fs.platformType != Platform::Type::Unspecified) temp.mSettings.platform.set(fs.platformType); if (mSettings.clang) { temp.mSettings.includePaths.insert(temp.mSettings.includePaths.end(), fs.systemIncludePaths.cbegin(), fs.systemIncludePaths.cend()); // TODO: propagate back suppressions // TODO: propagate back mFileInfo const unsigned int returnValue = temp.check(fs.file); if (mUnusedFunctionsCheck) mUnusedFunctionsCheck->updateFunctionData(*temp.mUnusedFunctionsCheck); return returnValue; } const unsigned int returnValue = temp.checkFile(fs.file, fs.cfg); mSettings.supprs.nomsg.addSuppressions(temp.mSettings.supprs.nomsg.getSuppressions()); if (mUnusedFunctionsCheck) mUnusedFunctionsCheck->updateFunctionData(*temp.mUnusedFunctionsCheck); while (!temp.mFileInfo.empty()) { mFileInfo.push_back(temp.mFileInfo.back()); temp.mFileInfo.pop_back(); } // TODO: propagate back more data? return returnValue; } static simplecpp::TokenList createTokenList(const std::string& filename, std::vector<std::string>& files, simplecpp::OutputList* outputList, std::istream* fileStream) { if (fileStream) return {*fileStream, files, filename, outputList}; return {filename, files, outputList}; } unsigned int CppCheck::checkFile(const FileWithDetails& file, const std::string &cfgname, std::istream* fileStream) { // TODO: move to constructor when CppCheck no longer owns the settings if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mUnusedFunctionsCheck) mUnusedFunctionsCheck.reset(new CheckUnusedFunctions()); mExitCode = 0; if (Settings::terminated()) return mExitCode; const Timer fileTotalTimer(mSettings.showtime == SHOWTIME_MODES::SHOWTIME_FILE_TOTAL, file.spath()); if (!mSettings.quiet) { std::string fixedpath = Path::toNativeSeparators(file.spath()); mErrorLogger.reportOut(std::string("Checking ") + fixedpath + ' ' + cfgname + std::string("..."), Color::FgGreen); if (mSettings.verbose) { mErrorLogger.reportOut("Defines:" + mSettings.userDefines); std::string undefs; for (const std::string& U : mSettings.userUndefs) { if (!undefs.empty()) undefs += ';'; undefs += ' ' + U; } mErrorLogger.reportOut("Undefines:" + undefs); std::string includePaths; for (const std::string &I : mSettings.includePaths) includePaths += " -I" + I; mErrorLogger.reportOut("Includes:" + includePaths); mErrorLogger.reportOut(std::string("Platform:") + mSettings.platform.toString()); } } if (mPlistFile.is_open()) { mPlistFile << ErrorLogger::plistFooter(); mPlistFile.close(); } try { if (mSettings.library.markupFile(file.spath())) { if (mUnusedFunctionsCheck && (mSettings.useSingleJob() || !mSettings.buildDir.empty())) { // this is not a real source file - we just want to tokenize it. treat it as C anyways as the language needs to be determined. Tokenizer tokenizer(mSettings, *this); // enforce the language since markup files are special and do not adhere to the enforced language tokenizer.list.setLang(Standards::Language::C, true); if (fileStream) { tokenizer.list.createTokens(*fileStream, file.spath()); } else { std::ifstream in(file.spath()); tokenizer.list.createTokens(in, file.spath()); } mUnusedFunctionsCheck->parseTokens(tokenizer, mSettings); // TODO: set analyzer information } return EXIT_SUCCESS; } simplecpp::OutputList outputList; std::vector<std::string> files; simplecpp::TokenList tokens1 = createTokenList(file.spath(), files, &outputList, fileStream); // If there is a syntax error, report it and stop const auto output_it = std::find_if(outputList.cbegin(), outputList.cend(), [](const simplecpp::Output &output){ return Preprocessor::hasErrors(output); }); if (output_it != outputList.cend()) { const simplecpp::Output &output = *output_it; std::string locfile = Path::fromNativeSeparators(output.location.file()); if (mSettings.relativePaths) locfile = Path::getRelativePath(locfile, mSettings.basePaths); ErrorMessage::FileLocation loc1(locfile, output.location.line, output.location.col); ErrorMessage errmsg({std::move(loc1)}, "", // TODO: is this correct? Severity::error, output.msg, "syntaxError", Certainty::normal); reportErr(errmsg); return mExitCode; } Preprocessor preprocessor(mSettings, *this); if (!preprocessor.loadFiles(tokens1, files)) return mExitCode; if (!mSettings.plistOutput.empty()) { std::string filename2; if (file.spath().find('/') != std::string::npos) filename2 = file.spath().substr(file.spath().rfind('/') + 1); else filename2 = file.spath(); const std::size_t fileNameHash = std::hash<std::string> {}(file.spath()); filename2 = mSettings.plistOutput + filename2.substr(0, filename2.find('.')) + "_" + std::to_string(fileNameHash) + ".plist"; mPlistFile.open(filename2); mPlistFile << ErrorLogger::plistHeader(version(), files); } std::string dumpProlog; if (mSettings.dump || !mSettings.addons.empty()) { dumpProlog += getDumpFileContentsRawTokens(files, tokens1); } // Parse comments and then remove them mRemarkComments = preprocessor.getRemarkComments(tokens1); preprocessor.inlineSuppressions(tokens1, mSettings.supprs.nomsg); if (mSettings.dump || !mSettings.addons.empty()) { std::ostringstream oss; mSettings.supprs.nomsg.dump(oss); dumpProlog += oss.str(); } preprocessor.removeComments(tokens1); if (!mSettings.buildDir.empty()) { // Get toolinfo std::ostringstream toolinfo; toolinfo << CPPCHECK_VERSION_STRING; toolinfo << (mSettings.severity.isEnabled(Severity::warning) ? 'w' : ' '); toolinfo << (mSettings.severity.isEnabled(Severity::style) ? 's' : ' '); toolinfo << (mSettings.severity.isEnabled(Severity::performance) ? 'p' : ' '); toolinfo << (mSettings.severity.isEnabled(Severity::portability) ? 'p' : ' '); toolinfo << (mSettings.severity.isEnabled(Severity::information) ? 'i' : ' '); toolinfo << mSettings.userDefines; mSettings.supprs.nomsg.dump(toolinfo); // Calculate hash so it can be compared with old hash / future hashes const std::size_t hash = preprocessor.calculateHash(tokens1, toolinfo.str()); std::list<ErrorMessage> errors; if (!mAnalyzerInformation.analyzeFile(mSettings.buildDir, file.spath(), cfgname, hash, errors)) { while (!errors.empty()) { reportErr(errors.front()); errors.pop_front(); } return mExitCode; // known results => no need to reanalyze file } } FilesDeleter filesDeleter; // write dump file xml prolog std::ofstream fdump; std::string dumpFile; createDumpFile(mSettings, file, fdump, dumpFile); if (fdump.is_open()) { fdump << dumpProlog; if (!mSettings.dump) filesDeleter.addFile(dumpFile); } // Get directives std::list<Directive> directives = preprocessor.createDirectives(tokens1); preprocessor.simplifyPragmaAsm(tokens1); Preprocessor::setPlatformInfo(tokens1, mSettings); // Get configurations.. std::set<std::string> configurations; if ((mSettings.checkAllConfigurations && mSettings.userDefines.empty()) || mSettings.force) { Timer::run("Preprocessor::getConfigs", mSettings.showtime, &s_timerResults, [&]() { configurations = preprocessor.getConfigs(tokens1); }); } else { configurations.insert(mSettings.userDefines); } if (mSettings.checkConfiguration) { for (const std::string &config : configurations) (void)preprocessor.getcode(tokens1, config, files, true); return 0; } #ifdef HAVE_RULES // Run define rules on raw code if (hasRule("define")) { std::string code; for (const Directive &dir : directives) { if (startsWith(dir.str,"#define ") || startsWith(dir.str,"#include ")) code += "#line " + std::to_string(dir.linenr) + " \"" + dir.file + "\"\n" + dir.str + '\n'; } TokenList tokenlist(&mSettings); std::istringstream istr2(code); // TODO: asserts when file has unknown extension tokenlist.createTokens(istr2, Path::identify(*files.begin(), false)); // TODO: check result? executeRules("define", tokenlist); } #endif if (!mSettings.force && configurations.size() > mSettings.maxConfigs) { if (mSettings.severity.isEnabled(Severity::information)) { tooManyConfigsError(Path::toNativeSeparators(file.spath()),configurations.size()); } else { mTooManyConfigs = true; } } std::set<unsigned long long> hashes; int checkCount = 0; bool hasValidConfig = false; std::list<std::string> configurationError; for (const std::string &currCfg : configurations) { // bail out if terminated if (Settings::terminated()) break; // Check only a few configurations (default 12), after that bail out, unless --force // was used. if (!mSettings.force && ++checkCount > mSettings.maxConfigs) break; if (!mSettings.userDefines.empty()) { mCurrentConfig = mSettings.userDefines; const std::vector<std::string> v1(split(mSettings.userDefines, ";")); for (const std::string &cfg: split(currCfg, ";")) { if (std::find(v1.cbegin(), v1.cend(), cfg) == v1.cend()) { mCurrentConfig += ";" + cfg; } } } else { mCurrentConfig = currCfg; } if (mSettings.preprocessOnly) { std::string codeWithoutCfg; Timer::run("Preprocessor::getcode", mSettings.showtime, &s_timerResults, [&]() { codeWithoutCfg = preprocessor.getcode(tokens1, mCurrentConfig, files, true); }); if (startsWith(codeWithoutCfg,"#file")) codeWithoutCfg.insert(0U, "//"); std::string::size_type pos = 0; while ((pos = codeWithoutCfg.find("\n#file",pos)) != std::string::npos) codeWithoutCfg.insert(pos+1U, "//"); pos = 0; while ((pos = codeWithoutCfg.find("\n#endfile",pos)) != std::string::npos) codeWithoutCfg.insert(pos+1U, "//"); pos = 0; while ((pos = codeWithoutCfg.find(Preprocessor::macroChar,pos)) != std::string::npos) codeWithoutCfg[pos] = ' '; reportOut(codeWithoutCfg); continue; } Tokenizer tokenizer(mSettings, *this); if (mSettings.showtime != SHOWTIME_MODES::SHOWTIME_NONE) tokenizer.setTimerResults(&s_timerResults); tokenizer.setDirectives(directives); // TODO: how to avoid repeated copies? try { // Create tokens, skip rest of iteration if failed Timer::run("Tokenizer::createTokens", mSettings.showtime, &s_timerResults, [&]() { simplecpp::TokenList tokensP = preprocessor.preprocess(tokens1, mCurrentConfig, files, true); tokenizer.list.createTokens(std::move(tokensP)); }); hasValidConfig = true; // locations macros mLocationMacros.clear(); for (const Token* tok = tokenizer.tokens(); tok; tok = tok->next()) { if (!tok->getMacroName().empty()) mLocationMacros[Location(files[tok->fileIndex()], tok->linenr())].emplace(tok->getMacroName()); } // If only errors are printed, print filename after the check if (!mSettings.quiet && (!mCurrentConfig.empty() || checkCount > 1)) { std::string fixedpath = Path::toNativeSeparators(file.spath()); mErrorLogger.reportOut("Checking " + fixedpath + ": " + mCurrentConfig + "...", Color::FgGreen); } if (!tokenizer.tokens()) continue; // skip rest of iteration if just checking configuration if (mSettings.checkConfiguration) continue; #ifdef HAVE_RULES // Execute rules for "raw" code executeRules("raw", tokenizer.list); #endif // Simplify tokens into normal form, skip rest of iteration if failed if (!tokenizer.simplifyTokens1(mCurrentConfig)) continue; // dump xml if --dump if ((mSettings.dump || !mSettings.addons.empty()) && fdump.is_open()) { fdump << "<dump cfg=\"" << ErrorLogger::toxml(mCurrentConfig) << "\">" << std::endl; fdump << " <standards>" << std::endl; fdump << " <c version=\"" << mSettings.standards.getC() << "\"/>" << std::endl; fdump << " <cpp version=\"" << mSettings.standards.getCPP() << "\"/>" << std::endl; fdump << " </standards>" << std::endl; fdump << getLibraryDumpData(); preprocessor.dump(fdump); tokenizer.dump(fdump); fdump << "</dump>" << std::endl; } // Need to call this even if the hash will skip this configuration mSettings.supprs.nomsg.markUnmatchedInlineSuppressionsAsChecked(tokenizer); // Skip if we already met the same simplified token list if (mSettings.force || mSettings.maxConfigs > 1) { const std::size_t hash = tokenizer.list.calculateHash(); if (hashes.find(hash) != hashes.end()) { if (mSettings.debugwarnings) purgedConfigurationMessage(file.spath(), mCurrentConfig); continue; } hashes.insert(hash); } // Check normal tokens checkNormalTokens(tokenizer); } catch (const simplecpp::Output &o) { // #error etc during preprocessing configurationError.push_back((mCurrentConfig.empty() ? "\'\'" : mCurrentConfig) + " : [" + o.location.file() + ':' + std::to_string(o.location.line) + "] " + o.msg); --checkCount; // don't count invalid configurations if (!hasValidConfig && currCfg == *configurations.rbegin()) { // If there is no valid configuration then report error.. std::string locfile = Path::fromNativeSeparators(o.location.file()); if (mSettings.relativePaths) locfile = Path::getRelativePath(locfile, mSettings.basePaths); ErrorMessage::FileLocation loc1(locfile, o.location.line, o.location.col); ErrorMessage errmsg({std::move(loc1)}, file.spath(), Severity::error, o.msg, "preprocessorErrorDirective", Certainty::normal); reportErr(errmsg); } continue; } catch (const TerminateException &) { // Analysis is terminated return mExitCode; } catch (const InternalError &e) { ErrorMessage errmsg = ErrorMessage::fromInternalError(e, &tokenizer.list, file.spath()); reportErr(errmsg); } } if (!hasValidConfig && configurations.size() > 1 && mSettings.severity.isEnabled(Severity::information)) { std::string msg; msg = "This file is not analyzed. Cppcheck failed to extract a valid configuration. Use -v for more details."; msg += "\nThis file is not analyzed. Cppcheck failed to extract a valid configuration. The tested configurations have these preprocessor errors:"; for (const std::string &s : configurationError) msg += '\n' + s; const std::string locFile = Path::toNativeSeparators(file.spath()); ErrorMessage::FileLocation loc(locFile, 0, 0); ErrorMessage errmsg({std::move(loc)}, locFile, Severity::information, msg, "noValidConfiguration", Certainty::normal); reportErr(errmsg); } // dumped all configs, close root </dumps> element now if (fdump.is_open()) { fdump << "</dumps>" << std::endl; fdump.close(); } executeAddons(dumpFile, file); } catch (const TerminateException &) { // Analysis is terminated return mExitCode; } catch (const std::runtime_error &e) { internalError(file.spath(), std::string("Checking file failed: ") + e.what()); } catch (const std::bad_alloc &) { internalError(file.spath(), "Checking file failed: out of memory"); } catch (const InternalError &e) { const ErrorMessage errmsg = ErrorMessage::fromInternalError(e, nullptr, file.spath(), "Bailing out from analysis: Checking file failed"); reportErr(errmsg); } if (!mSettings.buildDir.empty()) { mAnalyzerInformation.close(); } // In jointSuppressionReport mode, unmatched suppressions are // collected after all files are processed if (!mSettings.useSingleJob() && (mSettings.severity.isEnabled(Severity::information) || mSettings.checkConfiguration)) { SuppressionList::reportUnmatchedSuppressions(mSettings.supprs.nomsg.getUnmatchedLocalSuppressions(file, (bool)mUnusedFunctionsCheck), *this); } mErrorList.clear(); if (mSettings.showtime == SHOWTIME_MODES::SHOWTIME_FILE || mSettings.showtime == SHOWTIME_MODES::SHOWTIME_TOP5_FILE) printTimerResults(mSettings.showtime); return mExitCode; } // TODO: replace with ErrorMessage::fromInternalError() void CppCheck::internalError(const std::string &filename, const std::string &msg) { const std::string fullmsg("Bailing out from analysis: " + msg); ErrorMessage::FileLocation loc1(filename, 0, 0); ErrorMessage errmsg({std::move(loc1)}, emptyString, Severity::error, fullmsg, "internalError", Certainty::normal); mErrorLogger.reportErr(errmsg); } //--------------------------------------------------------------------------- // CppCheck - A function that checks a normal token list //--------------------------------------------------------------------------- void CppCheck::checkNormalTokens(const Tokenizer &tokenizer) { CheckUnusedFunctions unusedFunctionsChecker; // TODO: this should actually be the behavior if only "--enable=unusedFunction" is specified - see #10648 const char* unusedFunctionOnly = std::getenv("UNUSEDFUNCTION_ONLY"); const bool doUnusedFunctionOnly = unusedFunctionOnly && (std::strcmp(unusedFunctionOnly, "1") == 0); if (!doUnusedFunctionOnly) { const std::time_t maxTime = mSettings.checksMaxTime > 0 ? std::time(nullptr) + mSettings.checksMaxTime : 0; // call all "runChecks" in all registered Check classes // cppcheck-suppress shadowFunction - TODO: fix this for (Check *check : Check::instances()) { if (Settings::terminated()) return; if (maxTime > 0 && std::time(nullptr) > maxTime) { if (mSettings.debugwarnings) { ErrorMessage::FileLocation loc(tokenizer.list.getFiles()[0], 0, 0); ErrorMessage errmsg({std::move(loc)}, emptyString, Severity::debug, "Checks maximum time exceeded", "checksMaxTime", Certainty::normal); reportErr(errmsg); } return; } Timer::run(check->name() + "::runChecks", mSettings.showtime, &s_timerResults, [&]() { check->runChecks(tokenizer, this); }); } } if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mSettings.buildDir.empty()) { unusedFunctionsChecker.parseTokens(tokenizer, mSettings); } if (mUnusedFunctionsCheck && mSettings.useSingleJob() && mSettings.buildDir.empty()) { mUnusedFunctionsCheck->parseTokens(tokenizer, mSettings); } if (mSettings.clang) { // TODO: Use CTU for Clang analysis return; } if (mSettings.useSingleJob() || !mSettings.buildDir.empty()) { // Analyse the tokens.. if (CTU::FileInfo * const fi1 = CTU::getFileInfo(tokenizer)) { if (!mSettings.buildDir.empty()) mAnalyzerInformation.setFileInfo("ctu", fi1->toString()); if (mSettings.useSingleJob()) mFileInfo.push_back(fi1); else delete fi1; } if (!doUnusedFunctionOnly) { // cppcheck-suppress shadowFunction - TODO: fix this for (const Check *check : Check::instances()) { if (Check::FileInfo * const fi = check->getFileInfo(tokenizer, mSettings)) { if (!mSettings.buildDir.empty()) mAnalyzerInformation.setFileInfo(check->name(), fi->toString()); if (mSettings.useSingleJob()) mFileInfo.push_back(fi); else delete fi; } } } } if (mSettings.checks.isEnabled(Checks::unusedFunction) && !mSettings.buildDir.empty()) { mAnalyzerInformation.setFileInfo("CheckUnusedFunctions", unusedFunctionsChecker.analyzerInfo()); } #ifdef HAVE_RULES executeRules("normal", tokenizer.list); #endif } //--------------------------------------------------------------------------- #ifdef HAVE_RULES bool CppCheck::hasRule(const std::string &tokenlist) const { return std::any_of(mSettings.rules.cbegin(), mSettings.rules.cend(), [&](const Settings::Rule& rule) { return rule.tokenlist == tokenlist; }); } static const char * pcreErrorCodeToString(const int pcreExecRet) { switch (pcreExecRet) { case PCRE_ERROR_NULL: return "Either code or subject was passed as NULL, or ovector was NULL " "and ovecsize was not zero (PCRE_ERROR_NULL)"; case PCRE_ERROR_BADOPTION: return "An unrecognized bit was set in the options argument (PCRE_ERROR_BADOPTION)"; case PCRE_ERROR_BADMAGIC: return "PCRE stores a 4-byte \"magic number\" at the start of the compiled code, " "to catch the case when it is passed a junk pointer and to detect when a " "pattern that was compiled in an environment of one endianness is run in " "an environment with the other endianness. This is the error that PCRE " "gives when the magic number is not present (PCRE_ERROR_BADMAGIC)"; case PCRE_ERROR_UNKNOWN_NODE: return "While running the pattern match, an unknown item was encountered in the " "compiled pattern. This error could be caused by a bug in PCRE or by " "overwriting of the compiled pattern (PCRE_ERROR_UNKNOWN_NODE)"; case PCRE_ERROR_NOMEMORY: return "If a pattern contains back references, but the ovector that is passed " "to pcre_exec() is not big enough to remember the referenced substrings, " "PCRE gets a block of memory at the start of matching to use for this purpose. " "If the call via pcre_malloc() fails, this error is given. The memory is " "automatically freed at the end of matching. This error is also given if " "pcre_stack_malloc() fails in pcre_exec(). " "This can happen only when PCRE has been compiled with " "--disable-stack-for-recursion (PCRE_ERROR_NOMEMORY)"; case PCRE_ERROR_NOSUBSTRING: return "This error is used by the pcre_copy_substring(), pcre_get_substring(), " "and pcre_get_substring_list() functions (see below). " "It is never returned by pcre_exec() (PCRE_ERROR_NOSUBSTRING)"; case PCRE_ERROR_MATCHLIMIT: return "The backtracking limit, as specified by the match_limit field in a pcre_extra " "structure (or defaulted) was reached. " "See the description above (PCRE_ERROR_MATCHLIMIT)"; case PCRE_ERROR_CALLOUT: return "This error is never generated by pcre_exec() itself. " "It is provided for use by callout functions that want to yield a distinctive " "error code. See the pcrecallout documentation for details (PCRE_ERROR_CALLOUT)"; case PCRE_ERROR_BADUTF8: return "A string that contains an invalid UTF-8 byte sequence was passed as a subject, " "and the PCRE_NO_UTF8_CHECK option was not set. If the size of the output vector " "(ovecsize) is at least 2, the byte offset to the start of the the invalid UTF-8 " "character is placed in the first element, and a reason code is placed in the " "second element. The reason codes are listed in the following section. For " "backward compatibility, if PCRE_PARTIAL_HARD is set and the problem is a truncated " "UTF-8 character at the end of the subject (reason codes 1 to 5), " "PCRE_ERROR_SHORTUTF8 is returned instead of PCRE_ERROR_BADUTF8"; case PCRE_ERROR_BADUTF8_OFFSET: return "The UTF-8 byte sequence that was passed as a subject was checked and found to " "be valid (the PCRE_NO_UTF8_CHECK option was not set), but the value of " "startoffset did not point to the beginning of a UTF-8 character or the end of " "the subject (PCRE_ERROR_BADUTF8_OFFSET)"; case PCRE_ERROR_PARTIAL: return "The subject string did not match, but it did match partially. See the " "pcrepartial documentation for details of partial matching (PCRE_ERROR_PARTIAL)"; case PCRE_ERROR_BADPARTIAL: return "This code is no longer in use. It was formerly returned when the PCRE_PARTIAL " "option was used with a compiled pattern containing items that were not supported " "for partial matching. From release 8.00 onwards, there are no restrictions on " "partial matching (PCRE_ERROR_BADPARTIAL)"; case PCRE_ERROR_INTERNAL: return "An unexpected internal error has occurred. This error could be caused by a bug " "in PCRE or by overwriting of the compiled pattern (PCRE_ERROR_INTERNAL)"; case PCRE_ERROR_BADCOUNT: return "This error is given if the value of the ovecsize argument is negative " "(PCRE_ERROR_BADCOUNT)"; case PCRE_ERROR_RECURSIONLIMIT: return "The internal recursion limit, as specified by the match_limit_recursion " "field in a pcre_extra structure (or defaulted) was reached. " "See the description above (PCRE_ERROR_RECURSIONLIMIT)"; case PCRE_ERROR_DFA_UITEM: return "PCRE_ERROR_DFA_UITEM"; case PCRE_ERROR_DFA_UCOND: return "PCRE_ERROR_DFA_UCOND"; case PCRE_ERROR_DFA_WSSIZE: return "PCRE_ERROR_DFA_WSSIZE"; case PCRE_ERROR_DFA_RECURSE: return "PCRE_ERROR_DFA_RECURSE"; case PCRE_ERROR_NULLWSLIMIT: return "PCRE_ERROR_NULLWSLIMIT"; case PCRE_ERROR_BADNEWLINE: return "An invalid combination of PCRE_NEWLINE_xxx options was " "given (PCRE_ERROR_BADNEWLINE)"; case PCRE_ERROR_BADOFFSET: return "The value of startoffset was negative or greater than the length " "of the subject, that is, the value in length (PCRE_ERROR_BADOFFSET)"; case PCRE_ERROR_SHORTUTF8: return "This error is returned instead of PCRE_ERROR_BADUTF8 when the subject " "string ends with a truncated UTF-8 character and the PCRE_PARTIAL_HARD option is set. " "Information about the failure is returned as for PCRE_ERROR_BADUTF8. " "It is in fact sufficient to detect this case, but this special error code for " "PCRE_PARTIAL_HARD precedes the implementation of returned information; " "it is retained for backwards compatibility (PCRE_ERROR_SHORTUTF8)"; case PCRE_ERROR_RECURSELOOP: return "This error is returned when pcre_exec() detects a recursion loop " "within the pattern. Specifically, it means that either the whole pattern " "or a subpattern has been called recursively for the second time at the same " "position in the subject string. Some simple patterns that might do this " "are detected and faulted at compile time, but more complicated cases, " "in particular mutual recursions between two different subpatterns, " "cannot be detected until run time (PCRE_ERROR_RECURSELOOP)"; case PCRE_ERROR_JIT_STACKLIMIT: return "This error is returned when a pattern that was successfully studied " "using a JIT compile option is being matched, but the memory available " "for the just-in-time processing stack is not large enough. See the pcrejit " "documentation for more details (PCRE_ERROR_JIT_STACKLIMIT)"; case PCRE_ERROR_BADMODE: return "This error is given if a pattern that was compiled by the 8-bit library " "is passed to a 16-bit or 32-bit library function, or vice versa (PCRE_ERROR_BADMODE)"; case PCRE_ERROR_BADENDIANNESS: return "This error is given if a pattern that was compiled and saved is reloaded on a " "host with different endianness. The utility function pcre_pattern_to_host_byte_order() " "can be used to convert such a pattern so that it runs on the new host (PCRE_ERROR_BADENDIANNESS)"; case PCRE_ERROR_DFA_BADRESTART: return "PCRE_ERROR_DFA_BADRESTART"; #if PCRE_MAJOR >= 8 && PCRE_MINOR >= 32 case PCRE_ERROR_BADLENGTH: return "This error is given if pcre_exec() is called with a negative value for the length argument (PCRE_ERROR_BADLENGTH)"; case PCRE_ERROR_JIT_BADOPTION: return "This error is returned when a pattern that was successfully studied using a JIT compile " "option is being matched, but the matching mode (partial or complete match) does not correspond " "to any JIT compilation mode. When the JIT fast path function is used, this error may be " "also given for invalid options. See the pcrejit documentation for more details (PCRE_ERROR_JIT_BADOPTION)"; #endif } return ""; } void CppCheck::executeRules(const std::string &tokenlist, const TokenList &list) { // There is no rule to execute if (!hasRule(tokenlist)) return; // Write all tokens in a string that can be parsed by pcre std::string str; for (const Token *tok = list.front(); tok; tok = tok->next()) { str += " "; str += tok->str(); } for (const Settings::Rule &rule : mSettings.rules) { if (rule.tokenlist != tokenlist) continue; if (!mSettings.quiet) { reportOut("Processing rule: " + rule.pattern, Color::FgGreen); } const char *pcreCompileErrorStr = nullptr; int erroffset = 0; pcre * const re = pcre_compile(rule.pattern.c_str(),0,&pcreCompileErrorStr,&erroffset,nullptr); if (!re) { if (pcreCompileErrorStr) { const std::string msg = "pcre_compile failed: " + std::string(pcreCompileErrorStr); const ErrorMessage errmsg(std::list<ErrorMessage::FileLocation>(), emptyString, Severity::error, msg, "pcre_compile", Certainty::normal); reportErr(errmsg); } continue; } // Optimize the regex, but only if PCRE_CONFIG_JIT is available #ifdef PCRE_CONFIG_JIT const char *pcreStudyErrorStr = nullptr; pcre_extra * const pcreExtra = pcre_study(re, PCRE_STUDY_JIT_COMPILE, &pcreStudyErrorStr); // pcre_study() returns NULL for both errors and when it can not optimize the regex. // The last argument is how one checks for errors. // It is NULL if everything works, and points to an error string otherwise. if (pcreStudyErrorStr) { const std::string msg = "pcre_study failed: " + std::string(pcreStudyErrorStr); const ErrorMessage errmsg(std::list<ErrorMessage::FileLocation>(), emptyString, Severity::error, msg, "pcre_study", Certainty::normal); reportErr(errmsg); // pcre_compile() worked, but pcre_study() returned an error. Free the resources allocated by pcre_compile(). pcre_free(re); continue; } #else const pcre_extra * const pcreExtra = nullptr; #endif int pos = 0; int ovector[30]= {0}; while (pos < (int)str.size()) { const int pcreExecRet = pcre_exec(re, pcreExtra, str.c_str(), (int)str.size(), pos, 0, ovector, 30); if (pcreExecRet < 0) { const std::string errorMessage = pcreErrorCodeToString(pcreExecRet); if (!errorMessage.empty()) { const ErrorMessage errmsg(std::list<ErrorMessage::FileLocation>(), emptyString, Severity::error, std::string("pcre_exec failed: ") + errorMessage, "pcre_exec", Certainty::normal); reportErr(errmsg); } break; } const auto pos1 = (unsigned int)ovector[0]; const auto pos2 = (unsigned int)ovector[1]; // jump to the end of the match for the next pcre_exec pos = (int)pos2; // determine location.. int fileIndex = 0; int line = 0; std::size_t len = 0; for (const Token *tok = list.front(); tok; tok = tok->next()) { len = len + 1U + tok->str().size(); if (len > pos1) { fileIndex = tok->fileIndex(); line = tok->linenr(); break; } } const std::string& file = list.getFiles()[fileIndex]; ErrorMessage::FileLocation loc(file, line, 0); // Create error message const ErrorMessage errmsg({std::move(loc)}, list.getSourceFilePath(), rule.severity, !rule.summary.empty() ? rule.summary : "found '" + str.substr(pos1, pos2 - pos1) + "'", rule.id, Certainty::normal); // Report error reportErr(errmsg); } pcre_free(re); #ifdef PCRE_CONFIG_JIT // Free up the EXTRA PCRE value (may be NULL at this point) if (pcreExtra) { pcre_free_study(pcreExtra); } #endif } } #endif void CppCheck::executeAddons(const std::string& dumpFile, const FileWithDetails& file) { if (!dumpFile.empty()) { std::vector<std::string> f{dumpFile}; executeAddons(f, file.spath()); } } void CppCheck::executeAddons(const std::vector<std::string>& files, const std::string& file0) { if (mSettings.addons.empty() || files.empty()) return; FilesDeleter filesDeleter; std::string fileList; if (files.size() >= 2 || endsWith(files[0], ".ctu-info")) { fileList = Path::getPathFromFilename(files[0]) + FILELIST; std::ofstream fout(fileList); for (const std::string& f: files) fout << f << std::endl; } // ensure all addons have already been resolved - TODO: remove when settings are const after creation assert(mSettings.addonInfos.size() == mSettings.addons.size()); std::string ctuInfo; for (const AddonInfo &addonInfo : mSettings.addonInfos) { if (addonInfo.name != "misra" && !addonInfo.ctu && endsWith(files.back(), ".ctu-info")) continue; const std::vector<picojson::value> results = executeAddon(addonInfo, mSettings.addonPython, fileList.empty() ? files[0] : fileList, mSettings.premiumArgs, mExecuteCommand); const bool misraC2023 = mSettings.premiumArgs.find("--misra-c-2023") != std::string::npos; for (const picojson::value& res : results) { // TODO: get rid of copy? // this is a copy so we can access missing fields and get a default value picojson::object obj = res.get<picojson::object>(); ErrorMessage errmsg; if (obj.count("summary") > 0) { if (!mSettings.buildDir.empty()) { ctuInfo += res.serialize() + "\n"; } else { errmsg.severity = Severity::internal; errmsg.id = "ctuinfo"; errmsg.setmsg(res.serialize()); reportErr(errmsg); } continue; } if (obj.count("file") > 0) { std::string fileName = obj["file"].get<std::string>(); const int64_t lineNumber = obj["linenr"].get<int64_t>(); const int64_t column = obj["column"].get<int64_t>(); errmsg.callStack.emplace_back(std::move(fileName), lineNumber, column); } else if (obj.count("loc") > 0) { for (const picojson::value &locvalue: obj["loc"].get<picojson::array>()) { picojson::object loc = locvalue.get<picojson::object>(); std::string fileName = loc["file"].get<std::string>(); const int64_t lineNumber = loc["linenr"].get<int64_t>(); const int64_t column = loc["column"].get<int64_t>(); std::string info = loc["info"].get<std::string>(); errmsg.callStack.emplace_back(std::move(fileName), std::move(info), lineNumber, column); } } errmsg.id = obj["addon"].get<std::string>() + "-" + obj["errorId"].get<std::string>(); if (misraC2023 && startsWith(errmsg.id, "misra-c2012-")) errmsg.id = "misra-c2023-" + errmsg.id.substr(12); errmsg.setmsg(mSettings.getMisraRuleText(errmsg.id, obj["message"].get<std::string>())); const std::string severity = obj["severity"].get<std::string>(); errmsg.severity = severityFromString(severity); if (errmsg.severity == Severity::none || errmsg.severity == Severity::internal) { if (!endsWith(errmsg.id, "-logChecker")) continue; errmsg.severity = Severity::internal; } else if (!mSettings.severity.isEnabled(errmsg.severity)) { // Do not filter out premium misra/cert/autosar messages that has been // explicitly enabled with a --premium option if (!isPremiumCodingStandardId(errmsg.id)) continue; } errmsg.file0 = file0; reportErr(errmsg); } } if (!mSettings.buildDir.empty() && fileList.empty()) { const std::string& ctuInfoFile = getCtuInfoFileName(files[0]); std::ofstream fout(ctuInfoFile); fout << ctuInfo; } } void CppCheck::executeAddonsWholeProgram(const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo) { if (mSettings.addons.empty()) return; if (mSettings.buildDir.empty()) { const std::string fileName = std::to_string(mSettings.pid) + ".ctu-info"; FilesDeleter filesDeleter; filesDeleter.addFile(fileName); std::ofstream fout(fileName); fout << ctuInfo; fout.close(); executeAddons({fileName}, ""); return; } std::vector<std::string> ctuInfoFiles; for (const auto &f: files) { const std::string &dumpFileName = getDumpFileName(mSettings, f.path()); ctuInfoFiles.push_back(getCtuInfoFileName(dumpFileName)); } for (const auto &f: fileSettings) { const std::string &dumpFileName = getDumpFileName(mSettings, f.filename()); ctuInfoFiles.push_back(getCtuInfoFileName(dumpFileName)); } try { executeAddons(ctuInfoFiles, ""); } catch (const InternalError& e) { const ErrorMessage errmsg = ErrorMessage::fromInternalError(e, nullptr, "", "Bailing out from analysis: Whole program analysis failed"); reportErr(errmsg); } } Settings &CppCheck::settings() { return mSettings; } void CppCheck::tooManyConfigsError(const std::string &file, const int numberOfConfigurations) { if (!mSettings.severity.isEnabled(Severity::information) && !mTooManyConfigs) return; mTooManyConfigs = false; if (mSettings.severity.isEnabled(Severity::information) && file.empty()) return; std::list<ErrorMessage::FileLocation> loclist; if (!file.empty()) { loclist.emplace_back(file, 0, 0); } std::ostringstream msg; msg << "Too many #ifdef configurations - cppcheck only checks " << mSettings.maxConfigs; if (numberOfConfigurations > mSettings.maxConfigs) msg << " of " << numberOfConfigurations << " configurations. Use --force to check all configurations.\n"; if (file.empty()) msg << " configurations. Use --force to check all configurations. For more details, use --enable=information.\n"; msg << "The checking of the file will be interrupted because there are too many " "#ifdef configurations. Checking of all #ifdef configurations can be forced " "by --force command line option or from GUI preferences. However that may " "increase the checking time."; if (file.empty()) msg << " For more details, use --enable=information."; ErrorMessage errmsg(std::move(loclist), emptyString, Severity::information, msg.str(), "toomanyconfigs", CWE398, Certainty::normal); reportErr(errmsg); } void CppCheck::purgedConfigurationMessage(const std::string &file, const std::string& configuration) { mTooManyConfigs = false; if (mSettings.severity.isEnabled(Severity::information) && file.empty()) return; std::list<ErrorMessage::FileLocation> loclist; if (!file.empty()) { loclist.emplace_back(file, 0, 0); } ErrorMessage errmsg(std::move(loclist), emptyString, Severity::information, "The configuration '" + configuration + "' was not checked because its code equals another one.", "purgedConfiguration", Certainty::normal); reportErr(errmsg); } //--------------------------------------------------------------------------- // TODO: part of this logic is duplicated in Executor::hasToLog() void CppCheck::reportErr(const ErrorMessage &msg) { if (msg.severity == Severity::internal) { mErrorLogger.reportErr(msg); return; } if (!mSettings.library.reportErrors(msg.file0)) return; std::set<std::string> macroNames; if (!msg.callStack.empty()) { const std::string &file = msg.callStack.back().getfile(false); int lineNumber = msg.callStack.back().line; const auto it = mLocationMacros.find(Location(file, lineNumber)); if (it != mLocationMacros.cend()) macroNames = it->second; } // TODO: only convert if necessary const auto errorMessage = SuppressionList::ErrorMessage::fromErrorMessage(msg, macroNames); if (mSettings.supprs.nomsg.isSuppressed(errorMessage, mUseGlobalSuppressions)) { // Safety: Report critical errors to ErrorLogger if (mSettings.safety && ErrorLogger::isCriticalErrorId(msg.id)) { mExitCode = 1; if (mSettings.supprs.nomsg.isSuppressedExplicitly(errorMessage, mUseGlobalSuppressions)) { // Report with internal severity to signal that there is this critical error but // it is suppressed ErrorMessage temp(msg); temp.severity = Severity::internal; mErrorLogger.reportErr(temp); } else { // Report critical error that is not explicitly suppressed mErrorLogger.reportErr(msg); } } return; } // TODO: there should be no need for the verbose and default messages here std::string errmsg = msg.toString(mSettings.verbose); if (errmsg.empty()) return; // Alert only about unique errors. // This makes sure the errors of a single check() call are unique. // TODO: get rid of this? This is forwarded to another ErrorLogger which is also doing this if (!mErrorList.emplace(std::move(errmsg)).second) return; if (!mSettings.buildDir.empty()) mAnalyzerInformation.reportErr(msg); if (!mSettings.supprs.nofail.isSuppressed(errorMessage) && !mSettings.supprs.nomsg.isSuppressed(errorMessage)) { mExitCode = 1; } std::string remark; if (!msg.callStack.empty()) { for (const auto& r: mRemarkComments) { if (r.file != msg.callStack.back().getfile(false)) continue; if (r.lineNumber != msg.callStack.back().line) continue; remark = r.str; break; } } if (!remark.empty()) { ErrorMessage msg2(msg); msg2.remark = std::move(remark); mErrorLogger.reportErr(msg2); } else { mErrorLogger.reportErr(msg); } // check if plistOutput should be populated and the current output file is open and the error is not suppressed if (!mSettings.plistOutput.empty() && mPlistFile.is_open() && !mSettings.supprs.nomsg.isSuppressed(errorMessage)) { // add error to plist output file mPlistFile << ErrorLogger::plistData(msg); } } void CppCheck::reportOut(const std::string &outmsg, Color c) { mErrorLogger.reportOut(outmsg, c); } void CppCheck::reportProgress(const std::string &filename, const char stage[], const std::size_t value) { mErrorLogger.reportProgress(filename, stage, value); } void CppCheck::getErrorMessages(ErrorLogger &errorlogger) { Settings s; s.addEnabled("all"); CppCheck cppcheck(errorlogger, true, nullptr); cppcheck.purgedConfigurationMessage(emptyString,emptyString); cppcheck.mTooManyConfigs = true; cppcheck.tooManyConfigsError(emptyString,0U); // TODO: add functions to get remaining error messages // call all "getErrorMessages" in all registered Check classes for (std::list<Check *>::const_iterator it = Check::instances().cbegin(); it != Check::instances().cend(); ++it) (*it)->getErrorMessages(&errorlogger, &s); CheckUnusedFunctions::getErrorMessages(errorlogger); Preprocessor::getErrorMessages(errorlogger, s); } void CppCheck::analyseClangTidy(const FileSettings &fileSettings) { std::string allIncludes; for (const std::string &inc : fileSettings.includePaths) { allIncludes = allIncludes + "-I\"" + inc + "\" "; } const std::string allDefines = getDefinesFlags(fileSettings.defines); #ifdef _WIN32 constexpr char exe[] = "clang-tidy.exe"; #else constexpr char exe[] = "clang-tidy"; #endif const std::string args = "-quiet -checks=*,-clang-analyzer-*,-llvm* \"" + fileSettings.filename() + "\" -- " + allIncludes + allDefines; std::string output; if (const int exitcode = mExecuteCommand(exe, split(args), emptyString, output)) { std::cerr << "Failed to execute '" << exe << "' (exitcode: " << std::to_string(exitcode) << ")" << std::endl; return; } // parse output and create error messages std::istringstream istr(output); std::string line; if (!mSettings.buildDir.empty()) { const std::string analyzerInfoFile = AnalyzerInformation::getAnalyzerInfoFile(mSettings.buildDir, fileSettings.filename(), emptyString); std::ofstream fcmd(analyzerInfoFile + ".clang-tidy-cmd"); fcmd << istr.str(); } while (std::getline(istr, line)) { if (line.find("error") == std::string::npos && line.find("warning") == std::string::npos) continue; std::size_t endColumnPos = line.find(": error:"); if (endColumnPos == std::string::npos) { endColumnPos = line.find(": warning:"); } const std::size_t endLinePos = line.rfind(':', endColumnPos-1); const std::size_t endNamePos = line.rfind(':', endLinePos - 1); const std::size_t endMsgTypePos = line.find(':', endColumnPos + 2); const std::size_t endErrorPos = line.rfind('[', std::string::npos); if (endLinePos==std::string::npos || endNamePos==std::string::npos || endMsgTypePos==std::string::npos || endErrorPos==std::string::npos) continue; const std::string lineNumString = line.substr(endNamePos + 1, endLinePos - endNamePos - 1); const std::string columnNumString = line.substr(endLinePos + 1, endColumnPos - endLinePos - 1); const std::string messageString = line.substr(endMsgTypePos + 1, endErrorPos - endMsgTypePos - 1); const std::string errorString = line.substr(endErrorPos, line.length()); std::string fixedpath = Path::simplifyPath(line.substr(0, endNamePos)); const auto lineNumber = strToInt<int64_t>(lineNumString); const auto column = strToInt<int64_t>(columnNumString); fixedpath = Path::toNativeSeparators(std::move(fixedpath)); ErrorMessage errmsg; errmsg.callStack.emplace_back(fixedpath, lineNumber, column); errmsg.id = "clang-tidy-" + errorString.substr(1, errorString.length() - 2); if (errmsg.id.find("performance") != std::string::npos) errmsg.severity = Severity::performance; else if (errmsg.id.find("portability") != std::string::npos) errmsg.severity = Severity::portability; else if (errmsg.id.find("cert") != std::string::npos || errmsg.id.find("misc") != std::string::npos || errmsg.id.find("unused") != std::string::npos) errmsg.severity = Severity::warning; else errmsg.severity = Severity::style; errmsg.file0 = std::move(fixedpath); errmsg.setmsg(messageString); reportErr(errmsg); } } bool CppCheck::analyseWholeProgram() { bool errors = false; // Analyse the tokens CTU::FileInfo ctu; if (mSettings.useSingleJob() || !mSettings.buildDir.empty()) { for (const Check::FileInfo *fi : mFileInfo) { const auto *fi2 = dynamic_cast<const CTU::FileInfo *>(fi); if (fi2) { ctu.functionCalls.insert(ctu.functionCalls.end(), fi2->functionCalls.cbegin(), fi2->functionCalls.cend()); ctu.nestedCalls.insert(ctu.nestedCalls.end(), fi2->nestedCalls.cbegin(), fi2->nestedCalls.cend()); } } } // cppcheck-suppress shadowFunction - TODO: fix this for (Check *check : Check::instances()) errors |= check->analyseWholeProgram(&ctu, mFileInfo, mSettings, *this); // TODO: ctu if (mUnusedFunctionsCheck) errors |= mUnusedFunctionsCheck->check(mSettings, *this); return errors && (mExitCode > 0); } unsigned int CppCheck::analyseWholeProgram(const std::string &buildDir, const std::list<FileWithDetails> &files, const std::list<FileSettings>& fileSettings, const std::string& ctuInfo) { executeAddonsWholeProgram(files, fileSettings, ctuInfo); if (mSettings.checks.isEnabled(Checks::unusedFunction)) CheckUnusedFunctions::analyseWholeProgram(mSettings, *this, buildDir); std::list<Check::FileInfo*> fileInfoList; CTU::FileInfo ctuFileInfo; // Load all analyzer info data.. const std::string filesTxt(buildDir + "/files.txt"); std::ifstream fin(filesTxt); std::string filesTxtLine; while (std::getline(fin, filesTxtLine)) { const std::string::size_type firstColon = filesTxtLine.find(':'); if (firstColon == std::string::npos) continue; const std::string::size_type lastColon = filesTxtLine.rfind(':'); if (firstColon == lastColon) continue; const std::string xmlfile = buildDir + '/' + filesTxtLine.substr(0,firstColon); //const std::string sourcefile = filesTxtLine.substr(lastColon+1); tinyxml2::XMLDocument doc; const tinyxml2::XMLError error = doc.LoadFile(xmlfile.c_str()); if (error != tinyxml2::XML_SUCCESS) continue; const tinyxml2::XMLElement * const rootNode = doc.FirstChildElement(); if (rootNode == nullptr) continue; for (const tinyxml2::XMLElement *e = rootNode->FirstChildElement(); e; e = e->NextSiblingElement()) { if (std::strcmp(e->Name(), "FileInfo") != 0) continue; const char *checkClassAttr = e->Attribute("check"); if (!checkClassAttr) continue; if (std::strcmp(checkClassAttr, "ctu") == 0) { ctuFileInfo.loadFromXml(e); continue; } // cppcheck-suppress shadowFunction - TODO: fix this for (const Check *check : Check::instances()) { if (checkClassAttr == check->name()) fileInfoList.push_back(check->loadFileInfoFromXml(e)); } } } // Analyse the tokens // cppcheck-suppress shadowFunction - TODO: fix this for (Check *check : Check::instances()) check->analyseWholeProgram(&ctuFileInfo, fileInfoList, mSettings, *this); if (mUnusedFunctionsCheck) mUnusedFunctionsCheck->check(mSettings, *this); for (Check::FileInfo *fi : fileInfoList) delete fi; return mExitCode; } // cppcheck-suppress unusedFunction - only used in tests void CppCheck::resetTimerResults() { s_timerResults.reset(); } void CppCheck::printTimerResults(SHOWTIME_MODES mode) { s_timerResults.showResults(mode); } bool CppCheck::isPremiumCodingStandardId(const std::string& id) const { if (mSettings.premiumArgs.find("--misra") != std::string::npos) { if (startsWith(id, "misra-") || startsWith(id, "premium-misra-")) return true; } if (mSettings.premiumArgs.find("--cert") != std::string::npos && startsWith(id, "premium-cert-")) return true; if (mSettings.premiumArgs.find("--autosar") != std::string::npos && startsWith(id, "premium-autosar-")) return true; return false; } std::string CppCheck::getDumpFileContentsRawTokens(const std::vector<std::string>& files, const simplecpp::TokenList& tokens1) const { std::string dumpProlog; dumpProlog += " <rawtokens>\n"; for (unsigned int i = 0; i < files.size(); ++i) { dumpProlog += " <file index=\""; dumpProlog += std::to_string(i); dumpProlog += "\" name=\""; dumpProlog += ErrorLogger::toxml(Path::getRelativePath(files[i], mSettings.basePaths)); dumpProlog += "\"/>\n"; } for (const simplecpp::Token *tok = tokens1.cfront(); tok; tok = tok->next) { dumpProlog += " <tok "; dumpProlog += "fileIndex=\""; dumpProlog += std::to_string(tok->location.fileIndex); dumpProlog += "\" "; dumpProlog += "linenr=\""; dumpProlog += std::to_string(tok->location.line); dumpProlog += "\" "; dumpProlog +="column=\""; dumpProlog += std::to_string(tok->location.col); dumpProlog += "\" "; dumpProlog += "str=\""; dumpProlog += ErrorLogger::toxml(tok->str()); dumpProlog += "\""; dumpProlog += "/>\n"; } dumpProlog += " </rawtokens>\n"; return dumpProlog; }
80,065
C++
.cpp
1,679
37.369267
262
0.599124
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,181
astutils.cpp
danmar_cppcheck/lib/astutils.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "astutils.h" #include "config.h" #include "errortypes.h" #include "findtoken.h" #include "infer.h" #include "library.h" #include "mathlib.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "utils.h" #include "valueflow.h" #include "valueptr.h" #include "vfvalue.h" #include "checkclass.h" #include <algorithm> #include <cassert> #include <cstring> #include <functional> #include <initializer_list> #include <iterator> #include <list> #include <set> #include <type_traits> #include <unordered_map> #include <utility> const Token* findExpression(const nonneg int exprid, const Token* start, const Token* end, const std::function<bool(const Token*)>& pred) { if (exprid == 0) return nullptr; if (!precedes(start, end)) return nullptr; for (const Token* tok = start; tok != end; tok = tok->next()) { if (tok->exprId() != exprid) continue; if (pred(tok)) return tok; } return nullptr; } static int findArgumentPosRecursive(const Token* tok, const Token* tokToFind, bool &found, nonneg int depth=0) { ++depth; if (!tok || depth >= 100) return -1; if (tok->str() == ",") { int res = findArgumentPosRecursive(tok->astOperand1(), tokToFind, found, depth); if (res == -1) return -1; if (found) return res; const int argn = res; res = findArgumentPosRecursive(tok->astOperand2(), tokToFind, found, depth); if (res == -1) return -1; return argn + res; } if (tokToFind == tok) found = true; return 1; } static int findArgumentPos(const Token* tok, const Token* tokToFind){ bool found = false; const int argn = findArgumentPosRecursive(tok, tokToFind, found, 0); if (found) return argn - 1; return -1; } static int getArgumentPos(const Token* ftok, const Token* tokToFind){ const Token* tok = ftok; if (Token::Match(tok, "%name% (|{")) tok = ftok->next(); if (!Token::Match(tok, "(|{|[")) return -1; const Token* startTok = tok->astOperand2(); if (!startTok && tok->next() != tok->link()) startTok = tok->astOperand1(); return findArgumentPos(startTok, tokToFind); } template<class T, class OuputIterator, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static void astFlattenCopy(T* tok, const char* op, OuputIterator out, nonneg int depth = 100) { --depth; if (!tok || depth < 0) return; if (strcmp(tok->str().c_str(), op) == 0) { astFlattenCopy(tok->astOperand1(), op, out, depth); astFlattenCopy(tok->astOperand2(), op, out, depth); } else { *out = tok; ++out; } } std::vector<const Token*> astFlatten(const Token* tok, const char* op) { std::vector<const Token*> result; astFlattenCopy(tok, op, std::back_inserter(result)); return result; } std::vector<Token*> astFlatten(Token* tok, const char* op) { std::vector<Token*> result; astFlattenCopy(tok, op, std::back_inserter(result)); return result; } nonneg int astCount(const Token* tok, const char* op, int depth) { --depth; if (!tok || depth < 0) return 0; if (strcmp(tok->str().c_str(), op) == 0) return astCount(tok->astOperand1(), op, depth) + astCount(tok->astOperand2(), op, depth); return 1; } bool astHasToken(const Token* root, const Token * tok) { if (!root) return false; while (tok->astParent() && tok != root) tok = tok->astParent(); return root == tok; } bool astHasVar(const Token * tok, nonneg int varid) { if (!tok) return false; if (tok->varId() == varid) return true; return astHasVar(tok->astOperand1(), varid) || astHasVar(tok->astOperand2(), varid); } bool astHasExpr(const Token* tok, nonneg int exprid) { if (!tok) return false; if (tok->exprId() == exprid) return true; return astHasExpr(tok->astOperand1(), exprid) || astHasExpr(tok->astOperand2(), exprid); } static bool astIsCharWithSign(const Token *tok, ValueType::Sign sign) { if (!tok) return false; const ValueType *valueType = tok->valueType(); if (!valueType) return false; return valueType->type == ValueType::Type::CHAR && valueType->pointer == 0U && valueType->sign == sign; } bool astIsSignedChar(const Token *tok) { return astIsCharWithSign(tok, ValueType::Sign::SIGNED); } bool astIsUnknownSignChar(const Token *tok) { return astIsCharWithSign(tok, ValueType::Sign::UNKNOWN_SIGN); } bool astIsGenericChar(const Token* tok) { return !astIsPointer(tok) && tok && tok->valueType() && (tok->valueType()->type == ValueType::Type::CHAR || tok->valueType()->type == ValueType::Type::WCHAR_T); } bool astIsPrimitive(const Token* tok) { const ValueType* vt = tok ? tok->valueType() : nullptr; if (!vt) return false; return vt->isPrimitive(); } bool astIsIntegral(const Token *tok, bool unknown) { const ValueType *vt = tok ? tok->valueType() : nullptr; if (!vt) return unknown; return vt->isIntegral() && vt->pointer == 0U; } bool astIsUnsigned(const Token* tok) { return tok && tok->valueType() && tok->valueType()->sign == ValueType::UNSIGNED; } bool astIsFloat(const Token *tok, bool unknown) { const ValueType *vt = tok ? tok->valueType() : nullptr; if (!vt) return unknown; return vt->type >= ValueType::Type::FLOAT && vt->pointer == 0U; } bool astIsBool(const Token *tok) { return tok && (tok->isBoolean() || (tok->valueType() && tok->valueType()->type == ValueType::Type::BOOL && !tok->valueType()->pointer)); } bool astIsPointer(const Token *tok) { return tok && tok->valueType() && tok->valueType()->pointer; } bool astIsSmartPointer(const Token* tok) { return tok && tok->valueType() && tok->valueType()->smartPointerTypeToken; } bool astIsUniqueSmartPointer(const Token* tok) { if (!astIsSmartPointer(tok)) return false; if (!tok->valueType()->smartPointer) return false; return tok->valueType()->smartPointer->unique; } bool astIsIterator(const Token *tok) { return tok && tok->valueType() && tok->valueType()->type == ValueType::Type::ITERATOR; } bool astIsContainer(const Token* tok) { return getLibraryContainer(tok) != nullptr && !astIsIterator(tok); } bool astIsNonStringContainer(const Token* tok) { const Library::Container* container = getLibraryContainer(tok); return container && !container->stdStringLike && !astIsIterator(tok); } bool astIsContainerView(const Token* tok) { const Library::Container* container = getLibraryContainer(tok); return container && !astIsIterator(tok) && container->view; } bool astIsContainerOwned(const Token* tok) { return astIsContainer(tok) && !astIsContainerView(tok); } bool astIsContainerString(const Token* tok) { if (!tok) return false; if (!tok->valueType()) return false; const Library::Container* container = tok->valueType()->container; if (!container) return false; return container->stdStringLike; } static std::pair<const Token*, const Library::Container*> getContainerFunction(const Token* tok, const Settings* settings) { const Library::Container* cont{}; if (!tok || !tok->valueType() || (!tok->valueType()->container && (!settings || !(cont = settings->library.detectContainerOrIterator(tok->valueType()->smartPointerTypeToken))))) return {}; const Token* parent = tok->astParent(); if (Token::Match(parent, ". %name% (") && astIsLHS(tok)) { return { parent->next(), cont ? cont : tok->valueType()->container }; } return {}; } Library::Container::Action astContainerAction(const Token* tok, const Token** ftok, const Settings* settings) { const auto ftokCont = getContainerFunction(tok, settings); if (ftok) *ftok = ftokCont.first; if (!ftokCont.first) return Library::Container::Action::NO_ACTION; return ftokCont.second->getAction(ftokCont.first->str()); } Library::Container::Yield astContainerYield(const Token* tok, const Token** ftok, const Settings* settings) { const auto ftokCont = getContainerFunction(tok, settings); if (ftok) *ftok = ftokCont.first; if (!ftokCont.first) return Library::Container::Yield::NO_YIELD; return ftokCont.second->getYield(ftokCont.first->str()); } Library::Container::Yield astFunctionYield(const Token* tok, const Settings& settings, const Token** ftok) { if (!tok) return Library::Container::Yield::NO_YIELD; const auto* function = settings.library.getFunction(tok); if (!function) return Library::Container::Yield::NO_YIELD; if (ftok) *ftok = tok; return function->containerYield; } bool astIsRangeBasedForDecl(const Token* tok) { return Token::simpleMatch(tok->astParent(), ":") && Token::simpleMatch(tok->astParent()->astParent(), "("); } std::string astCanonicalType(const Token *expr, bool pointedToType) { if (!expr) return ""; std::pair<const Token*, const Token*> decl = Token::typeDecl(expr, pointedToType); if (decl.first && decl.second) { std::string ret; for (const Token *type = decl.first; Token::Match(type,"%name%|::") && type != decl.second; type = type->next()) { if (!Token::Match(type, "const|static")) ret += type->str(); } return ret; } return ""; } static bool match(const Token *tok, const std::string &rhs) { if (tok->str() == rhs) return true; if (!tok->varId() && tok->hasKnownIntValue() && std::to_string(tok->values().front().intvalue) == rhs) return true; return false; } const Token * astIsVariableComparison(const Token *tok, const std::string &comp, const std::string &rhs, const Token **vartok) { if (!tok) return nullptr; const Token *ret = nullptr; if (tok->isComparisonOp()) { if (tok->astOperand1() && match(tok->astOperand1(), rhs)) { // Invert comparator std::string s = tok->str(); if (s[0] == '>') s[0] = '<'; else if (s[0] == '<') s[0] = '>'; if (s == comp) { ret = tok->astOperand2(); } } else if (tok->str() == comp && tok->astOperand2() && match(tok->astOperand2(), rhs)) { ret = tok->astOperand1(); } } else if (comp == "!=" && rhs == "0") { if (tok->str() == "!") { ret = tok->astOperand1(); // handle (!(x==0)) as (x!=0) astIsVariableComparison(ret, "==", "0", &ret); } else ret = tok; } else if (comp == "==" && rhs == "0") { if (tok->str() == "!") { ret = tok->astOperand1(); // handle (!(x!=0)) as (x==0) astIsVariableComparison(ret, "!=", "0", &ret); } } while (ret && ret->str() == ".") ret = ret->astOperand2(); if (ret && ret->str() == "=" && ret->astOperand1() && ret->astOperand1()->varId()) ret = ret->astOperand1(); else if (ret && ret->varId() == 0U) ret = nullptr; if (vartok) *vartok = ret; return ret; } bool isVariableDecl(const Token* tok) { if (!tok) return false; const Variable* var = tok->variable(); if (!var) return false; if (var->nameToken() == tok) return true; const Token * const varDeclEndToken = var->declEndToken(); return Token::Match(varDeclEndToken, "; %var%") && varDeclEndToken->next() == tok; } bool isStlStringType(const Token* tok) { return Token::Match(tok, "std :: string|wstring|u16string|u32string !!::") || (Token::simpleMatch(tok, "std :: basic_string <") && !Token::simpleMatch(tok->linkAt(3), "> ::")); } bool isTemporary(const Token* tok, const Library* library, bool unknown) { if (!tok) return false; if (Token::simpleMatch(tok, ".")) return (tok->originalName() != "->" && isTemporary(tok->astOperand1(), library)) || isTemporary(tok->astOperand2(), library); if (Token::Match(tok, ",|::")) return isTemporary(tok->astOperand2(), library); if (tok->isCast() || (tok->isCpp() && isCPPCast(tok))) return isTemporary(tok->astOperand2(), library); if (Token::Match(tok, ".|[|++|--|%name%|%assign%")) return false; if (tok->isUnaryOp("*")) return false; if (Token::Match(tok, "&|<<|>>") && isLikelyStream(tok->astOperand1())) return false; if (Token::simpleMatch(tok, "?")) { const Token* branchTok = tok->astOperand2(); if (!branchTok->astOperand1() || !branchTok->astOperand1()->valueType()) return false; if (!branchTok->astOperand2()->valueType()) return false; return !branchTok->astOperand1()->valueType()->isTypeEqual(branchTok->astOperand2()->valueType()); } if (Token::simpleMatch(tok, "(") && tok->astOperand1() && (tok->astOperand2() || Token::simpleMatch(tok->next(), ")"))) { if (Token::simpleMatch(tok->astOperand1(), "typeid")) return false; if (tok->valueType()) { if (tok->valueType()->pointer > 0) { const Token* const parent = tok->astParent(); if (Token::simpleMatch(parent, "&")) return true; if (Token::simpleMatch(parent, "return") && parent->valueType()->reference != Reference::None && parent->valueType()->container && parent->valueType()->container->stdStringLike) return true; } return tok->valueType()->reference == Reference::None && tok->valueType()->pointer == 0; } const Token* ftok = nullptr; if (Token::simpleMatch(tok->previous(), ">") && tok->linkAt(-1)) ftok = tok->linkAt(-1)->previous(); else ftok = tok->previous(); if (!ftok) return false; if (const Function * f = ftok->function()) return !Function::returnsReference(f, true); if (ftok->type()) return true; if (library) { const std::string& returnType = library->returnValueType(ftok); return !returnType.empty() && returnType.back() != '&'; } return unknown; } if (tok->isCast()) return false; // Currying a function is unknown in cppcheck if (Token::simpleMatch(tok, "(") && Token::simpleMatch(tok->astOperand1(), "(")) return unknown; if (Token::simpleMatch(tok, "{") && Token::simpleMatch(tok->astParent(), "return") && tok->astOperand1() && !tok->astOperand2()) return isTemporary(tok->astOperand1(), library); return true; } static bool isFunctionCall(const Token* tok) { if (Token::Match(tok, "%name% (")) return true; if (Token::Match(tok, "%name% <") && Token::simpleMatch(tok->linkAt(1), "> (")) return true; if (Token::Match(tok, "%name% ::")) return isFunctionCall(tok->tokAt(2)); return false; } static bool hasToken(const Token * startTok, const Token * stopTok, const Token * tok) { for (const Token * tok2 = startTok; tok2 != stopTok; tok2 = tok2->next()) { if (tok2 == tok) return true; } return false; } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* previousBeforeAstLeftmostLeafGeneric(T* tok) { if (!tok) return nullptr; T* leftmostLeaf = tok; while (leftmostLeaf->astOperand1()) leftmostLeaf = leftmostLeaf->astOperand1(); return leftmostLeaf->previous(); } const Token* previousBeforeAstLeftmostLeaf(const Token* tok) { return previousBeforeAstLeftmostLeafGeneric(tok); } Token* previousBeforeAstLeftmostLeaf(Token* tok) { return previousBeforeAstLeftmostLeafGeneric(tok); } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* nextAfterAstRightmostLeafGeneric(T* tok) { T * rightmostLeaf = tok; if (!rightmostLeaf || !rightmostLeaf->astOperand1()) return nullptr; do { if (T* lam = findLambdaEndToken(rightmostLeaf)) { rightmostLeaf = lam; break; } if (rightmostLeaf->astOperand2() && precedes(rightmostLeaf, rightmostLeaf->astOperand2())) rightmostLeaf = rightmostLeaf->astOperand2(); else if (rightmostLeaf->astOperand1() && precedes(rightmostLeaf, rightmostLeaf->astOperand1())) rightmostLeaf = rightmostLeaf->astOperand1(); else break; } while (rightmostLeaf->astOperand1() || rightmostLeaf->astOperand2()); while (Token::Match(rightmostLeaf->next(), "]|)") && !hasToken(rightmostLeaf->linkAt(1), rightmostLeaf->next(), tok)) rightmostLeaf = rightmostLeaf->next(); if (Token::Match(rightmostLeaf, "{|(|[") && rightmostLeaf->link()) rightmostLeaf = rightmostLeaf->link(); return rightmostLeaf->next(); } const Token* nextAfterAstRightmostLeaf(const Token* tok) { return nextAfterAstRightmostLeafGeneric(tok); } Token* nextAfterAstRightmostLeaf(Token* tok) { return nextAfterAstRightmostLeafGeneric(tok); } const Token* astParentSkipParens(const Token* tok) { return astParentSkipParens(const_cast<Token*>(tok)); } Token* astParentSkipParens(Token* tok) { if (!tok) return nullptr; Token * parent = tok->astParent(); if (!Token::simpleMatch(parent, "(")) return parent; if (parent->link() != nextAfterAstRightmostLeaf(tok)) return parent; if (Token::Match(parent->previous(), "%name% (") || (Token::simpleMatch(parent->previous(), "> (") && parent->linkAt(-1))) return parent; return astParentSkipParens(parent); } const Token* getParentMember(const Token * tok) { if (!tok) return tok; const Token * parent = tok->astParent(); if (!Token::simpleMatch(parent, ".")) return tok; if (astIsRHS(tok)) { if (Token::simpleMatch(parent->astOperand1(), ".")) return parent->astOperand1()->astOperand2(); return parent->astOperand1(); } const Token * gparent = parent->astParent(); if (!Token::simpleMatch(gparent, ".") || gparent->astOperand2() != parent) return tok; if (gparent->astOperand1()) return gparent->astOperand1(); return tok; } const Token* getParentLifetime(const Token* tok) { if (!tok) return tok; // Skipping checking for variable if its a pointer-to-member if (!Token::simpleMatch(tok->previous(), ". *")) { const Variable* var = tok->variable(); // TODO: Call getLifetimeVariable for deeper analysis if (!var) return tok; if (var->isLocal() || var->isArgument()) return tok; } const Token* parent = getParentMember(tok); if (parent != tok) return getParentLifetime(parent); return tok; } static std::vector<const Token*> getParentMembers(const Token* tok) { if (!tok) return {}; if (!Token::simpleMatch(tok->astParent(), ".")) return {tok}; const Token* parent = tok->astParent(); while (Token::simpleMatch(parent->astParent(), ".")) parent = parent->astParent(); std::vector<const Token*> result; for (const Token* tok2 : astFlatten(parent, ".")) { if (Token::simpleMatch(tok2, "(") && Token::simpleMatch(tok2->astOperand1(), ".")) { std::vector<const Token*> sub = getParentMembers(tok2->astOperand1()); result.insert(result.end(), sub.cbegin(), sub.cend()); } result.push_back(tok2); } return result; } static const Token* getParentLifetimeObject(const Token* tok) { while (Token::simpleMatch(tok, "[")) tok = tok->astOperand1(); return tok; } const Token* getParentLifetime(const Token* tok, const Library& library) { std::vector<const Token*> members = getParentMembers(tok); if (members.size() < 2) return tok; // Find the first local variable, temporary, or array auto it = std::find_if(members.crbegin(), members.crend(), [&](const Token* tok2) { const Variable* var = tok2->variable(); if (var) return var->isLocal() || var->isArgument(); if (Token::simpleMatch(tok2, "[")) return true; return isTemporary(tok2, &library); }); if (it == members.rend()) return tok; // If any of the submembers are borrowed types then stop if (std::any_of(it.base() - 1, members.cend() - 1, [&](const Token* tok2) { const Token* obj = getParentLifetimeObject(tok2); const Variable* var = obj->variable(); // Check for arrays first since astIsPointer will return true, but an array is not a borrowed type if (var && var->isArray()) return false; if (astIsPointer(obj) || astIsContainerView(obj) || astIsIterator(obj)) return true; if (!astIsUniqueSmartPointer(obj)) { if (astIsSmartPointer(obj)) return true; const Token* dotTok = obj->next(); if (!Token::simpleMatch(dotTok, ".")) { const Token* endTok = nextAfterAstRightmostLeaf(obj); if (!endTok) dotTok = obj->next(); else if (Token::simpleMatch(endTok, ".")) dotTok = endTok; else if (Token::simpleMatch(endTok->next(), ".")) dotTok = endTok->next(); } // If we are dereferencing the member variable then treat it as borrowed if (Token::simpleMatch(dotTok, ".") && dotTok->originalName() == "->") return true; } return var && var->isReference(); })) return nullptr; const Token* result = getParentLifetimeObject(*it); if (result != *it) return getParentLifetime(result); return result; } static bool isInConstructorList(const Token* tok) { if (!tok) return false; if (!astIsRHS(tok)) return false; const Token* parent = tok->astParent(); if (!Token::Match(parent, "{|(")) return false; if (!Token::Match(parent->previous(), "%var% {|(")) return false; if (!parent->astOperand1() || !parent->astOperand2()) return false; do { parent = parent->astParent(); } while (Token::simpleMatch(parent, ",")); return Token::simpleMatch(parent, ":") && !Token::simpleMatch(parent->astParent(), "?"); } std::vector<ValueType> getParentValueTypes(const Token* tok, const Settings& settings, const Token** parent) { if (!tok) return {}; if (!tok->astParent()) return {}; if (isInConstructorList(tok)) { if (parent) *parent = tok->astParent()->astOperand1(); if (tok->astParent()->astOperand1()->valueType()) return {*tok->astParent()->astOperand1()->valueType()}; return {}; } const Token* ftok = nullptr; if (Token::Match(tok->astParent(), "(|{|,")) { int argn = -1; ftok = getTokenArgumentFunction(tok, argn); const Token* typeTok = nullptr; if (ftok && argn >= 0) { if (ftok->function()) { std::vector<ValueType> result; const Token* nameTok = nullptr; for (const Variable* var : getArgumentVars(ftok, argn)) { if (!var) continue; if (!var->valueType()) continue; nameTok = var->nameToken(); result.push_back(*var->valueType()); if (var->isArray()) result.back().pointer += var->dimensions().size(); } if (result.size() == 1 && nameTok && parent) { *parent = nameTok; } return result; } if (const Type* t = Token::typeOf(ftok, &typeTok)) { if (astIsPointer(typeTok)) return {*typeTok->valueType()}; const Scope* scope = t->classScope; // Check for aggregate constructors if (scope && scope->numConstructors == 0 && t->derivedFrom.empty() && (t->isClassType() || t->isStructType()) && numberOfArguments(ftok) <= scope->varlist.size() && !scope->varlist.empty()) { assert(argn < scope->varlist.size()); auto it = std::next(scope->varlist.cbegin(), argn); if (it->valueType()) return {*it->valueType()}; } } } } if (Token::Match(tok->astParent()->tokAt(-2), ". push_back|push_front|insert|push (") && astIsContainer(tok->astParent()->tokAt(-2)->astOperand1())) { const Token* contTok = tok->astParent()->tokAt(-2)->astOperand1(); const ValueType* vtCont = contTok->valueType(); if (!vtCont->containerTypeToken) return {}; ValueType vtParent = ValueType::parseDecl(vtCont->containerTypeToken, settings); return {std::move(vtParent)}; } // The return type of a function is not the parent valuetype if (Token::simpleMatch(tok->astParent(), "(") && ftok && !tok->astParent()->isCast() && ftok->tokType() != Token::eType) return {}; if (parent && Token::Match(tok->astParent(), "return|(|{|%assign%")) { *parent = tok->astParent(); } if (tok->astParent()->valueType()) return {*tok->astParent()->valueType()}; return {}; } bool astIsLHS(const Token* tok) { if (!tok) return false; const Token* parent = tok->astParent(); if (!parent) return false; if (!parent->astOperand1()) return false; if (!parent->astOperand2()) return false; return parent->astOperand1() == tok; } bool astIsRHS(const Token* tok) { if (!tok) return false; const Token* parent = tok->astParent(); if (!parent) return false; if (!parent->astOperand1()) return false; if (!parent->astOperand2()) return false; return parent->astOperand2() == tok; } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* getCondTokImpl(T* tok) { if (!tok) return nullptr; if (Token::simpleMatch(tok, "(")) return getCondTok(tok->previous()); if (Token::simpleMatch(tok, "do {")) { T* endTok = tok->linkAt(1); if (Token::simpleMatch(endTok, "} while (")) return endTok->tokAt(2)->astOperand2(); } if (Token::simpleMatch(tok, "for") && Token::simpleMatch(tok->next()->astOperand2(), ";") && tok->next()->astOperand2()->astOperand2()) return tok->next()->astOperand2()->astOperand2()->astOperand1(); if (Token::simpleMatch(tok->next()->astOperand2(), ";")) return tok->next()->astOperand2()->astOperand1(); if (tok->isName() && !tok->isControlFlowKeyword()) return nullptr; return tok->next()->astOperand2(); } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* getCondTokFromEndImpl(T* endBlock) { if (!Token::simpleMatch(endBlock, "}")) return nullptr; T* startBlock = endBlock->link(); if (!Token::simpleMatch(startBlock, "{")) return nullptr; if (Token::simpleMatch(startBlock->previous(), "do")) return getCondTok(startBlock->previous()); if (Token::simpleMatch(startBlock->previous(), ")")) return getCondTok(startBlock->linkAt(-1)); if (Token::simpleMatch(startBlock->tokAt(-2), "} else {")) return getCondTokFromEnd(startBlock->tokAt(-2)); return nullptr; } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* getInitTokImpl(T* tok) { if (!tok) return nullptr; if (Token::Match(tok, "%name% (")) return getInitTokImpl(tok->next()); if (tok->str() != "(") return nullptr; if (!Token::simpleMatch(tok->astOperand2(), ";")) return nullptr; if (Token::simpleMatch(tok->astOperand2()->astOperand1(), ";")) return nullptr; return tok->astOperand2()->astOperand1(); } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* getStepTokImpl(T* tok) { if (!tok) return nullptr; if (Token::Match(tok, "%name% (")) return getStepTokImpl(tok->next()); if (tok->str() != "(") return nullptr; if (!Token::simpleMatch(tok->astOperand2(), ";")) return nullptr; if (!Token::simpleMatch(tok->astOperand2()->astOperand2(), ";")) return nullptr; return tok->astOperand2()->astOperand2()->astOperand2(); } Token* getCondTok(Token* tok) { return getCondTokImpl(tok); } const Token* getCondTok(const Token* tok) { return getCondTokImpl(tok); } Token* getCondTokFromEnd(Token* endBlock) { return getCondTokFromEndImpl(endBlock); } const Token* getCondTokFromEnd(const Token* endBlock) { return getCondTokFromEndImpl(endBlock); } Token* getInitTok(Token* tok) { return getInitTokImpl(tok); } const Token* getInitTok(const Token* tok) { return getInitTokImpl(tok); } Token* getStepTok(Token* tok) { return getStepTokImpl(tok); } const Token* getStepTok(const Token* tok) { return getStepTokImpl(tok); } const Token *findNextTokenFromBreak(const Token *breakToken) { const Scope *scope = breakToken->scope(); while (scope) { if (scope->isLoopScope() || scope->type == Scope::ScopeType::eSwitch) { if (scope->type == Scope::ScopeType::eDo && Token::simpleMatch(scope->bodyEnd, "} while (")) return scope->bodyEnd->linkAt(2)->next(); return scope->bodyEnd; } scope = scope->nestedIn; } return nullptr; } bool extractForLoopValues(const Token *forToken, nonneg int &varid, bool &knownInitValue, MathLib::bigint &initValue, bool &partialCond, MathLib::bigint &stepValue, MathLib::bigint &lastValue) { if (!Token::simpleMatch(forToken, "for (") || !Token::simpleMatch(forToken->next()->astOperand2(), ";")) return false; const Token *initExpr = forToken->next()->astOperand2()->astOperand1(); const Token *condExpr = forToken->next()->astOperand2()->astOperand2()->astOperand1(); const Token *incExpr = forToken->next()->astOperand2()->astOperand2()->astOperand2(); if (!initExpr || !initExpr->isBinaryOp() || initExpr->str() != "=" || !Token::Match(initExpr->astOperand1(), "%var%")) return false; std::vector<MathLib::bigint> minInitValue = getMinValue(makeIntegralInferModel(), initExpr->astOperand2()->values()); if (minInitValue.empty()) { const ValueFlow::Value* v = initExpr->astOperand2()->getMinValue(true); if (v) minInitValue.push_back(v->intvalue); } if (minInitValue.empty()) return false; varid = initExpr->astOperand1()->varId(); knownInitValue = initExpr->astOperand2()->hasKnownIntValue(); initValue = minInitValue.front(); partialCond = Token::Match(condExpr, "%oror%|&&"); visitAstNodes(condExpr, [varid, &condExpr](const Token *tok) { if (Token::Match(tok, "%oror%|&&")) return ChildrenToVisit::op1_and_op2; if (Token::Match(tok, "<|<=") && tok->isBinaryOp() && tok->astOperand1()->varId() == varid && tok->astOperand2()->hasKnownIntValue()) { if (Token::Match(condExpr, "%oror%|&&") || tok->astOperand2()->getKnownIntValue() < condExpr->astOperand2()->getKnownIntValue()) condExpr = tok; } return ChildrenToVisit::none; }); if (!Token::Match(condExpr, "<|<=") || !condExpr->isBinaryOp() || condExpr->astOperand1()->varId() != varid || !condExpr->astOperand2()->hasKnownIntValue()) return false; if (!incExpr || !incExpr->isUnaryOp("++") || incExpr->astOperand1()->varId() != varid) return false; stepValue = 1; if (condExpr->str() == "<") lastValue = condExpr->astOperand2()->getKnownIntValue() - 1; else lastValue = condExpr->astOperand2()->getKnownIntValue(); return true; } static const Token * getVariableInitExpression(const Variable * var) { if (!var) return nullptr; const Token *varDeclEndToken = var->declEndToken(); if (!varDeclEndToken) return nullptr; if (Token::Match(varDeclEndToken, "; %varid% =", var->declarationId())) return varDeclEndToken->tokAt(2)->astOperand2(); return varDeclEndToken->astOperand2(); } const Token* isInLoopCondition(const Token* tok) { const Token* top = tok->astTop(); return Token::Match(top->previous(), "for|while (") ? top : nullptr; } /// If tok2 comes after tok1 bool precedes(const Token * tok1, const Token * tok2) { if (tok1 == tok2) return false; if (!tok1) return false; if (!tok2) return true; return tok1->index() < tok2->index(); } /// If tok1 comes after tok2 bool succeeds(const Token* tok1, const Token* tok2) { if (tok1 == tok2) return false; if (!tok1) return false; if (!tok2) return true; return tok1->index() > tok2->index(); } bool isAliasOf(const Token *tok, nonneg int varid, bool* inconclusive) { if (tok->varId() == varid) return false; // NOLINTNEXTLINE(readability-use-anyofallof) - TODO: fix this / also Cppcheck false negative for (const ValueFlow::Value &val : tok->values()) { if (!val.isLocalLifetimeValue()) continue; if (val.tokvalue->varId() == varid) { if (val.isInconclusive()) { if (inconclusive) *inconclusive = true; else continue; } return true; } } return false; } bool isAliasOf(const Token* tok, const Token* expr, int* indirect) { const Token* r = nullptr; if (indirect) *indirect = 1; for (const ReferenceToken& ref : followAllReferences(tok)) { const bool pointer = astIsPointer(ref.token); r = findAstNode(expr, [&](const Token* childTok) { if (childTok->exprId() == 0) return false; if (ref.token != tok && expr->exprId() == childTok->exprId()) { if (indirect) *indirect = 0; return true; } for (const ValueFlow::Value& val : ref.token->values()) { if (val.isImpossible()) continue; if (val.isLocalLifetimeValue() || (pointer && val.isSymbolicValue() && val.intvalue == 0)) { if (findAstNode(val.tokvalue, [&](const Token* aliasTok) { return aliasTok != childTok && aliasTok->exprId() == childTok->exprId(); })) { return true; } } } return false; }); if (r) break; } return r; } static bool isAliased(const Token *startTok, const Token *endTok, nonneg int varid) { if (!precedes(startTok, endTok)) return false; for (const Token *tok = startTok; tok != endTok; tok = tok->next()) { if (Token::Match(tok, "= & %varid% ;", varid)) return true; if (isAliasOf(tok, varid)) return true; } return false; } bool exprDependsOnThis(const Token* expr, bool onVar, nonneg int depth) { if (!expr) return false; if (expr->str() == "this") return true; if (depth >= 1000) // Abort recursion to avoid stack overflow return true; ++depth; // calling nonstatic method? if (Token::Match(expr, "%name% (") && expr->function() && expr->function()->nestedIn && expr->function()->nestedIn->isClassOrStruct() && !expr->function()->isStatic()) { // is it a method of this? const Scope* fScope = expr->scope(); while (!fScope->functionOf && fScope->nestedIn) fScope = fScope->nestedIn; const Scope* classScope = fScope->functionOf; if (classScope && classScope->function) classScope = classScope->function->token->scope(); if (classScope && classScope->isClassOrStruct()) return contains(classScope->findAssociatedScopes(), expr->function()->nestedIn); return false; } if (onVar && expr->variable()) { const Variable* var = expr->variable(); return ((var->isPrivate() || var->isPublic() || var->isProtected()) && !var->isStatic()); } if (Token::simpleMatch(expr, ".")) return exprDependsOnThis(expr->astOperand1(), onVar, depth); return exprDependsOnThis(expr->astOperand1(), onVar, depth) || exprDependsOnThis(expr->astOperand2(), onVar, depth); } static bool hasUnknownVars(const Token* startTok) { bool result = false; visitAstNodes(startTok, [&](const Token* tok) { if (tok->varId() > 0 && !tok->variable()) { result = true; return ChildrenToVisit::done; } return ChildrenToVisit::op1_and_op2; }); return result; } bool isStructuredBindingVariable(const Variable* var) { if (!var) return false; const Token* tok = var->nameToken(); while (tok && Token::Match(tok->astParent(), "[|,|:")) tok = tok->astParent(); return tok && (tok->str() == "[" || Token::simpleMatch(tok->previous(), "] :")); // TODO: remove workaround when #11105 is fixed } /// This takes a token that refers to a variable and it will return the token /// to the expression that the variable is assigned to. If its not valid to /// make such substitution then it will return the original token. static const Token * followVariableExpression(const Settings& settings, const Token * tok, const Token * end = nullptr) { if (!tok) return tok; // Skip following variables that is across multiple files if (end && end->fileIndex() != tok->fileIndex()) return tok; // Skip array access if (Token::Match(tok, "%var% [")) return tok; // Skip pointer indirection if (tok->astParent() && tok->isUnaryOp("*")) return tok; // Skip following variables if it is used in an assignment if (Token::Match(tok->next(), "%assign%")) return tok; const Variable * var = tok->variable(); const Token * varTok = getVariableInitExpression(var); if (!varTok) return tok; if (hasUnknownVars(varTok)) return tok; if (var->isVolatile()) return tok; if (!var->isLocal() && !var->isConst()) return tok; if (var->isStatic() && !var->isConst()) return tok; if (var->isArgument()) return tok; if (isStructuredBindingVariable(var)) return tok; // assigning a floating point value to an integer does not preserve the value if (var->valueType() && var->valueType()->isIntegral() && varTok->valueType() && varTok->valueType()->isFloat()) return tok; const Token * lastTok = precedes(tok, end) ? end : tok; // If this is in a loop then check if variables are modified in the entire scope const Token * endToken = (isInLoopCondition(tok) || isInLoopCondition(varTok) || var->scope() != tok->scope()) ? var->scope()->bodyEnd : lastTok; if (!var->isConst() && (!precedes(varTok, endToken) || isVariableChanged(varTok, endToken, tok->varId(), false, settings))) return tok; if (precedes(varTok, endToken) && isAliased(varTok, endToken, tok->varId())) return tok; const Token* startToken = nextAfterAstRightmostLeaf(varTok); if (!startToken) startToken = varTok; if (varTok->exprId() == 0) { if (!varTok->isLiteral()) return tok; } else if (!precedes(startToken, endToken)) { return tok; } else if (findExpressionChanged(varTok, startToken, endToken, settings)) { return tok; } return varTok; } static void followVariableExpressionError(const Token *tok1, const Token *tok2, ErrorPath* errors) { if (!errors) return; if (!tok1) return; if (!tok2) return; ErrorPathItem item = std::make_pair(tok2, "'" + tok1->str() + "' is assigned value '" + tok2->expressionString() + "' here."); if (std::find(errors->cbegin(), errors->cend(), item) != errors->cend()) return; errors->push_back(std::move(item)); } SmallVector<ReferenceToken> followAllReferences(const Token* tok, bool temporary, bool inconclusive, ErrorPath errors, int depth) { struct ReferenceTokenLess { bool operator()(const ReferenceToken& x, const ReferenceToken& y) const { return x.token < y.token; } }; if (!tok) return {}; if (depth < 0) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } const Variable *var = tok->variable(); if (var && var->declarationId() == tok->varId()) { if (var->nameToken() == tok || isStructuredBindingVariable(var)) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } if (var->isReference() || var->isRValueReference()) { const Token * const varDeclEndToken = var->declEndToken(); if (!varDeclEndToken) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } if (var->isArgument()) { errors.emplace_back(varDeclEndToken, "Passed to reference."); SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } if (Token::simpleMatch(varDeclEndToken, "=")) { if (astHasToken(varDeclEndToken, tok)) return {}; errors.emplace_back(varDeclEndToken, "Assigned to reference."); const Token *vartok = varDeclEndToken->astOperand2(); if (vartok == tok || (!temporary && isTemporary(vartok, nullptr, true) && (var->isConst() || var->isRValueReference()))) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } if (vartok) return followAllReferences(vartok, temporary, inconclusive, std::move(errors), depth - 1); } } } else if (Token::simpleMatch(tok, "?") && Token::simpleMatch(tok->astOperand2(), ":")) { std::set<ReferenceToken, ReferenceTokenLess> result; const Token* tok2 = tok->astOperand2(); auto refs = followAllReferences(tok2->astOperand1(), temporary, inconclusive, errors, depth - 1); result.insert(refs.cbegin(), refs.cend()); refs = followAllReferences(tok2->astOperand2(), temporary, inconclusive, errors, depth - 1); result.insert(refs.cbegin(), refs.cend()); if (!inconclusive && result.size() != 1) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } if (!result.empty()) { SmallVector<ReferenceToken> refs_result; refs_result.insert(refs_result.end(), result.cbegin(), result.cend()); return refs_result; } } else if (tok->previous() && tok->previous()->function() && Token::Match(tok->previous(), "%name% (")) { const Function *f = tok->previous()->function(); if (!Function::returnsReference(f)) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } std::set<ReferenceToken, ReferenceTokenLess> result; std::vector<const Token*> returns = Function::findReturns(f); for (const Token* returnTok : returns) { if (returnTok == tok) continue; for (const ReferenceToken& rt : followAllReferences(returnTok, temporary, inconclusive, errors, depth - returns.size())) { const Variable* argvar = rt.token->variable(); if (!argvar) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } if (argvar->isArgument() && (argvar->isReference() || argvar->isRValueReference())) { const int n = getArgumentPos(argvar, f); if (n < 0) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } std::vector<const Token*> args = getArguments(tok->previous()); if (n >= args.size()) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } const Token* argTok = args[n]; ErrorPath er = errors; er.emplace_back(returnTok, "Return reference."); er.emplace_back(tok->previous(), "Called function passing '" + argTok->expressionString() + "'."); auto refs = followAllReferences(argTok, temporary, inconclusive, std::move(er), depth - returns.size()); result.insert(refs.cbegin(), refs.cend()); if (!inconclusive && result.size() > 1) { SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } } } } if (!result.empty()) { SmallVector<ReferenceToken> refs_result; refs_result.insert(refs_result.end(), result.cbegin(), result.cend()); return refs_result; } } SmallVector<ReferenceToken> refs_result; refs_result.emplace_back(tok, std::move(errors)); return refs_result; } const Token* followReferences(const Token* tok, ErrorPath* errors) { if (!tok) return nullptr; auto refs = followAllReferences(tok, true, false); if (refs.size() == 1) { if (errors) *errors = std::move(refs.front().errors); return refs.front().token; } return nullptr; } static bool isSameLifetime(const Token * const tok1, const Token * const tok2) { ValueFlow::Value v1 = ValueFlow::getLifetimeObjValue(tok1); if (!v1.isLifetimeValue()) return false; ValueFlow::Value v2 = ValueFlow::getLifetimeObjValue(tok2); if (!v2.isLifetimeValue()) return false; return v1.tokvalue == v2.tokvalue; } static bool compareKnownValue(const Token * const tok1, const Token * const tok2, const std::function<bool(const ValueFlow::Value&, const ValueFlow::Value&, bool)> &compare) { static const auto isKnownFn = std::mem_fn(&ValueFlow::Value::isKnown); const auto v1 = std::find_if(tok1->values().cbegin(), tok1->values().cend(), isKnownFn); if (v1 == tok1->values().end()) { return false; } if (v1->isNonValue() || v1->isContainerSizeValue() || v1->isSymbolicValue()) return false; const auto v2 = std::find_if(tok2->values().cbegin(), tok2->values().cend(), isKnownFn); if (v2 == tok2->values().end()) { return false; } if (v1->valueType != v2->valueType) { return false; } const bool sameLifetime = isSameLifetime(tok1, tok2); return compare(*v1, *v2, sameLifetime); } bool isEqualKnownValue(const Token * const tok1, const Token * const tok2) { return compareKnownValue(tok1, tok2, [&](const ValueFlow::Value& v1, const ValueFlow::Value& v2, bool sameLifetime) { bool r = v1.equalValue(v2); if (v1.isIteratorValue()) { r &= sameLifetime; } return r; }); } static inline bool isDifferentKnownValues(const Token * const tok1, const Token * const tok2) { return compareKnownValue(tok1, tok2, [&](const ValueFlow::Value& v1, const ValueFlow::Value& v2, bool sameLifetime) { bool r = v1.equalValue(v2); if (v1.isIteratorValue()) { r &= sameLifetime; } return !r; }); } static inline bool isSameConstantValue(bool macro, const Token* tok1, const Token* tok2) { if (tok1 == nullptr || tok2 == nullptr) return false; auto adjustForCast = [](const Token* tok) { if (tok->astOperand2() && Token::Match(tok->previous(), "%type% (|{") && tok->previous()->isStandardType()) return tok->astOperand2(); return tok; }; tok1 = adjustForCast(tok1); if (!tok1->isNumber() && !tok1->enumerator()) return false; tok2 = adjustForCast(tok2); if (!tok2->isNumber() && !tok2->enumerator()) return false; if (macro && (tok1->isExpandedMacro() || tok2->isExpandedMacro() || tok1->isTemplateArg() || tok2->isTemplateArg())) return false; const ValueType * v1 = tok1->valueType(); const ValueType * v2 = tok2->valueType(); if (!v1 || !v2 || v1->sign != v2->sign || v1->type != v2->type || v1->pointer != v2->pointer) return false; return isEqualKnownValue(tok1, tok2); } static bool isForLoopCondition(const Token * const tok) { if (!tok) return false; const Token *const parent = tok->astParent(); return Token::simpleMatch(parent, ";") && parent->astOperand1() == tok && Token::simpleMatch(parent->astParent(), ";") && Token::simpleMatch(parent->astParent()->astParent(), "(") && parent->astParent()->astParent()->astOperand1()->str() == "for"; } static bool isForLoopIncrement(const Token* const tok) { if (!tok) return false; const Token *const parent = tok->astParent(); return Token::simpleMatch(parent, ";") && parent->astOperand2() == tok && Token::simpleMatch(parent->astParent(), ";") && Token::simpleMatch(parent->astParent()->astParent(), "(") && parent->astParent()->astParent()->astOperand1()->str() == "for"; } bool isUsedAsBool(const Token* const tok, const Settings& settings) { if (!tok) return false; if (isForLoopIncrement(tok)) return false; if (astIsBool(tok)) return true; if (Token::Match(tok, "!|&&|%oror%|%comp%")) return true; const Token* parent = tok->astParent(); if (!parent) return false; if (Token::simpleMatch(parent, "[")) return false; if (parent->isUnaryOp("*")) return false; if (Token::simpleMatch(parent, ".")) { if (astIsRHS(tok)) return isUsedAsBool(parent, settings); return false; } if (Token::Match(parent, "&&|!|%oror%")) return true; if (parent->isCast()) return !Token::simpleMatch(parent->astOperand1(), "dynamic_cast") && isUsedAsBool(parent, settings); if (parent->isUnaryOp("*")) return isUsedAsBool(parent, settings); if (Token::Match(parent, "==|!=") && (tok->astSibling()->isNumber() || tok->astSibling()->isKeyword()) && tok->astSibling()->hasKnownIntValue() && tok->astSibling()->values().front().intvalue == 0) return true; if (parent->str() == "(" && astIsRHS(tok) && Token::Match(parent->astOperand1(), "if|while")) return true; if (Token::simpleMatch(parent, "?") && astIsLHS(tok)) return true; if (isForLoopCondition(tok)) return true; if (!Token::Match(parent, "%cop%") && !(parent->str() == "(" && tok == parent->astOperand1())) { if (parent->str() == "," && parent->isInitComma()) return false; std::vector<ValueType> vtParents = getParentValueTypes(tok, settings); return std::any_of(vtParents.cbegin(), vtParents.cend(), [&](const ValueType& vt) { return vt.pointer == 0 && vt.type == ValueType::BOOL; }); } return false; } bool compareTokenFlags(const Token* tok1, const Token* tok2, bool macro) { if (macro) { if (tok1->isExpandedMacro() != tok2->isExpandedMacro()) return false; if (tok1->isExpandedMacro()) { // both are macros if (tok1->getMacroName() != tok2->getMacroName()) return false; if (tok1->astParent() && tok2->astParent() && tok1->astParent()->isExpandedMacro() && tok1->astParent()->getMacroName() == tok2->astParent()->getMacroName()) return false; } if (tok1->isTemplateArg() || tok2->isTemplateArg()) return false; } if (tok1->isComplex() != tok2->isComplex()) return false; if (tok1->isLong() != tok2->isLong()) return false; if (tok1->isUnsigned() != tok2->isUnsigned()) return false; if (tok1->isSigned() != tok2->isSigned()) return false; return true; } static bool astIsBoolLike(const Token* tok, const Settings& settings) { return astIsBool(tok) || isUsedAsBool(tok, settings); } bool isSameExpression(bool macro, const Token *tok1, const Token *tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors) { if (tok1 == tok2) return true; if (tok1 == nullptr || tok2 == nullptr) return false; // tokens needs to be from the same TokenList so no need check standard on both of them if (tok1->isCpp()) { if (tok1->str() == "." && tok1->astOperand1() && tok1->astOperand1()->str() == "this") tok1 = tok1->astOperand2(); if (tok2->str() == "." && tok2->astOperand1() && tok2->astOperand1()->str() == "this") tok2 = tok2->astOperand2(); } // Skip double not if (Token::simpleMatch(tok1, "!") && Token::simpleMatch(tok1->astOperand1(), "!") && !Token::simpleMatch(tok1->astParent(), "=") && astIsBoolLike(tok2, settings)) { return isSameExpression(macro, tok1->astOperand1()->astOperand1(), tok2, settings, pure, followVar, errors); } if (Token::simpleMatch(tok2, "!") && Token::simpleMatch(tok2->astOperand1(), "!") && !Token::simpleMatch(tok2->astParent(), "=") && astIsBoolLike(tok1, settings)) { return isSameExpression(macro, tok1, tok2->astOperand1()->astOperand1(), settings, pure, followVar, errors); } const bool tok_str_eq = tok1->str() == tok2->str(); if (!tok_str_eq && isDifferentKnownValues(tok1, tok2)) return false; const Token *followTok1 = tok1, *followTok2 = tok2; while (Token::simpleMatch(followTok1, "::") && followTok1->astOperand2()) followTok1 = followTok1->astOperand2(); while (Token::simpleMatch(followTok2, "::") && followTok2->astOperand2()) followTok2 = followTok2->astOperand2(); if (isSameConstantValue(macro, followTok1, followTok2)) return true; // Follow variable if (followVar && !tok_str_eq && (followTok1->varId() || followTok2->varId() || followTok1->enumerator() || followTok2->enumerator())) { const Token * varTok1 = followVariableExpression(settings, followTok1, followTok2); if ((varTok1->str() == followTok2->str()) || isSameConstantValue(macro, varTok1, followTok2)) { followVariableExpressionError(followTok1, varTok1, errors); return isSameExpression(macro, varTok1, followTok2, settings, true, followVar, errors); } const Token * varTok2 = followVariableExpression(settings, followTok2, followTok1); if ((followTok1->str() == varTok2->str()) || isSameConstantValue(macro, followTok1, varTok2)) { followVariableExpressionError(followTok2, varTok2, errors); return isSameExpression(macro, followTok1, varTok2, settings, true, followVar, errors); } if ((varTok1->str() == varTok2->str()) || isSameConstantValue(macro, varTok1, varTok2)) { followVariableExpressionError(tok1, varTok1, errors); followVariableExpressionError(tok2, varTok2, errors); return isSameExpression(macro, varTok1, varTok2, settings, true, followVar, errors); } } // Follow references if (!tok_str_eq) { const Token* refTok1 = followReferences(tok1, errors); const Token* refTok2 = followReferences(tok2, errors); if (refTok1 != tok1 || refTok2 != tok2) { if (refTok1 && !refTok1->varId() && refTok2 && !refTok2->varId()) { // complex reference expression const Token *start = refTok1, *end = refTok2; if (!precedes(start, end)) std::swap(start, end); if (findExpressionChanged(start, start, end, settings)) return false; } return isSameExpression(macro, refTok1, refTok2, settings, pure, followVar, errors); } } if (tok1->varId() != tok2->varId() || !tok_str_eq || tok1->originalName() != tok2->originalName()) { if ((Token::Match(tok1,"<|>") && Token::Match(tok2,"<|>")) || (Token::Match(tok1,"<=|>=") && Token::Match(tok2,"<=|>="))) { return isSameExpression(macro, tok1->astOperand1(), tok2->astOperand2(), settings, pure, followVar, errors) && isSameExpression(macro, tok1->astOperand2(), tok2->astOperand1(), settings, pure, followVar, errors); } const Token* condTok = nullptr; const Token* exprTok = nullptr; if (Token::Match(tok1, "==|!=")) { condTok = tok1; exprTok = tok2; } else if (Token::Match(tok2, "==|!=")) { condTok = tok2; exprTok = tok1; } if (condTok && condTok->astOperand1() && condTok->astOperand2() && !Token::Match(exprTok, "%comp%")) { const Token* varTok1 = nullptr; const Token* varTok2 = exprTok; const ValueFlow::Value* value = nullptr; if (condTok->astOperand1()->hasKnownIntValue()) { value = &condTok->astOperand1()->values().front(); varTok1 = condTok->astOperand2(); } else if (condTok->astOperand2()->hasKnownIntValue()) { value = &condTok->astOperand2()->values().front(); varTok1 = condTok->astOperand1(); } const bool exprIsNot = Token::simpleMatch(exprTok, "!"); if (exprIsNot) varTok2 = exprTok->astOperand1(); bool compare = false; if (value) { if (value->intvalue == 0 && exprIsNot && Token::simpleMatch(condTok, "==")) { compare = true; } else if (value->intvalue == 0 && !exprIsNot && Token::simpleMatch(condTok, "!=")) { compare = true; } else if (value->intvalue != 0 && exprIsNot && Token::simpleMatch(condTok, "!=")) { compare = true; } else if (value->intvalue != 0 && !exprIsNot && Token::simpleMatch(condTok, "==")) { compare = true; } } if (compare && astIsBoolLike(varTok1, settings) && astIsBoolLike(varTok2, settings)) return isSameExpression(macro, varTok1, varTok2, settings, pure, followVar, errors); } return false; } if (!compareTokenFlags(tok1, tok2, macro)) return false; if (pure && tok1->isName() && tok1->strAt(1) == "(" && tok1->str() != "sizeof" && !(tok1->variable() && tok1 == tok1->variable()->nameToken())) { if (!tok1->function()) { if (Token::simpleMatch(tok1->previous(), ".")) { const Token *lhs = tok1->previous(); while (Token::Match(lhs, "(|.|[")) lhs = lhs->astOperand1(); if (!lhs) return false; const bool lhsIsConst = (lhs->variable() && lhs->variable()->isConst()) || (lhs->valueType() && lhs->valueType()->constness > 0) || (Token::Match(lhs, "%var% . %name% (") && settings.library.isFunctionConst(lhs->tokAt(2))); if (!lhsIsConst) return false; } else { const Token * ftok = tok1; if (!settings.library.isFunctionConst(ftok) && !ftok->isAttributeConst() && !ftok->isAttributePure()) return false; } } else { if (!tok1->function()->isConst() && !tok1->function()->isAttributeConst() && !tok1->function()->isAttributePure()) return false; } } // templates/casts if ((tok1->next() && tok1->linkAt(1) && Token::Match(tok1, "%name% <")) || (tok2->next() && tok2->linkAt(1) && Token::Match(tok2, "%name% <"))) { // non-const template function that is not a dynamic_cast => return false if (pure && Token::simpleMatch(tok1->linkAt(1), "> (") && !(tok1->function() && tok1->function()->isConst()) && tok1->str() != "dynamic_cast") return false; // some template/cast stuff.. check that the template arguments are same const Token *t1 = tok1->next(); const Token *t2 = tok2->next(); const Token *end1 = t1->link(); const Token *end2 = t2->link(); while (t1 && t2 && t1 != end1 && t2 != end2) { if (t1->str() != t2->str() || !compareTokenFlags(t1, t2, macro)) return false; t1 = t1->next(); t2 = t2->next(); } if (t1 != end1 || t2 != end2) return false; } if (tok1->tokType() == Token::eIncDecOp || tok1->isAssignmentOp()) return false; // bailout when we see ({..}) if (tok1->str() == "{") return false; // cast => assert that the casts are equal if (tok1->str() == "(" && tok1->previous() && !tok1->previous()->isName() && !(tok1->strAt(-1) == ">" && tok1->linkAt(-1))) { const Token *t1 = tok1->next(); const Token *t2 = tok2->next(); while (t1 && t2 && t1->str() == t2->str() && compareTokenFlags(t1, t2, macro) && (t1->isName() || t1->str() == "*")) { t1 = t1->next(); t2 = t2->next(); } if (!t1 || !t2 || t1->str() != ")" || t2->str() != ")") return false; } bool noncommutativeEquals = isSameExpression(macro, tok1->astOperand1(), tok2->astOperand1(), settings, pure, followVar, errors); noncommutativeEquals = noncommutativeEquals && isSameExpression(macro, tok1->astOperand2(), tok2->astOperand2(), settings, pure, followVar, errors); if (noncommutativeEquals) return true; // in c++, a+b might be different to b+a, depending on the type of a and b if (tok1->isCpp() && tok1->str() == "+" && tok1->isBinaryOp()) { const ValueType* vt1 = tok1->astOperand1()->valueType(); const ValueType* vt2 = tok1->astOperand2()->valueType(); if (!(vt1 && (vt1->type >= ValueType::VOID || vt1->pointer) && vt2 && (vt2->type >= ValueType::VOID || vt2->pointer))) return false; } const bool commutative = tok1->isBinaryOp() && Token::Match(tok1, "%or%|%oror%|+|*|&|&&|^|==|!="); bool commutativeEquals = commutative && isSameExpression(macro, tok1->astOperand2(), tok2->astOperand1(), settings, pure, followVar, errors); commutativeEquals = commutativeEquals && isSameExpression(macro, tok1->astOperand1(), tok2->astOperand2(), settings, pure, followVar, errors); return commutativeEquals; } static bool isZeroBoundCond(const Token * const cond) { if (cond == nullptr) return false; // Assume unsigned // TODO: Handle reverse conditions const bool isZero = cond->astOperand2()->getValue(0); if (cond->str() == "==" || cond->str() == ">=") return isZero; if (cond->str() == "<=") return true; if (cond->str() == "<") return !isZero; if (cond->str() == ">") return false; return false; } bool isOppositeCond(bool isNot, const Token * const cond1, const Token * const cond2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors) { if (!cond1 || !cond2) return false; if (isSameExpression(true, cond1, cond2, settings, pure, followVar, errors)) return false; if (!isNot && cond1->str() == "&&" && cond2->str() == "&&") { for (const Token* tok1: { cond1->astOperand1(), cond1->astOperand2() }) { for (const Token* tok2: { cond2->astOperand1(), cond2->astOperand2() }) { if (isSameExpression(true, tok1, tok2, settings, pure, followVar, errors)) { if (isOppositeCond(isNot, tok1->astSibling(), tok2->astSibling(), settings, pure, followVar, errors)) return true; } } } } if (cond1->str() != cond2->str() && (cond1->str() == "||" || cond2->str() == "||")) { const Token* orCond = nullptr; const Token* otherCond = nullptr; if (cond1->str() == "||") { orCond = cond1; otherCond = cond2; } if (cond2->str() == "||") { orCond = cond2; otherCond = cond1; } return isOppositeCond(isNot, orCond->astOperand1(), otherCond, settings, pure, followVar, errors) && isOppositeCond(isNot, orCond->astOperand2(), otherCond, settings, pure, followVar, errors); } if (cond1->str() == "!") { if (cond2->str() == "!=") { if (cond2->astOperand1() && cond2->astOperand1()->str() == "0") return isSameExpression(true, cond1->astOperand1(), cond2->astOperand2(), settings, pure, followVar, errors); if (cond2->astOperand2() && cond2->astOperand2()->str() == "0") return isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors); } if (!isUsedAsBool(cond2, settings)) return false; return isSameExpression(true, cond1->astOperand1(), cond2, settings, pure, followVar, errors); } if (cond2->str() == "!") return isOppositeCond(isNot, cond2, cond1, settings, pure, followVar, errors); if (!isNot) { if (cond1->str() == "==" && cond2->str() == "==") { if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors)) return isDifferentKnownValues(cond1->astOperand2(), cond2->astOperand2()); if (isSameExpression(true, cond1->astOperand2(), cond2->astOperand2(), settings, pure, followVar, errors)) return isDifferentKnownValues(cond1->astOperand1(), cond2->astOperand1()); } // TODO: Handle reverse conditions if (Library::isContainerYield(cond1, Library::Container::Yield::EMPTY, "empty") && Library::isContainerYield(cond2->astOperand1(), Library::Container::Yield::SIZE, "size") && isSameExpression(true, cond1->astOperand1()->astOperand1(), cond2->astOperand1()->astOperand1()->astOperand1(), settings, pure, followVar, errors)) { return !isZeroBoundCond(cond2); } if (Library::isContainerYield(cond2, Library::Container::Yield::EMPTY, "empty") && Library::isContainerYield(cond1->astOperand1(), Library::Container::Yield::SIZE, "size") && isSameExpression(true, cond2->astOperand1()->astOperand1(), cond1->astOperand1()->astOperand1()->astOperand1(), settings, pure, followVar, errors)) { return !isZeroBoundCond(cond1); } } if (!cond1->isComparisonOp() || !cond2->isComparisonOp()) return false; const std::string &comp1 = cond1->str(); // condition found .. get comparator std::string comp2; if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand1(), settings, pure, followVar, errors) && isSameExpression(true, cond1->astOperand2(), cond2->astOperand2(), settings, pure, followVar, errors)) { comp2 = cond2->str(); } else if (isSameExpression(true, cond1->astOperand1(), cond2->astOperand2(), settings, pure, followVar, errors) && isSameExpression(true, cond1->astOperand2(), cond2->astOperand1(), settings, pure, followVar, errors)) { comp2 = cond2->str(); if (comp2[0] == '>') comp2[0] = '<'; else if (comp2[0] == '<') comp2[0] = '>'; } if (!isNot && comp2.empty()) { const Token *expr1 = nullptr, *value1 = nullptr, *expr2 = nullptr, *value2 = nullptr; std::string op1 = cond1->str(), op2 = cond2->str(); if (cond1->astOperand2()->hasKnownIntValue()) { expr1 = cond1->astOperand1(); value1 = cond1->astOperand2(); } else if (cond1->astOperand1()->hasKnownIntValue()) { expr1 = cond1->astOperand2(); value1 = cond1->astOperand1(); if (op1[0] == '>') op1[0] = '<'; else if (op1[0] == '<') op1[0] = '>'; } if (cond2->astOperand2()->hasKnownIntValue()) { expr2 = cond2->astOperand1(); value2 = cond2->astOperand2(); } else if (cond2->astOperand1()->hasKnownIntValue()) { expr2 = cond2->astOperand2(); value2 = cond2->astOperand1(); if (op2[0] == '>') op2[0] = '<'; else if (op2[0] == '<') op2[0] = '>'; } if (!expr1 || !value1 || !expr2 || !value2) { return false; } if (!isSameExpression(true, expr1, expr2, settings, pure, followVar, errors)) return false; const ValueFlow::Value &rhsValue1 = value1->values().front(); const ValueFlow::Value &rhsValue2 = value2->values().front(); if (op1 == "<" || op1 == "<=") return (op2 == "==" || op2 == ">" || op2 == ">=") && (rhsValue1.intvalue < rhsValue2.intvalue); if (op1 == ">=" || op1 == ">") return (op2 == "==" || op2 == "<" || op2 == "<=") && (rhsValue1.intvalue > rhsValue2.intvalue); return false; } // is condition opposite? return ((comp1 == "==" && comp2 == "!=") || (comp1 == "!=" && comp2 == "==") || (comp1 == "<" && comp2 == ">=") || (comp1 == "<=" && comp2 == ">") || (comp1 == ">" && comp2 == "<=") || (comp1 == ">=" && comp2 == "<") || (!isNot && ((comp1 == "<" && comp2 == ">") || (comp1 == ">" && comp2 == "<") || (comp1 == "==" && (comp2 == "!=" || comp2 == ">" || comp2 == "<")) || ((comp1 == "!=" || comp1 == ">" || comp1 == "<") && comp2 == "==") ))); } bool isOppositeExpression(const Token * const tok1, const Token * const tok2, const Settings& settings, bool pure, bool followVar, ErrorPath* errors) { if (!tok1 || !tok2) return false; if (isOppositeCond(true, tok1, tok2, settings, pure, followVar, errors)) return true; if (tok1->isUnaryOp("-") && !(tok2->astParent() && tok2->astParent()->tokType() == Token::eBitOp)) return isSameExpression(true, tok1->astOperand1(), tok2, settings, pure, followVar, errors); if (tok2->isUnaryOp("-") && !(tok2->astParent() && tok2->astParent()->tokType() == Token::eBitOp)) return isSameExpression(true, tok2->astOperand1(), tok1, settings, pure, followVar, errors); return false; } static bool functionModifiesArguments(const Function* f) { return std::any_of(f->argumentList.cbegin(), f->argumentList.cend(), [](const Variable& var) { if (var.isReference() || var.isPointer()) return !var.isConst(); return true; }); } bool isConstFunctionCall(const Token* ftok, const Library& library) { if (isUnevaluated(ftok)) return true; if (!Token::Match(ftok, "%name% (")) return false; if (const Function* f = ftok->function()) { if (f->isAttributePure() || f->isAttributeConst()) return true; // Any modified arguments if (functionModifiesArguments(f)) return false; if (Function::returnsVoid(f)) return false; // Member function call if (Token::simpleMatch(ftok->previous(), ".") || exprDependsOnThis(ftok->next())) { if (f->isConst()) return true; // Check for const overloaded function that just return the const version if (!Function::returnsConst(f)) { std::vector<const Function*> fs = f->getOverloadedFunctions(); if (std::any_of(fs.cbegin(), fs.cend(), [&](const Function* g) { if (f == g) return false; if (f->argumentList.size() != g->argumentList.size()) return false; if (functionModifiesArguments(g)) return false; if (g->isConst() && Function::returnsConst(g)) return true; return false; })) return true; } return false; } if (f->argumentList.empty()) return f->isConstexpr(); } else if (Token::Match(ftok->previous(), ". %name% (") && ftok->previous()->originalName() != "->" && astIsSmartPointer(ftok->previous()->astOperand1())) { return Token::Match(ftok, "get|get_deleter ( )"); } else if (Token::Match(ftok->previous(), ". %name% (") && astIsContainer(ftok->previous()->astOperand1())) { const Library::Container* container = ftok->previous()->astOperand1()->valueType()->container; if (!container) return false; if (container->getYield(ftok->str()) != Library::Container::Yield::NO_YIELD) return true; if (container->getAction(ftok->str()) == Library::Container::Action::FIND_CONST) return true; return false; } else if (const Library::Function* lf = library.getFunction(ftok)) { if (lf->ispure) return true; if (lf->containerYield != Library::Container::Yield::NO_YIELD) return true; if (lf->containerAction == Library::Container::Action::FIND_CONST) return true; return false; } else { const bool memberFunction = Token::Match(ftok->previous(), ". %name% ("); bool constMember = !memberFunction; if (Token::Match(ftok->tokAt(-2), "%var% . %name% (")) { const Variable* var = ftok->tokAt(-2)->variable(); if (var) constMember = var->isConst(); } // TODO: Only check const on lvalues std::vector<const Token*> args = getArguments(ftok); if (args.empty()) return false; return constMember && std::all_of(args.cbegin(), args.cend(), [](const Token* tok) { const Variable* var = tok->variable(); if (var) return var->isConst(); return false; }); } return true; } bool isConstExpression(const Token *tok, const Library& library) { if (!tok) return true; if (tok->variable() && tok->variable()->isVolatile()) return false; if (tok->isName() && tok->strAt(1) == "(") { if (!isConstFunctionCall(tok, library)) return false; } if (tok->tokType() == Token::eIncDecOp) return false; if (tok->isAssignmentOp()) return false; if (isLikelyStreamRead(tok)) return false; // bailout when we see ({..}) if (tok->str() == "{") return false; return isConstExpression(tok->astOperand1(), library) && isConstExpression(tok->astOperand2(), library); } bool isWithoutSideEffects(const Token* tok, bool checkArrayAccess, bool checkReference) { if (!tok) return true; if (!tok->isCpp()) return true; while (tok && tok->astOperand2() && tok->astOperand2()->str() != "(") tok = tok->astOperand2(); if (tok && tok->varId()) { const Variable* var = tok->variable(); return var && ((!var->isClass() && (checkReference || !var->isReference())) || var->isPointer() || (checkArrayAccess ? var->isStlType() && !var->isStlType(CheckClass::stl_containers_not_const) : var->isStlType())); } return true; } bool isUniqueExpression(const Token* tok) { if (!tok) return true; if (tok->function()) { const Function * fun = tok->function(); const Scope * scope = fun->nestedIn; if (!scope) return true; const std::string returnType = fun->retType ? fun->retType->name() : fun->retDef->stringifyList(fun->tokenDef); if (!std::all_of(scope->functionList.begin(), scope->functionList.end(), [&](const Function& f) { if (f.type != Function::eFunction) return true; const std::string freturnType = f.retType ? f.retType->name() : f.retDef->stringifyList(f.returnDefEnd()); return f.argumentList.size() != fun->argumentList.size() || returnType != freturnType || f.name() == fun->name(); })) return false; } else if (tok->variable()) { const Variable * var = tok->variable(); const Scope * scope = var->scope(); if (!scope) return true; const Type * varType = var->type(); // Iterate over the variables in scope and the parameters of the function if possible const Function * fun = scope->function; auto pred = [=](const Variable& v) { if (varType) return v.type() && v.type()->name() == varType->name() && v.name() != var->name(); return v.isFloatingType() == var->isFloatingType() && v.isEnumType() == var->isEnumType() && v.isClass() == var->isClass() && v.isArray() == var->isArray() && v.isPointer() == var->isPointer() && v.name() != var->name(); }; if (std::any_of(scope->varlist.cbegin(), scope->varlist.cend(), pred)) return false; if (fun) { if (std::any_of(fun->argumentList.cbegin(), fun->argumentList.cend(), pred)) return false; } } else if (!isUniqueExpression(tok->astOperand1())) { return false; } return isUniqueExpression(tok->astOperand2()); } static bool isEscaped(const Token* tok, bool functionsScope, const Library& library) { if (library.isnoreturn(tok)) return true; if (functionsScope) return Token::simpleMatch(tok, "throw"); return Token::Match(tok, "return|throw"); } static bool isEscapedOrJump(const Token* tok, bool functionsScope, const Library& library) { if (library.isnoreturn(tok)) return true; if (functionsScope) return Token::simpleMatch(tok, "throw"); return Token::Match(tok, "return|goto|throw|continue|break"); } bool isEscapeFunction(const Token* ftok, const Library* library) { if (!Token::Match(ftok, "%name% (")) return false; const Function* function = ftok->function(); if (function) { if (function->isEscapeFunction()) return true; if (function->isAttributeNoreturn()) return true; } else if (library) { if (library->isnoreturn(ftok)) return true; } return false; } static bool hasNoreturnFunction(const Token* tok, const Library& library, const Token** unknownFunc) { if (!tok) return false; const Token* ftok = tok->str() == "(" ? tok->previous() : nullptr; while (Token::simpleMatch(ftok, "(")) ftok = ftok->astOperand1(); if (ftok) { const Function * function = ftok->function(); if (function) { if (function->isEscapeFunction()) return true; if (function->isAttributeNoreturn()) return true; } else if (library.isnoreturn(ftok)) { return true; } else if (Token::Match(ftok, "exit|abort")) { return true; } if (unknownFunc && !function && library.functions().count(library.getFunctionName(ftok)) == 0) *unknownFunc = ftok; return false; } if (tok->isConstOp()) { return hasNoreturnFunction(tok->astOperand1(), library, unknownFunc) || hasNoreturnFunction(tok->astOperand2(), library, unknownFunc); } return false; } bool isReturnScope(const Token* const endToken, const Library& library, const Token** unknownFunc, bool functionScope) { if (!endToken || endToken->str() != "}") return false; const Token *prev = endToken->previous(); while (prev && Token::simpleMatch(prev->previous(), "; ;")) prev = prev->previous(); if (prev && Token::simpleMatch(prev->previous(), "} ;")) prev = prev->previous(); if (Token::simpleMatch(prev, "}")) { if (Token::simpleMatch(prev->link()->tokAt(-2), "} else {")) return isReturnScope(prev, library, unknownFunc, functionScope) && isReturnScope(prev->link()->tokAt(-2), library, unknownFunc, functionScope); // TODO: Check all cases if (!functionScope && Token::simpleMatch(prev->link()->previous(), ") {") && Token::simpleMatch(prev->link()->linkAt(-1)->previous(), "switch (") && !Token::findsimplematch(prev->link(), "break", prev)) { return isReturnScope(prev, library, unknownFunc, functionScope); } if (isEscaped(prev->link()->astTop(), functionScope, library)) return true; if (Token::Match(prev->link()->previous(), "[;{}] {")) return isReturnScope(prev, library, unknownFunc, functionScope); } else if (Token::simpleMatch(prev, ";")) { if (prev->tokAt(-2) && hasNoreturnFunction(prev->tokAt(-2)->astTop(), library, unknownFunc)) return true; // Unknown symbol if (Token::Match(prev->tokAt(-2), ";|}|{ %name% ;") && prev->previous()->isIncompleteVar()) { if (unknownFunc) *unknownFunc = prev->previous(); return false; } if (Token::simpleMatch(prev->previous(), ") ;") && prev->linkAt(-1) && isEscaped(prev->linkAt(-1)->astTop(), functionScope, library)) return true; if (isEscaped(prev->previous()->astTop(), functionScope, library)) return true; // return/goto statement prev = prev->previous(); while (prev && !Token::Match(prev, ";|{|}") && !isEscapedOrJump(prev, functionScope, library)) prev = prev->previous(); return prev && prev->isName(); } return false; } bool isWithinScope(const Token* tok, const Variable* var, Scope::ScopeType type) { if (!tok || !var) return false; const Scope* scope = tok->scope(); while (scope && scope != var->scope()) { if (scope->type == type) return true; scope = scope->nestedIn; } return false; } bool isVariableChangedByFunctionCall(const Token *tok, int indirect, nonneg int varid, const Settings &settings, bool *inconclusive) { if (!tok) return false; if (tok->varId() == varid) return isVariableChangedByFunctionCall(tok, indirect, settings, inconclusive); return isVariableChangedByFunctionCall(tok->astOperand1(), indirect, varid, settings, inconclusive) || isVariableChangedByFunctionCall(tok->astOperand2(), indirect, varid, settings, inconclusive); } bool isScopeBracket(const Token* tok) { if (!Token::Match(tok, "{|}")) return false; if (!tok->scope()) return false; if (tok->str() == "{") return tok->scope()->bodyStart == tok; if (tok->str() == "}") return tok->scope()->bodyEnd == tok; return false; } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* getTokenArgumentFunctionImpl(T* tok, int& argn) { argn = -1; { T* parent = tok->astParent(); if (parent && (parent->isUnaryOp("&") || parent->isIncDecOp())) parent = parent->astParent(); while (parent && parent->isCast()) parent = parent->astParent(); if (Token::Match(parent, "[+-]") && parent->valueType() && parent->valueType()->pointer) parent = parent->astParent(); // passing variable to subfunction? if (Token::Match(parent, "[[(,{.]") || Token::Match(parent, "%oror%|&&") || (parent && parent->isUnaryOp("*"))) ; else if (Token::simpleMatch(parent, ":")) { while (Token::Match(parent, "[?:]")) parent = parent->astParent(); while (Token::simpleMatch(parent, ",")) parent = parent->astParent(); if (!parent || parent->str() != "(") return nullptr; } else return nullptr; } T* argtok = tok; while (argtok && argtok->astParent() && (!Token::Match(argtok->astParent(), ",|(|{") || argtok->astParent()->isCast())) { argtok = argtok->astParent(); } if (!argtok) return nullptr; if (Token::simpleMatch(argtok, ",")) argtok = argtok->astOperand1(); tok = argtok; while (Token::Match(tok->astParent(), ",|(|{")) { tok = tok->astParent(); if (Token::Match(tok, "(|{")) break; } argn = getArgumentPos(tok, argtok); if (argn == -1) return nullptr; if (!Token::Match(tok, "{|(")) return nullptr; if (tok->astOperand2()) tok = tok->astOperand1(); while (tok && (tok->isUnaryOp("*") || tok->str() == "[")) tok = tok->astOperand1(); if (Token::Match(tok, ". * %name%")) // bailout for pointer to member return tok->tokAt(2); while (Token::simpleMatch(tok, ".")) tok = tok->astOperand2(); while (Token::simpleMatch(tok, "::")) { // If there is only a op1 and not op2, then this is a global scope if (!tok->astOperand2() && tok->astOperand1()) { tok = tok->astOperand1(); break; } tok = tok->astOperand2(); if (Token::simpleMatch(tok, "<") && tok->link()) tok = tok->astOperand1(); } if (tok && tok->link() && tok->str() == ">") tok = tok->link()->previous(); if (!Token::Match(tok, "%name%|(|{")) return nullptr; // Skip labels if (Token::Match(tok, "%name% :")) return nullptr; return tok; } const Token* getTokenArgumentFunction(const Token* tok, int& argn) { return getTokenArgumentFunctionImpl(tok, argn); } Token* getTokenArgumentFunction(Token* tok, int& argn) { return getTokenArgumentFunctionImpl(tok, argn); } std::vector<const Variable*> getArgumentVars(const Token* tok, int argnr) { std::vector<const Variable*> result; if (!tok) return result; if (tok->function()) { const Variable* argvar = tok->function()->getArgumentVar(argnr); if (argvar) return {argvar}; return result; } if (tok->variable() || Token::simpleMatch(tok, "{") || Token::Match(tok->previous(), "%type% (|{")) { const Type* type = Token::typeOf(tok); if (!type) return result; const Scope* typeScope = type->classScope; if (!typeScope) return result; const bool tokIsBrace = Token::simpleMatch(tok, "{"); // Aggregate constructor if (tokIsBrace && typeScope->numConstructors == 0 && argnr < typeScope->varlist.size()) { auto it = std::next(typeScope->varlist.cbegin(), argnr); return {&*it}; } const int argCount = numberOfArguments(tok); const bool constructor = tokIsBrace || (tok->variable() && tok->variable()->nameToken() == tok); for (const Function &function : typeScope->functionList) { if (function.argCount() < argCount) continue; if (constructor && !function.isConstructor()) continue; if (!constructor && !Token::simpleMatch(function.token, "operator()")) continue; const Variable* argvar = function.getArgumentVar(argnr); if (argvar) result.push_back(argvar); } } return result; } static bool isCPPCastKeyword(const Token* tok) { if (!tok) return false; return endsWith(tok->str(), "_cast"); } static bool isTrivialConstructor(const Token* tok) { const Token* typeTok = nullptr; const Type* t = Token::typeOf(tok, &typeTok); if (t) return false; if (typeTok->valueType() && typeTok->valueType()->isPrimitive()) return true; return false; } static bool isArray(const Token* tok) { if (!tok) return false; if (tok->variable()) return tok->variable()->isArray(); if (Token::simpleMatch(tok, ".")) return isArray(tok->astOperand2()); return false; } static inline // limit it to CLang as compiling with GCC might fail with // error: inlining failed in call to always_inline 'bool isMutableExpression(const Token*)': function not considered for inlining // error: inlining failed in call to ‘always_inline’ ‘bool isMutableExpression(const Token*)’: recursive inlining #if defined(__clang__) __attribute__((always_inline)) #endif bool isMutableExpression(const Token* tok) { if (!tok) return false; if (tok->isLiteral() || tok->isKeyword() || tok->isStandardType() || tok->isEnumerator()) return false; if (Token::Match(tok, ",|;|:|]|)|}")) return false; if (Token::simpleMatch(tok, "[ ]")) return false; if (tok->previous() && tok->previous()->isKeyword() && Token::Match(tok->previous(), "%name% (")) return false; if (tok->link() && Token::Match(tok, "<|>")) return false; if (tok->astOperand1() && Token::simpleMatch(tok, "[")) return isMutableExpression(tok->astOperand1()); if (const Variable* var = tok->variable()) { if (var->nameToken() == tok) return false; if (!var->isPointer() && var->isConst()) return false; } return true; } bool isVariableChangedByFunctionCall(const Token *tok, int indirect, const Settings &settings, bool *inconclusive) { if (!tok) return false; if (Token::simpleMatch(tok, ",")) return false; const Token * const tok1 = tok; // address of variable const bool addressOf = tok->astParent() && tok->astParent()->isUnaryOp("&"); if (addressOf) indirect++; const bool deref = tok->astParent() && tok->astParent()->isUnaryOp("*"); if (deref && indirect > 0) indirect--; if (indirect == 1 && tok->isCpp() && tok->tokAt(-1) && Token::simpleMatch(tok->tokAt(-2), "new (")) // placement new TODO: fix AST return true; int argnr; tok = getTokenArgumentFunction(tok, argnr); if (!tok) return false; // not a function => variable not changed if (Token::simpleMatch(tok, "{") && isTrivialConstructor(tok)) return false; if (tok->isKeyword() && !isCPPCastKeyword(tok) && !startsWith(tok->str(),"operator")) return false; // A functional cast won't modify the variable if (Token::Match(tok, "%type% (|{") && tok->tokType() == Token::eType && astIsPrimitive(tok->next())) return false; const Token * parenTok = tok->next(); if (Token::simpleMatch(parenTok, "<") && parenTok->link()) parenTok = parenTok->link()->next(); const bool possiblyPassedByReference = (parenTok->next() == tok1 || Token::Match(tok1->previous(), ", %name% [,)}]")); if (!tok->function() && !tok->variable() && tok->isName()) { // Check if direction (in, out, inout) is specified in the library configuration and use that const Library::ArgumentChecks::Direction argDirection = settings.library.getArgDirection(tok, 1 + argnr, indirect); if (argDirection == Library::ArgumentChecks::Direction::DIR_IN) return false; const bool requireNonNull = settings.library.isnullargbad(tok, 1 + argnr); if (argDirection == Library::ArgumentChecks::Direction::DIR_OUT || argDirection == Library::ArgumentChecks::Direction::DIR_INOUT) { if (indirect == 0 && isArray(tok1)) return true; const bool requireInit = settings.library.isuninitargbad(tok, 1 + argnr); // Assume that if the variable must be initialized then the indirection is 1 if (indirect > 0 && requireInit && requireNonNull) return true; } if (Token::simpleMatch(tok->tokAt(-2), "std :: tie")) return true; // if the library says 0 is invalid // => it is assumed that parameter is an in parameter (TODO: this is a bad heuristic) if (indirect == 0 && requireNonNull) return false; // possible pass-by-reference => inconclusive if (possiblyPassedByReference) { if (inconclusive != nullptr) *inconclusive = true; return false; } // Safe guess: Assume that parameter is changed by function call return true; } if (const Variable* var = tok->variable()) { if (tok == var->nameToken() && (!var->isReference() || var->isConst()) && (!var->isClass() || (var->valueType() && var->valueType()->container))) // const ref or passed to (copy) ctor return false; } std::vector<const Variable*> args = getArgumentVars(tok, argnr); bool conclusive = false; for (const Variable *arg:args) { if (!arg) continue; conclusive = true; if (indirect > 0) { if (arg->isPointer() && !(arg->valueType() && arg->valueType()->isConst(indirect))) return true; if (indirect > 1 && addressOf && arg->isPointer() && (!arg->valueType() || !arg->valueType()->isConst(indirect-1))) return true; if (arg->isArray() || (!arg->isPointer() && (!arg->valueType() || arg->valueType()->type == ValueType::UNKNOWN_TYPE))) return true; } if (!arg->isConst() && arg->isReference()) return true; } if (addressOf && tok1->astParent()->isUnaryOp("&")) { const Token* castToken = tok1->astParent(); while (castToken->astParent()->isCast()) castToken = castToken->astParent(); if (Token::Match(castToken->astParent(), ",|(") && castToken->valueType() && castToken->valueType()->isIntegral() && castToken->valueType()->pointer == 0) return true; } if (!conclusive && inconclusive) { *inconclusive = true; } return false; } bool isVariableChanged(const Token *tok, int indirect, const Settings &settings, int depth) { if (!isMutableExpression(tok)) return false; if (indirect == 0 && isConstVarExpression(tok)) return false; const Token *tok2 = tok; int derefs = 0; while ((tok2->astParent() && tok2->astParent()->isUnaryOp("*")) || (Token::simpleMatch(tok2->astParent(), ".") && !Token::Match(tok2->astParent()->astParent(), "[(,]")) || (tok2->astParent() && tok2->astParent()->isUnaryOp("&") && Token::simpleMatch(tok2->astParent()->astParent(), ".") && tok2->astParent()->astParent()->originalName()=="->") || (Token::simpleMatch(tok2->astParent(), "[") && tok2 == tok2->astParent()->astOperand1())) { if (tok2->astParent() && (tok2->astParent()->isUnaryOp("*") || (astIsLHS(tok2) && tok2->astParent()->originalName() == "->"))) derefs++; if (derefs > indirect) break; if (tok2->astParent() && tok2->astParent()->isUnaryOp("&") && Token::simpleMatch(tok2->astParent()->astParent(), ".") && tok2->astParent()->astParent()->originalName()=="->") tok2 = tok2->astParent(); tok2 = tok2->astParent(); } if (tok2->astParent() && tok2->astParent()->isUnaryOp("&")) { const Token* parent = tok2->astParent(); while (parent->astParent() && parent->astParent()->isCast()) parent = parent->astParent(); if (parent->astParent() && parent->astParent()->isUnaryOp("*")) tok2 = parent->astParent(); } while ((Token::simpleMatch(tok2, ":") && Token::simpleMatch(tok2->astParent(), "?")) || (Token::simpleMatch(tok2->astParent(), ":") && Token::simpleMatch(tok2->astParent()->astParent(), "?"))) tok2 = tok2->astParent(); if (indirect == 0 && tok2->astParent() && tok2->astParent()->tokType() == Token::eIncDecOp) return true; auto skipRedundantPtrOp = [](const Token* tok, const Token* parent) { const Token* gparent = parent ? parent->astParent() : nullptr; while (parent && gparent && ((parent->isUnaryOp("*") && gparent->isUnaryOp("&")) || (parent->isUnaryOp("&") && gparent->isUnaryOp("*")))) { tok = gparent; parent = gparent->astParent(); if (parent) gparent = parent->astParent(); } return tok; }; tok2 = skipRedundantPtrOp(tok2, tok2->astParent()); if (tok2->astParent() && tok2->astParent()->isAssignmentOp()) { if (astIsLHS(tok2)) return true; // Check if assigning to a non-const lvalue const Variable * var = getLHSVariable(tok2->astParent()); if (var && var->isReference() && !var->isConst() && var->nameToken() && var->nameToken()->next() == tok2->astParent()) { if (!var->isLocal() || isVariableChanged(var, settings, depth - 1)) return true; } } const ValueType* vt = tok->variable() ? tok->variable()->valueType() : tok->valueType(); // Check addressof if (tok2->astParent() && tok2->astParent()->isUnaryOp("&")) { if (isVariableChanged(tok2->astParent(), indirect + 1, settings, depth - 1)) return true; } else { // If its already const then it cant be modified if (vt && vt->isConst(indirect)) return false; } if (tok2->isCpp() && Token::Match(tok2->astParent(), ">>|&") && astIsRHS(tok2) && isLikelyStreamRead(tok2->astParent())) return true; if (isLikelyStream(tok2)) return true; // Member function call if (Token::Match(tok2->astParent(), ". %name%") && isFunctionCall(tok2->astParent()->next()) && tok2->astParent()->astOperand1() == tok2) { // Member function cannot change what `this` points to if (indirect == 0 && astIsPointer(tok)) return false; const Token *ftok = tok2->astParent()->astOperand2(); if (astIsContainer(tok2->astParent()->astOperand1()) && vt && vt->container) { const Library::Container* c = vt->container; const Library::Container::Action action = c->getAction(ftok->str()); if (contains({Library::Container::Action::INSERT, Library::Container::Action::ERASE, Library::Container::Action::APPEND, Library::Container::Action::CHANGE, Library::Container::Action::CHANGE_CONTENT, Library::Container::Action::CHANGE_INTERNAL, Library::Container::Action::CLEAR, Library::Container::Action::FIND, Library::Container::Action::PUSH, Library::Container::Action::POP, Library::Container::Action::RESIZE}, action)) return true; const Library::Container::Yield yield = c->getYield(ftok->str()); // If accessing element check if the element is changed if (contains({Library::Container::Yield::ITEM, Library::Container::Yield::AT_INDEX}, yield)) return isVariableChanged(ftok->next(), indirect, settings, depth - 1); if (contains({Library::Container::Yield::BUFFER, Library::Container::Yield::BUFFER_NT, Library::Container::Yield::START_ITERATOR, Library::Container::Yield::ITERATOR}, yield)) { return isVariableChanged(ftok->next(), indirect + 1, settings, depth - 1); } if (contains({Library::Container::Yield::SIZE, Library::Container::Yield::EMPTY, Library::Container::Yield::END_ITERATOR}, yield)) { return false; } } if (settings.library.isFunctionConst(ftok) || (astIsSmartPointer(tok) && ftok->str() == "get")) // TODO: replace with action/yield? return false; const Function * fun = ftok->function(); if (!fun) return true; return !fun->isConst(); } // Member pointer if (Token::Match(tok2->astParent(), ". * ( & %name% ::")) { const Token* ftok = tok2->astParent()->linkAt(2)->previous(); // TODO: Check for pointer to member variable if (!ftok->function() || !ftok->function()->isConst()) return true; } if (Token::Match(tok2->astParent(), ". * %name%")) // bailout return true; if (Token::simpleMatch(tok2, "[") && astIsContainer(tok) && vt && vt->container && vt->container->stdAssociativeLike) return true; const Token *ftok = tok2; while (ftok && (!Token::Match(ftok, "[({]") || ftok->isCast())) ftok = ftok->astParent(); if (ftok && Token::Match(ftok->link(), ")|} !!{")) { if (ftok->str() == "(" && Token::simpleMatch(ftok->astOperand1(), "[")) // operator() on array element, bail out return true; const Token * ptok = tok2; while (Token::Match(ptok->astParent(), ".|::|[")) ptok = ptok->astParent(); int pindirect = indirect; if (indirect == 0 && astIsLHS(tok2) && Token::Match(ptok, ". %var%") && astIsPointer(ptok->next())) pindirect = 1; bool inconclusive = false; bool isChanged = isVariableChangedByFunctionCall(ptok, pindirect, settings, &inconclusive); isChanged |= inconclusive; if (isChanged) return true; } const Token *parent = tok2->astParent(); while (Token::Match(parent, ".|::")) parent = parent->astParent(); if (parent && parent->tokType() == Token::eIncDecOp && (indirect == 0 || tok2 != tok)) return true; // structured binding, nonconst reference variable in lhs if (Token::Match(tok2->astParent(), ":|=") && tok2 == tok2->astParent()->astOperand2() && Token::simpleMatch(tok2->astParent()->previous(), "]")) { const Token *typeStart = tok2->astParent()->linkAt(-1)->previous(); if (Token::simpleMatch(typeStart, "&")) typeStart = typeStart->previous(); if (typeStart && Token::Match(typeStart->previous(), "[;{}(] auto &| [")) { for (const Token *vartok = typeStart->tokAt(2); vartok != tok2; vartok = vartok->next()) { if (vartok->varId()) { const Variable* refvar = vartok->variable(); if (!refvar || (!refvar->isConst() && refvar->isReference())) return true; } } } } if (Token::simpleMatch(tok2->astParent(), ":") && tok2->astParent()->astParent() && Token::simpleMatch(tok2->astParent()->astParent()->previous(), "for (")) { // TODO: Check if container is empty or not if (astIsLHS(tok2)) return true; const Token * varTok = tok2->astParent()->previous(); if (!varTok) return false; const Variable * loopVar = varTok->variable(); if (!loopVar) return false; if (!loopVar->isConst() && loopVar->isReference() && isVariableChanged(loopVar, settings, depth - 1)) return true; return false; } if (indirect > 0) { // check for `*(ptr + 1) = new_value` case parent = tok2->astParent(); while (parent && ((parent->isArithmeticalOp() && parent->isBinaryOp()) || parent->isIncDecOp())) { parent = parent->astParent(); } if (Token::simpleMatch(parent, "*")) { if (parent->astParent() && parent->astParent()->isAssignmentOp() && (parent->astParent()->astOperand1() == parent)) { return true; } } } return false; } bool isVariableChanged(const Token *start, const Token *end, const nonneg int exprid, bool globalvar, const Settings &settings, int depth) { return findVariableChanged(start, end, 0, exprid, globalvar, settings, depth) != nullptr; } bool isVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth) { return findVariableChanged(start, end, indirect, exprid, globalvar, settings, depth) != nullptr; } const Token* findExpression(const Token* start, const nonneg int exprid) { const Function* f = Scope::nestedInFunction(start->scope()); if (!f) return nullptr; const Scope* scope = f->functionScope; if (!scope) return nullptr; for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (tok->exprId() != exprid) continue; return tok; } return nullptr; } // Thread-unsafe memoization template<class F, class R=decltype(std::declval<F>()())> static std::function<R()> memoize(F f) { bool init = false; R result{}; return [=]() mutable -> R { if (init) return result; result = f(); init = true; return result; }; } template<class F, REQUIRES("F must be a function that returns a Token class", std::is_convertible<decltype(std::declval<F>()()), const Token*> )> static bool isExpressionChangedAt(const F& getExprTok, const Token* tok, int indirect, const nonneg int exprid, bool globalvar, const Settings& settings, int depth) { if (depth < 0) return true; if (!isMutableExpression(tok)) return false; if (tok->exprId() != exprid || (!tok->varId() && !tok->isName())) { if (globalvar && Token::Match(tok, "%name% (") && (!(tok->function() && (tok->function()->isAttributePure() || tok->function()->isAttributeConst())))) { if (!Token::simpleMatch(tok->astParent(), ".")) return true; const auto yield = astContainerYield(tok->astParent()->astOperand1()); if (yield != Library::Container::Yield::SIZE && yield != Library::Container::Yield::EMPTY && yield != Library::Container::Yield::BUFFER && yield != Library::Container::Yield::BUFFER_NT) // TODO: Is global variable really changed by function call? return true; } int i = 1; bool aliased = false; // If we can't find the expression then assume it is an alias auto expr = getExprTok(); if (!expr) aliased = true; if (!aliased) aliased = isAliasOf(tok, expr, &i); if (!aliased) return false; if (isVariableChanged(tok, indirect + i, settings, depth)) return true; // TODO: Try to traverse the lambda function if (Token::Match(tok, "%var% (")) return true; return false; } return (isVariableChanged(tok, indirect, settings, depth)); } bool isExpressionChangedAt(const Token* expr, const Token* tok, int indirect, bool globalvar, const Settings& settings, int depth) { return isExpressionChangedAt([&] { return expr; }, tok, indirect, expr->exprId(), globalvar, settings, depth); } Token* findVariableChanged(Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth) { if (!precedes(start, end)) return nullptr; if (depth < 0) return start; auto getExprTok = memoize([&] { return findExpression(start, exprid); }); for (Token *tok = start; tok != end; tok = tok->next()) { if (isExpressionChangedAt(getExprTok, tok, indirect, exprid, globalvar, settings, depth)) return tok; } return nullptr; } const Token* findVariableChanged(const Token *start, const Token *end, int indirect, const nonneg int exprid, bool globalvar, const Settings &settings, int depth) { return findVariableChanged(const_cast<Token*>(start), end, indirect, exprid, globalvar, settings, depth); } bool isVariableChanged(const Variable * var, const Settings &settings, int depth) { if (!var) return false; if (!var->scope()) return false; const Token * start = var->declEndToken(); if (!start) return false; if (Token::Match(start, "; %varid% =", var->declarationId())) start = start->tokAt(2); if (Token::simpleMatch(start, "=")) { const Token* next = nextAfterAstRightmostLeafGeneric(start); if (next) start = next; } return findExpressionChanged(var->nameToken(), start->next(), var->scope()->bodyEnd, settings, depth); } bool isVariablesChanged(const Token* start, const Token* end, int indirect, const std::vector<const Variable*> &vars, const Settings& settings) { std::set<int> varids; std::transform(vars.cbegin(), vars.cend(), std::inserter(varids, varids.begin()), [](const Variable* var) { return var->declarationId(); }); const bool globalvar = std::any_of(vars.cbegin(), vars.cend(), [](const Variable* var) { return var->isGlobal(); }); for (const Token* tok = start; tok != end; tok = tok->next()) { if (tok->varId() == 0 || varids.count(tok->varId()) == 0) { if (globalvar && Token::Match(tok, "%name% (")) // TODO: Is global variable really changed by function call? return true; continue; } if (isVariableChanged(tok, indirect, settings)) return true; } return false; } bool isThisChanged(const Token* tok, int indirect, const Settings& settings) { if ((Token::Match(tok->previous(), "%name% (") && !Token::simpleMatch(tok->astOperand1(), ".")) || Token::Match(tok->tokAt(-3), "this . %name% (")) { if (tok->previous()->function()) { return (!tok->previous()->function()->isConst() && !tok->previous()->function()->isStatic()); } if (!tok->previous()->isKeyword()) { return true; } } if (isVariableChanged(tok, indirect, settings)) return true; return false; } static const Token* findThisChanged(const Token* start, const Token* end, int indirect, const Settings& settings) { if (!precedes(start, end)) return nullptr; for (const Token* tok = start; tok != end; tok = tok->next()) { if (!exprDependsOnThis(tok)) continue; if (isThisChanged(tok, indirect, settings)) return tok; } return nullptr; } template<class Find> static const Token* findExpressionChangedImpl(const Token* expr, const Token* start, const Token* end, const Settings& settings, int depth, Find find) { if (depth < 0) return start; if (!precedes(start, end)) return nullptr; const Token* result = nullptr; findAstNode(expr, [&](const Token* tok) { if (exprDependsOnThis(tok)) { result = findThisChanged(start, end, /*indirect*/ 0, settings); if (result) return true; } bool global = false; if (tok->variable()) { if (tok->variable()->isConst()) return false; global = !tok->variable()->isLocal() && !tok->variable()->isArgument() && !(tok->variable()->isMember() && !tok->variable()->isStatic()); } else if (tok->isIncompleteVar() && !tok->isIncompleteConstant()) { global = true; } if (tok->exprId() > 0 || global) { const Token* modifedTok = find(start, end, [&](const Token* tok2) { int indirect = 0; if (const ValueType* vt = tok->valueType()) { indirect = vt->pointer; if (vt->type == ValueType::ITERATOR) ++indirect; } for (int i = 0; i <= indirect; ++i) { if (isExpressionChangedAt(tok, tok2, i, global, settings, depth)) return true; } return false; }); if (modifedTok) { result = modifedTok; return true; } } return false; }); return result; } namespace { struct ExpressionChangedSimpleFind { template<class F> const Token* operator()(const Token* start, const Token* end, F f) const { return findToken(start, end, f); } }; struct ExpressionChangedSkipDeadCode { const Library& library; const std::function<std::vector<MathLib::bigint>(const Token* tok)>* evaluate; ExpressionChangedSkipDeadCode(const Library& library, const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate) : library(library), evaluate(&evaluate) {} template<class F> const Token* operator()(const Token* start, const Token* end, F f) const { return findTokenSkipDeadCode(library, start, end, f, *evaluate); } }; } const Token* findExpressionChanged(const Token* expr, const Token* start, const Token* end, const Settings& settings, int depth) { return findExpressionChangedImpl(expr, start, end, settings, depth, ExpressionChangedSimpleFind{}); } const Token* findExpressionChangedSkipDeadCode(const Token* expr, const Token* start, const Token* end, const Settings& settings, const std::function<std::vector<MathLib::bigint>(const Token* tok)>& evaluate, int depth) { return findExpressionChangedImpl( expr, start, end, settings, depth, ExpressionChangedSkipDeadCode{settings.library, evaluate}); } const Token* getArgumentStart(const Token* ftok) { const Token* tok = ftok; if (Token::Match(tok, "%name% (|{|)")) tok = ftok->next(); while (Token::simpleMatch(tok, ")")) tok = tok->next(); if (!Token::Match(tok, "(|{|[")) return nullptr; const Token* startTok = tok->astOperand2(); if (!startTok && tok->next() != tok->link()) startTok = tok->astOperand1(); return startTok; } int numberOfArguments(const Token* ftok) { return astCount(getArgumentStart(ftok), ","); } int numberOfArgumentsWithoutAst(const Token* start) { int arguments = 0; const Token* openBracket = start->next(); while (Token::simpleMatch(openBracket, ")")) openBracket = openBracket->next(); if (openBracket && openBracket->str()=="(" && openBracket->next() && openBracket->strAt(1)!=")") { const Token* argument=openBracket->next(); while (argument) { ++arguments; argument = argument->nextArgument(); } } return arguments; } std::vector<const Token*> getArguments(const Token* ftok) { return astFlatten(getArgumentStart(ftok), ","); } int getArgumentPos(const Variable* var, const Function* f) { auto arg_it = std::find_if(f->argumentList.cbegin(), f->argumentList.cend(), [&](const Variable& v) { return v.nameToken() == var->nameToken(); }); if (arg_it == f->argumentList.end()) return -1; return std::distance(f->argumentList.cbegin(), arg_it); } const Token* getIteratorExpression(const Token* tok) { if (!tok) return nullptr; if (tok->isUnaryOp("*")) return nullptr; if (!tok->isName()) { const Token* iter1 = getIteratorExpression(tok->astOperand1()); if (iter1) return iter1; if (tok->str() == "(") return nullptr; const Token* iter2 = getIteratorExpression(tok->astOperand2()); if (iter2) return iter2; } else if (Token::Match(tok, "begin|cbegin|rbegin|crbegin|end|cend|rend|crend (")) { if (Token::Match(tok->previous(), ". %name% ( ) !!.")) return tok->previous()->astOperand1(); if (!Token::simpleMatch(tok->previous(), ".") && Token::Match(tok, "%name% ( !!)") && !Token::simpleMatch(tok->linkAt(1), ") .")) return tok->next()->astOperand2(); } return nullptr; } bool isIteratorPair(const std::vector<const Token*>& args) { if (args.size() != 2) return false; if (astIsPointer(args[0]) && astIsPointer(args[1])) return true; // Check if iterator is from same container const Token* tok1 = nullptr; const Token* tok2 = nullptr; if (astIsIterator(args[0]) && astIsIterator(args[1])) { tok1 = ValueFlow::getLifetimeObjValue(args[0]).tokvalue; tok2 = ValueFlow::getLifetimeObjValue(args[1]).tokvalue; if (!tok1 || !tok2) return true; } else { tok1 = getIteratorExpression(args[0]); tok2 = getIteratorExpression(args[1]); } if (tok1 && tok2) return tok1->exprId() == tok2->exprId(); return tok1 || tok2; } const Token *findLambdaStartToken(const Token *last) { if (!last || !last->isCpp() || last->str() != "}") return nullptr; const Token* tok = last->link(); if (Token::simpleMatch(tok->astParent(), "(")) tok = tok->astParent(); if (Token::simpleMatch(tok->astParent(), "[")) return tok->astParent(); return nullptr; } template<class T, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )> static T* findLambdaEndTokenGeneric(T* first) { auto maybeLambda = [](T* tok) -> bool { while (Token::Match(tok, "*|%name%|::|>")) { if (tok->link()) tok = tok->link()->previous(); else { if (tok->str() == ">") return true; if (tok->str() == "new") return false; tok = tok->previous(); } } return true; }; if (!first || !first->isCpp() || first->str() != "[") return nullptr; if (!maybeLambda(first->previous())) return nullptr; if (!Token::Match(first->link(), "] (|{|<")) return nullptr; const Token* roundOrCurly = first->link()->next(); if (roundOrCurly->link() && roundOrCurly->str() == "<") roundOrCurly = roundOrCurly->link()->next(); if (first->astOperand1() != roundOrCurly) return nullptr; T * tok = first; if (tok->astOperand1() && tok->astOperand1()->str() == "(") tok = tok->astOperand1(); if (tok->astOperand1() && tok->astOperand1()->str() == "{") return tok->astOperand1()->link(); return nullptr; } const Token* findLambdaEndToken(const Token* first) { return findLambdaEndTokenGeneric(first); } Token* findLambdaEndToken(Token* first) { return findLambdaEndTokenGeneric(first); } bool isLikelyStream(const Token *stream) { if (!stream) return false; if (!stream->isCpp()) return false; if (!Token::Match(stream->astParent(), "&|<<|>>") || !stream->astParent()->isBinaryOp()) return false; if (stream->astParent()->astOperand1() != stream) return false; return !astIsIntegral(stream, false); } bool isLikelyStreamRead(const Token *op) { if (!op) return false; if (!op->isCpp()) return false; if (!Token::Match(op, "&|>>") || !op->isBinaryOp()) return false; if (!Token::Match(op->astOperand2(), "%name%|.|*|[") && op->str() != op->astOperand2()->str()) return false; const Token *parent = op; while (parent->astParent() && parent->astParent()->str() == op->str()) parent = parent->astParent(); if (parent->astParent() && !Token::Match(parent->astParent(), "%oror%|&&|(|,|.|!|;|return")) return false; if (op->str() == "&" && parent->astParent()) return false; if (!parent->astOperand1() || !parent->astOperand2()) return false; return (!parent->astOperand1()->valueType() || !parent->astOperand1()->valueType()->isIntegral()); } bool isCPPCast(const Token* tok) { return tok && Token::simpleMatch(tok->previous(), "> (") && tok->astOperand2() && tok->astOperand1() && isCPPCastKeyword(tok->astOperand1()); } bool isConstVarExpression(const Token *tok, const std::function<bool(const Token*)>& skipPredicate) { if (!tok) return false; if (tok->str() == "?" && tok->astOperand2() && tok->astOperand2()->str() == ":") // ternary operator return isConstVarExpression(tok->astOperand2()->astOperand1()) && isConstVarExpression(tok->astOperand2()->astOperand2()); // left and right of ":" if (skipPredicate && skipPredicate(tok)) return false; if (Token::simpleMatch(tok->previous(), "sizeof (")) return true; if (Token::Match(tok->previous(), "%name% (")) { if (Token::simpleMatch(tok->astOperand1(), ".") && !isConstVarExpression(tok->astOperand1(), skipPredicate)) return false; std::vector<const Token *> args = getArguments(tok); if (args.empty() && tok->previous()->function() && tok->previous()->function()->isConstexpr()) return true; return !args.empty() && std::all_of(args.cbegin(), args.cend(), [&](const Token* t) { return isConstVarExpression(t, skipPredicate); }); } if (isCPPCast(tok)) { return isConstVarExpression(tok->astOperand2(), skipPredicate); } if (Token::Match(tok, "( %type%")) return isConstVarExpression(tok->astOperand1(), skipPredicate); if (tok->str() == "::" && tok->hasKnownValue()) return isConstVarExpression(tok->astOperand2(), skipPredicate); if (Token::Match(tok, "%cop%|[|.")) { if (tok->astOperand1() && !isConstVarExpression(tok->astOperand1(), skipPredicate)) return false; if (tok->astOperand2() && !isConstVarExpression(tok->astOperand2(), skipPredicate)) return false; return true; } if (Token::Match(tok, "%bool%|%num%|%str%|%char%|nullptr|NULL")) return true; if (tok->isEnumerator()) return true; if (tok->variable()) return tok->variable()->isConst() && tok->variable()->nameToken() && tok->variable()->nameToken()->hasKnownValue(); return false; } static ExprUsage getFunctionUsage(const Token* tok, int indirect, const Settings& settings) { const bool addressOf = tok->astParent() && tok->astParent()->isUnaryOp("&"); int argnr; const Token* ftok = getTokenArgumentFunction(tok, argnr); if (!ftok) return ExprUsage::None; const Function* func = ftok->function(); // variable init/constructor call? if (!func && ftok->variable() && ftok == ftok->variable()->nameToken()) { // STL types or containers don't initialize external variables if (ftok->variable()->isStlType() || (ftok->variable()->valueType() && ftok->variable()->valueType()->container)) return ExprUsage::Used; // TODO: resolve multiple constructors if (ftok->variable()->type() && ftok->variable()->type()->classScope) { const int nCtor = ftok->variable()->type()->classScope->numConstructors; if (nCtor == 0) return ExprUsage::Used; if (nCtor == 1) { const Scope* scope = ftok->variable()->type()->classScope; auto it = std::find_if(scope->functionList.begin(), scope->functionList.end(), [](const Function& f) { return f.isConstructor(); }); if (it != scope->functionList.end()) func = &*it; } } } if (func) { std::vector<const Variable*> args = getArgumentVars(ftok, argnr); for (const Variable* arg : args) { if (!arg) continue; if (arg->isReference() || (arg->isPointer() && indirect == 1)) { if (!func->hasBody()) return ExprUsage::PassedByReference; for (const Token* bodytok = func->functionScope->bodyStart; bodytok != func->functionScope->bodyEnd; bodytok = bodytok->next()) { if (bodytok->variable() == arg) { if (arg->isReference()) return ExprUsage::PassedByReference; if (Token::Match(bodytok->astParent(), "%comp%|!")) return ExprUsage::NotUsed; return ExprUsage::PassedByReference; } } return ExprUsage::NotUsed; } } if (!args.empty() && indirect == 0 && !addressOf) return ExprUsage::Used; } else if (ftok->isControlFlowKeyword()) { return ExprUsage::Used; } else if (ftok->str() == "{") { return indirect == 0 ? ExprUsage::Used : ExprUsage::Inconclusive; } else { const bool isnullbad = settings.library.isnullargbad(ftok, argnr + 1); if (indirect == 0 && astIsPointer(tok) && !addressOf && isnullbad) return ExprUsage::Used; bool hasIndirect = false; const bool isuninitbad = settings.library.isuninitargbad(ftok, argnr + 1, indirect, &hasIndirect); if (isuninitbad && (!addressOf || isnullbad)) return ExprUsage::Used; } return ExprUsage::Inconclusive; } bool isLeafDot(const Token* tok) { if (!tok) return false; const Token * parent = tok->astParent(); if (!Token::simpleMatch(parent, ".")) return false; if (parent->astOperand2() == tok && !Token::simpleMatch(parent->astParent(), ".")) return true; return isLeafDot(parent); } ExprUsage getExprUsage(const Token* tok, int indirect, const Settings& settings) { const Token* parent = tok->astParent(); if (indirect > 0 && parent) { while (Token::simpleMatch(parent, "[") && parent->astParent()) parent = parent->astParent(); if (Token::Match(parent, "%assign%") && (astIsRHS(tok) || astIsLHS(parent->astOperand1()))) return ExprUsage::NotUsed; if (Token::Match(parent, "++|--")) return ExprUsage::NotUsed; if (parent->isConstOp()) return ExprUsage::NotUsed; if (parent->isCast()) return ExprUsage::NotUsed; if (Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "?")) return getExprUsage(parent->astParent(), indirect, settings); if (isUsedAsBool(tok, settings)) return ExprUsage::NotUsed; } if (tok->isUnaryOp("&") && !parent) return ExprUsage::NotUsed; if (indirect == 0) { if (Token::Match(parent, "%cop%|%assign%|++|--") && parent->str() != "=" && !parent->isUnaryOp("&") && !(astIsRHS(tok) && isLikelyStreamRead(parent))) return ExprUsage::Used; if (isLeafDot(tok)) { const Token* op = parent->astParent(); while (Token::simpleMatch(op, ".")) op = op->astParent(); if (Token::Match(op, "%assign%|++|--")) { if (op->str() == "=") { if (precedes(tok, op)) return ExprUsage::NotUsed; } else return ExprUsage::Used; } } if (Token::simpleMatch(parent, "=") && astIsRHS(tok)) { const Token* const lhs = parent->astOperand1(); if (lhs && lhs->variable() && lhs->variable()->isReference() && lhs == lhs->variable()->nameToken()) return ExprUsage::NotUsed; return ExprUsage::Used; } // Function call or index if (((Token::simpleMatch(parent, "(") && !parent->isCast()) || (Token::simpleMatch(parent, "[") && tok->valueType())) && (astIsLHS(tok) || Token::simpleMatch(parent, "( )"))) return ExprUsage::Used; } return getFunctionUsage(tok, indirect, settings); } static void getLHSVariablesRecursive(std::vector<const Variable*>& vars, const Token* tok) { if (!tok) return; if (vars.empty() && Token::Match(tok, "*|&|&&|[")) { getLHSVariablesRecursive(vars, tok->astOperand1()); if (!vars.empty() || Token::simpleMatch(tok, "[")) return; getLHSVariablesRecursive(vars, tok->astOperand2()); } else if (Token::Match(tok->previous(), "this . %var%")) { getLHSVariablesRecursive(vars, tok->next()); } else if (Token::simpleMatch(tok, ".")) { getLHSVariablesRecursive(vars, tok->astOperand1()); getLHSVariablesRecursive(vars, tok->astOperand2()); } else if (Token::simpleMatch(tok, "::")) { getLHSVariablesRecursive(vars, tok->astOperand2()); } else if (tok->variable()) { vars.push_back(tok->variable()); } } std::vector<const Variable*> getLHSVariables(const Token* tok) { std::vector<const Variable*> result; if (!Token::Match(tok, "%assign%|(|{")) return result; if (!tok->astOperand1()) return result; if (tok->astOperand1()->varId() > 0 && tok->astOperand1()->variable()) return {tok->astOperand1()->variable()}; getLHSVariablesRecursive(result, tok->astOperand1()); return result; } static const Token* getLHSVariableRecursive(const Token* tok) { if (!tok) return nullptr; if (Token::Match(tok, "*|&|&&|[")) { const Token* vartok = getLHSVariableRecursive(tok->astOperand1()); if ((vartok && vartok->variable()) || Token::simpleMatch(tok, "[")) return vartok; return getLHSVariableRecursive(tok->astOperand2()); } if (Token::Match(tok->previous(), "this . %var%")) return tok->next(); return tok; } const Variable *getLHSVariable(const Token *tok) { if (!tok || !tok->isAssignmentOp()) return nullptr; if (!tok->astOperand1()) return nullptr; if (tok->astOperand1()->varId() > 0 && tok->astOperand1()->variable()) return tok->astOperand1()->variable(); const Token* vartok = getLHSVariableRecursive(tok->astOperand1()); if (!vartok) return nullptr; return vartok->variable(); } const Token* getLHSVariableToken(const Token* tok) { if (!Token::Match(tok, "%assign%")) return nullptr; if (!tok->astOperand1()) return nullptr; if (tok->astOperand1()->varId() > 0) return tok->astOperand1(); const Token* vartok = getLHSVariableRecursive(tok->astOperand1()); if (vartok && vartok->variable() && vartok->variable()->nameToken() == vartok) return vartok; return tok->astOperand1(); } const Token* findAllocFuncCallToken(const Token *expr, const Library &library) { if (!expr) return nullptr; if (Token::Match(expr, "[+-]")) { const Token *tok1 = findAllocFuncCallToken(expr->astOperand1(), library); return tok1 ? tok1 : findAllocFuncCallToken(expr->astOperand2(), library); } if (expr->isCast()) return findAllocFuncCallToken(expr->astOperand2() ? expr->astOperand2() : expr->astOperand1(), library); if (Token::Match(expr->previous(), "%name% (") && library.getAllocFuncInfo(expr->astOperand1())) return expr->astOperand1(); return (Token::simpleMatch(expr, "new") && expr->astOperand1()) ? expr : nullptr; } bool isNullOperand(const Token *expr) { if (!expr) return false; if (expr->isCpp() && Token::Match(expr, "static_cast|const_cast|dynamic_cast|reinterpret_cast <")) expr = expr->astParent(); else if (!expr->isCast()) return Token::Match(expr, "NULL|nullptr"); if (expr->valueType() && expr->valueType()->pointer == 0) return false; const Token *castOp = expr->astOperand2() ? expr->astOperand2() : expr->astOperand1(); return Token::Match(castOp, "NULL|nullptr") || (MathLib::isInt(castOp->str()) && MathLib::isNullValue(castOp->str())); } bool isGlobalData(const Token *expr) { // function call that returns reference => assume global data if (expr && expr->str() == "(" && expr->valueType() && expr->valueType()->reference != Reference::None) { if (expr->isBinaryOp()) return true; if (expr->astOperand1() && precedes(expr->astOperand1(), expr)) return true; } bool globalData = false; bool var = false; visitAstNodes(expr, [expr, &globalData, &var](const Token *tok) { if (tok->varId()) var = true; if (tok->varId() && !tok->variable()) { // Bailout, this is probably global globalData = true; return ChildrenToVisit::none; } if (tok->originalName() == "->") { // TODO check if pointer points at local data globalData = true; return ChildrenToVisit::none; } if (Token::Match(tok, "[*[]") && tok->astOperand1() && tok->astOperand1()->variable()) { // TODO check if pointer points at local data const Variable *lhsvar = tok->astOperand1()->variable(); const ValueType *lhstype = tok->astOperand1()->valueType(); if (lhsvar->isPointer()) { globalData = true; return ChildrenToVisit::none; } if (lhsvar->isArgument() && lhsvar->isArray()) { globalData = true; return ChildrenToVisit::none; } if (lhsvar->isArgument() && (!lhstype || (lhstype->type <= ValueType::Type::VOID && !lhstype->container))) { globalData = true; return ChildrenToVisit::none; } } if (tok->varId() == 0 && tok->isName() && tok->strAt(-1) != ".") { globalData = true; return ChildrenToVisit::none; } if (tok->variable()) { // TODO : Check references if (tok->variable()->isReference() && tok != tok->variable()->nameToken()) { globalData = true; return ChildrenToVisit::none; } if (tok->variable()->isExtern()) { globalData = true; return ChildrenToVisit::none; } if (tok->strAt(-1) != "." && !tok->variable()->isLocal() && !tok->variable()->isArgument()) { globalData = true; return ChildrenToVisit::none; } if (tok->variable()->isArgument() && tok->variable()->isPointer() && tok != expr) { globalData = true; return ChildrenToVisit::none; } if (tok->variable()->isPointerArray()) { globalData = true; return ChildrenToVisit::none; } } // Unknown argument type => it might be some reference type.. if (tok->isCpp() && tok->str() == "." && tok->astOperand1() && tok->astOperand1()->variable() && !tok->astOperand1()->valueType()) { globalData = true; return ChildrenToVisit::none; } if (Token::Match(tok, ".|[")) return ChildrenToVisit::op1; return ChildrenToVisit::op1_and_op2; }); return globalData || !var; } bool isUnevaluated(const Token *tok) { return Token::Match(tok, "alignof|_Alignof|_alignof|__alignof|__alignof__|decltype|offsetof|sizeof|typeid|typeof|__typeof__ ("); } static std::set<MathLib::bigint> getSwitchValues(const Token *startbrace, bool &hasDefault) { std::set<MathLib::bigint> values; const Token *endbrace = startbrace->link(); if (!endbrace) return values; hasDefault = false; for (const Token *tok = startbrace->next(); tok && tok != endbrace; tok = tok->next()) { if (Token::simpleMatch(tok, "{") && tok->scope()->type == Scope::ScopeType::eSwitch) { tok = tok->link(); continue; } if (Token::simpleMatch(tok, "default")) { hasDefault = true; break; } if (Token::simpleMatch(tok, "case")) { const Token *valueTok = tok->astOperand1(); if (valueTok->hasKnownIntValue()) values.insert(valueTok->getKnownIntValue()); continue; } } return values; } bool isExhaustiveSwitch(const Token *startbrace) { if (!startbrace || !Token::simpleMatch(startbrace->previous(), ") {") || startbrace->scope()->type != Scope::ScopeType::eSwitch) return false; const Token *rpar = startbrace->previous(); const Token *lpar = rpar->link(); const Token *condition = lpar->astOperand2(); if (!condition->valueType()) return true; bool hasDefault = false; const std::set<MathLib::bigint> switchValues = getSwitchValues(startbrace, hasDefault); if (hasDefault) return true; if (condition->valueType()->type == ValueType::Type::BOOL) return switchValues.count(0) && switchValues.count(1); if (condition->valueType()->isEnum()) { const std::vector<Enumerator> &enumList = condition->valueType()->typeScope->enumeratorList; return std::all_of(enumList.cbegin(), enumList.cend(), [&](const Enumerator &e) { return !e.value_known || switchValues.count(e.value); }); } return false; } bool isUnreachableOperand(const Token *tok) { for (;;) { const Token *parent = tok->astParent(); if (!parent) break; if (parent->isBinaryOp()) { const bool left = tok == parent->astOperand1(); const Token *sibling = left ? parent->astOperand2() : parent->astOperand1(); // logical and if (Token::simpleMatch(parent, "&&") && !left && sibling->hasKnownIntValue() && !sibling->getKnownIntValue()) return true; // logical or if (Token::simpleMatch(parent, "||") && !left && sibling->hasKnownIntValue() && sibling->getKnownIntValue()) return true; // ternary if (Token::simpleMatch(parent, ":") && Token::simpleMatch(parent->astParent(), "?")) { const Token *condTok = parent->astParent()->astOperand1(); if (condTok->hasKnownIntValue() && static_cast<bool>(condTok->getKnownIntValue()) != left) return true; } } tok = parent; } return false; }
143,541
C++
.cpp
3,479
32.616269
222
0.575789
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
26,182
vf_globalconstvar.cpp
danmar_cppcheck/lib/vf_globalconstvar.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_globalconstvar.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <list> #include <map> #include <utility> namespace ValueFlow { void analyzeGlobalConstVar(TokenList& tokenList, const Settings &settings) { // Get variable values... std::map<const Variable*, Value> vars; for (const Token* tok = tokenList.front(); tok; tok = tok->next()) { if (!tok->variable()) continue; // Initialization... if (tok == tok->variable()->nameToken() && !tok->variable()->isVolatile() && !tok->variable()->isArgument() && tok->variable()->isConst() && tok->valueType() && tok->valueType()->isIntegral() && tok->valueType()->pointer == 0 && tok->valueType()->constness == 1 && Token::Match(tok, "%name% =") && tok->next()->astOperand2() && tok->next()->astOperand2()->hasKnownIntValue()) { vars[tok->variable()] = tok->next()->astOperand2()->values().front(); } } // Set values.. for (Token* tok = tokenList.front(); tok; tok = tok->next()) { if (!tok->variable()) continue; const std::map<const Variable*, Value>::const_iterator var = vars.find(tok->variable()); if (var == vars.end()) continue; setTokenValue(tok, var->second, settings); } } }
2,366
C++
.cpp
61
31.065574
100
0.593736
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,183
addoninfo.cpp
danmar_cppcheck/lib/addoninfo.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "addoninfo.h" #include "path.h" #include "utils.h" #include <fstream> #include <iostream> #include <string> #include <vector> #include "json.h" static std::string getFullPath(const std::string &fileName, const std::string &exename, bool debug = false) { if (debug) std::cout << "looking for addon '" << fileName << "'" << std::endl; if (Path::isFile(fileName)) return fileName; const std::string exepath = Path::getPathFromFilename(exename); if (debug) std::cout << "looking for addon '" << (exepath + fileName) << "'" << std::endl; if (Path::isFile(exepath + fileName)) return exepath + fileName; if (debug) std::cout << "looking for addon '" << (exepath + "addons/" + fileName) << "'" << std::endl; if (Path::isFile(exepath + "addons/" + fileName)) return exepath + "addons/" + fileName; #ifdef FILESDIR if (debug) std::cout << "looking for addon '" << (FILESDIR + ("/" + fileName)) << "'" << std::endl; if (Path::isFile(FILESDIR + ("/" + fileName))) return FILESDIR + ("/" + fileName); if (debug) std::cout << "looking for addon '" << (FILESDIR + ("/addons/" + fileName)) << "'" << std::endl; if (Path::isFile(FILESDIR + ("/addons/" + fileName))) return FILESDIR + ("/addons/" + fileName); #endif return ""; } static std::string parseAddonInfo(AddonInfo& addoninfo, const picojson::value &json, const std::string &fileName, const std::string &exename) { const std::string& json_error = picojson::get_last_error(); if (!json_error.empty()) { return "Loading " + fileName + " failed. " + json_error; } if (!json.is<picojson::object>()) return "Loading " + fileName + " failed. JSON is not an object."; // TODO: remove/complete default value handling for missing fields const picojson::object& obj = json.get<picojson::object>(); { const auto it = obj.find("args"); if (it != obj.cend()) { const auto& val = it->second; if (!val.is<picojson::array>()) return "Loading " + fileName + " failed. 'args' must be an array."; for (const picojson::value &v : val.get<picojson::array>()) { if (!v.is<std::string>()) return "Loading " + fileName + " failed. 'args' entry is not a string."; addoninfo.args += " " + v.get<std::string>(); } } } { const auto it = obj.find("ctu"); if (it != obj.cend()) { const auto& val = it->second; // ctu is specified in the config file if (!val.is<bool>()) return "Loading " + fileName + " failed. 'ctu' must be a boolean."; addoninfo.ctu = val.get<bool>(); } else { addoninfo.ctu = false; } } { const auto it = obj.find("python"); if (it != obj.cend()) { const auto& val = it->second; // Python was defined in the config file if (!val.is<std::string>()) { return "Loading " + fileName +" failed. 'python' must be a string."; } addoninfo.python = val.get<std::string>(); } else { addoninfo.python = ""; } } { const auto it = obj.find("executable"); if (it != obj.cend()) { const auto& val = it->second; if (!val.is<std::string>()) return "Loading " + fileName + " failed. 'executable' must be a string."; const std::string e = val.get<std::string>(); addoninfo.executable = getFullPath(e, fileName); if (addoninfo.executable.empty()) addoninfo.executable = e; return ""; // <- do not load both "executable" and "script". } } const auto it = obj.find("script"); if (it == obj.cend()) return "Loading " + fileName + " failed. 'script' is missing."; const auto& val = it->second; if (!val.is<std::string>()) return "Loading " + fileName + " failed. 'script' must be a string."; return addoninfo.getAddonInfo(val.get<std::string>(), exename); } std::string AddonInfo::getAddonInfo(const std::string &fileName, const std::string &exename, bool debug) { if (fileName[0] == '{') { picojson::value json; const std::string err = picojson::parse(json, fileName); (void)err; // TODO: report return parseAddonInfo(*this, json, fileName, exename); } if (fileName.find('.') == std::string::npos) return getAddonInfo(fileName + ".py", exename, debug); if (endsWith(fileName, ".py")) { scriptFile = Path::fromNativeSeparators(getFullPath(fileName, exename, debug)); if (scriptFile.empty()) return "Did not find addon " + fileName; std::string::size_type pos1 = scriptFile.rfind('/'); if (pos1 == std::string::npos) pos1 = 0; else pos1++; std::string::size_type pos2 = scriptFile.rfind('.'); if (pos2 < pos1) pos2 = std::string::npos; name = scriptFile.substr(pos1, pos2 - pos1); runScript = getFullPath("runaddon.py", exename); return ""; } if (!endsWith(fileName, ".json")) return "Failed to open addon " + fileName; std::ifstream fin(fileName); if (!fin.is_open()) return "Failed to open " + fileName; if (name.empty()) { name = Path::fromNativeSeparators(fileName); if (name.find('/') != std::string::npos) name = name.substr(name.rfind('/') + 1); } picojson::value json; fin >> json; return parseAddonInfo(*this, json, fileName, exename); }
6,547
C++
.cpp
160
33.35625
143
0.581618
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,184
vf_arraybool.cpp
danmar_cppcheck/lib/vf_arraybool.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_arraybool.h" #include "astutils.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <algorithm> #include <functional> #include <list> #include <utility> namespace ValueFlow { static bool isNonZero(const Token *tok) { return tok && (!tok->hasKnownIntValue() || tok->values().front().intvalue != 0); } static const Token *getOtherOperand(const Token *tok) { if (!tok) return nullptr; if (!tok->astParent()) return nullptr; if (tok->astParent()->astOperand1() != tok) return tok->astParent()->astOperand1(); if (tok->astParent()->astOperand2() != tok) return tok->astParent()->astOperand2(); return nullptr; } void analyzeArrayBool(TokenList &tokenlist, const Settings &settings) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { if (tok->hasKnownIntValue()) continue; const Variable *var = nullptr; bool known = false; const std::list<Value>::const_iterator val = std::find_if(tok->values().cbegin(), tok->values().cend(), std::mem_fn(&Value::isTokValue)); if (val == tok->values().end()) { var = tok->variable(); known = true; } else { var = val->tokvalue->variable(); known = val->isKnown(); } if (!var) continue; if (!var->isArray() || var->isArgument() || var->isStlType()) continue; if (isNonZero(getOtherOperand(tok)) && Token::Match(tok->astParent(), "%comp%")) continue; // TODO: Check for function argument if ((astIsBool(tok->astParent()) && !Token::Match(tok->astParent(), "(|%name%")) || (tok->astParent() && Token::Match(tok->astParent()->previous(), "if|while|for ("))) { Value value{1}; if (known) value.setKnown(); setTokenValue(tok, std::move(value), settings); } } } }
2,983
C++
.cpp
79
29.734177
108
0.588885
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,185
vf_rightshift.cpp
danmar_cppcheck/lib/vf_rightshift.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_rightshift.h" #include "mathlib.h" #include "platform.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <list> #include <string> #include <utility> namespace ValueFlow { static bool getExpressionRange(const Token *expr, MathLib::bigint *minvalue, MathLib::bigint *maxvalue) { if (expr->hasKnownIntValue()) { if (minvalue) *minvalue = expr->values().front().intvalue; if (maxvalue) *maxvalue = expr->values().front().intvalue; return true; } if (expr->str() == "&" && expr->astOperand1() && expr->astOperand2()) { MathLib::bigint vals[4]; const bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]); const bool rhsHasKnownRange = getExpressionRange(expr->astOperand2(), &vals[2], &vals[3]); if (!lhsHasKnownRange && !rhsHasKnownRange) return false; if (!lhsHasKnownRange || !rhsHasKnownRange) { if (minvalue) *minvalue = lhsHasKnownRange ? vals[0] : vals[2]; if (maxvalue) *maxvalue = lhsHasKnownRange ? vals[1] : vals[3]; } else { if (minvalue) *minvalue = vals[0] & vals[2]; if (maxvalue) *maxvalue = vals[1] & vals[3]; } return true; } if (expr->str() == "%" && expr->astOperand1() && expr->astOperand2()) { MathLib::bigint vals[4]; if (!getExpressionRange(expr->astOperand2(), &vals[2], &vals[3])) return false; if (vals[2] <= 0) return false; const bool lhsHasKnownRange = getExpressionRange(expr->astOperand1(), &vals[0], &vals[1]); if (lhsHasKnownRange && vals[0] < 0) return false; // If lhs has unknown value, it must be unsigned if (!lhsHasKnownRange && (!expr->astOperand1()->valueType() || expr->astOperand1()->valueType()->sign != ValueType::Sign::UNSIGNED)) return false; if (minvalue) *minvalue = 0; if (maxvalue) *maxvalue = vals[3] - 1; return true; } return false; } void analyzeRightShift(TokenList &tokenList, const Settings& settings) { for (Token *tok = tokenList.front(); tok; tok = tok->next()) { if (tok->str() != ">>") continue; if (tok->hasKnownValue()) continue; if (!tok->astOperand1() || !tok->astOperand2()) continue; if (!tok->astOperand2()->hasKnownValue()) continue; const MathLib::bigint rhsvalue = tok->astOperand2()->values().front().intvalue; if (rhsvalue < 0) continue; if (!tok->astOperand1()->valueType() || !tok->astOperand1()->valueType()->isIntegral()) continue; if (!tok->astOperand2()->valueType() || !tok->astOperand2()->valueType()->isIntegral()) continue; MathLib::bigint lhsmax=0; if (!getExpressionRange(tok->astOperand1(), nullptr, &lhsmax)) continue; if (lhsmax < 0) continue; int lhsbits; if ((tok->astOperand1()->valueType()->type == ValueType::Type::CHAR) || (tok->astOperand1()->valueType()->type == ValueType::Type::SHORT) || (tok->astOperand1()->valueType()->type == ValueType::Type::WCHAR_T) || (tok->astOperand1()->valueType()->type == ValueType::Type::BOOL) || (tok->astOperand1()->valueType()->type == ValueType::Type::INT)) lhsbits = settings.platform.int_bit; else if (tok->astOperand1()->valueType()->type == ValueType::Type::LONG) lhsbits = settings.platform.long_bit; else if (tok->astOperand1()->valueType()->type == ValueType::Type::LONGLONG) lhsbits = settings.platform.long_long_bit; else continue; if (rhsvalue >= lhsbits || rhsvalue >= MathLib::bigint_bits || (1ULL << rhsvalue) <= lhsmax) continue; Value val(0); val.setKnown(); setTokenValue(tok, std::move(val), settings); } } }
5,334
C++
.cpp
123
32.634146
144
0.560647
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,186
vf_pointeralias.cpp
danmar_cppcheck/lib/vf_pointeralias.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_pointeralias.h" #include "symboldatabase.h" #include "token.h" #include "tokenlist.h" #include "vfvalue.h" #include "vf_settokenvalue.h" #include <string> #include <utility> namespace ValueFlow { void analyzePointerAlias(TokenList &tokenlist, const Settings& settings) { for (Token *tok = tokenlist.front(); tok; tok = tok->next()) { // not address of if (!tok->isUnaryOp("&")) continue; // parent should be a '=' if (!Token::simpleMatch(tok->astParent(), "=")) continue; // child should be some buffer or variable const Token *vartok = tok->astOperand1(); while (vartok) { if (vartok->str() == "[") vartok = vartok->astOperand1(); else if (vartok->str() == "." || vartok->str() == "::") vartok = vartok->astOperand2(); else break; } if (!(vartok && vartok->variable() && !vartok->variable()->isPointer())) continue; Value value; value.valueType = Value::ValueType::TOK; value.tokvalue = tok; setTokenValue(tok, std::move(value), settings); } } }
2,058
C++
.cpp
55
29.8
84
0.604511
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,187
vf_analyzers.cpp
danmar_cppcheck/lib/vf_analyzers.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "vf_analyzers.h" #include "analyzer.h" #include "astutils.h" #include "calculate.h" #include "config.h" #include "library.h" #include "mathlib.h" #include "programmemory.h" #include "smallvector.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "utils.h" #include "vfvalue.h" #include "valueptr.h" #include "valueflow.h" #include "vf_common.h" #include "vf_settokenvalue.h" #include <algorithm> #include <cassert> #include <cstddef> #include <functional> #include <initializer_list> #include <iterator> #include <list> #include <set> #include <type_traits> struct ValueFlowAnalyzer : Analyzer { const Settings& settings; ProgramMemoryState pms; explicit ValueFlowAnalyzer(const Settings& s) : settings(s), pms(settings) {} virtual const ValueFlow::Value* getValue(const Token* tok) const = 0; virtual ValueFlow::Value* getValue(const Token* tok) = 0; virtual void makeConditional() = 0; virtual void addErrorPath(const Token* tok, const std::string& s) = 0; virtual bool match(const Token* tok) const = 0; virtual bool internalMatch(const Token* /*tok*/) const { return false; } virtual bool isAlias(const Token* tok, bool& inconclusive) const = 0; using ProgramState = ProgramMemory::Map; virtual ProgramState getProgramState() const = 0; virtual int getIndirect(const Token* tok) const { const ValueFlow::Value* value = getValue(tok); if (value) return value->indirect; return 0; } virtual bool isGlobal() const { return false; } virtual bool dependsOnThis() const { return false; } virtual bool isVariable() const { return false; } const Settings& getSettings() const { return settings; } struct ConditionState { bool dependent = true; bool unknown = true; bool isUnknownDependent() const { return unknown && dependent; } }; ConditionState analyzeCondition(const Token* tok, int depth = 20) const { ConditionState result; if (!tok) return result; if (depth < 0) return result; depth--; if (analyze(tok, Direction::Forward).isRead()) { result.dependent = true; result.unknown = false; return result; } if (tok->hasKnownIntValue() || tok->isLiteral()) { result.dependent = false; result.unknown = false; return result; } if (Token::Match(tok, "%cop%")) { if (isLikelyStream(tok->astOperand1())) { result.dependent = false; return result; } ConditionState lhs = analyzeCondition(tok->astOperand1(), depth - 1); if (lhs.isUnknownDependent()) return lhs; ConditionState rhs = analyzeCondition(tok->astOperand2(), depth - 1); if (rhs.isUnknownDependent()) return rhs; if (Token::Match(tok, "%comp%")) result.dependent = lhs.dependent && rhs.dependent; else result.dependent = lhs.dependent || rhs.dependent; result.unknown = lhs.unknown || rhs.unknown; return result; } if (Token::Match(tok->previous(), "%name% (")) { std::vector<const Token*> args = getArguments(tok->previous()); if (Token::Match(tok->tokAt(-2), ". %name% (")) { args.push_back(tok->tokAt(-2)->astOperand1()); } result.dependent = std::any_of(args.cbegin(), args.cend(), [&](const Token* arg) { ConditionState cs = analyzeCondition(arg, depth - 1); return cs.dependent; }); if (result.dependent) { // Check if we can evaluate the function if (!evaluate(Evaluate::Integral, tok).empty()) result.unknown = false; } return result; } std::unordered_map<nonneg int, const Token*> symbols = getSymbols(tok); result.dependent = false; for (auto&& p : symbols) { const Token* arg = p.second; ConditionState cs = analyzeCondition(arg, depth - 1); result.dependent = cs.dependent; if (result.dependent) break; } if (result.dependent) { // Check if we can evaluate the token if (!evaluate(Evaluate::Integral, tok).empty()) result.unknown = false; } return result; } static ValueFlow::Value::MoveKind isMoveOrForward(const Token* tok) { if (!tok) return ValueFlow::Value::MoveKind::NonMovedVariable; const Token* parent = tok->astParent(); if (!Token::simpleMatch(parent, "(")) return ValueFlow::Value::MoveKind::NonMovedVariable; const Token* ftok = parent->astOperand1(); if (!ftok) return ValueFlow::Value::MoveKind::NonMovedVariable; if (Token::simpleMatch(ftok->astOperand1(), "std :: move")) return ValueFlow::Value::MoveKind::MovedVariable; if (Token::simpleMatch(ftok->astOperand1(), "std :: forward")) return ValueFlow::Value::MoveKind::ForwardedVariable; // TODO: Check for cast return ValueFlow::Value::MoveKind::NonMovedVariable; } virtual Action isModified(const Token* tok) const { const Action read = Action::Read; const ValueFlow::Value* value = getValue(tok); if (value) { // Moving a moved value won't change the moved value if (value->isMovedValue() && isMoveOrForward(tok) != ValueFlow::Value::MoveKind::NonMovedVariable) return read; // Inserting elements to container won't change the lifetime if (astIsContainer(tok) && value->isLifetimeValue() && contains({Library::Container::Action::PUSH, Library::Container::Action::INSERT, Library::Container::Action::APPEND, Library::Container::Action::CHANGE_INTERNAL}, astContainerAction(tok))) return read; } bool inconclusive = false; if (isVariableChangedByFunctionCall(tok, getIndirect(tok), getSettings(), &inconclusive)) return read | Action::Invalid; if (inconclusive) return read | Action::Inconclusive; if (isVariableChanged(tok, getIndirect(tok), getSettings())) { if (Token::Match(tok->astParent(), "*|[|.|++|--")) return read | Action::Invalid; // Check if its assigned to the same value if (value && !value->isImpossible() && Token::simpleMatch(tok->astParent(), "=") && astIsLHS(tok) && astIsIntegral(tok->astParent()->astOperand2(), false)) { std::vector<MathLib::bigint> result = evaluateInt(tok->astParent()->astOperand2()); if (!result.empty() && value->equalTo(result.front())) return Action::Idempotent; } return Action::Invalid; } return read; } virtual Action isAliasModified(const Token* tok, int indirect = -1) const { // Lambda function call if (Token::Match(tok, "%var% (")) // TODO: Check if modified in the lambda function return Action::Invalid; if (indirect == -1) { indirect = 0; if (const ValueType* vt = tok->valueType()) { indirect = vt->pointer; if (vt->type == ValueType::ITERATOR) ++indirect; const Token* tok2 = tok; while (Token::simpleMatch(tok2->astParent(), "[")) { tok2 = tok2->astParent(); --indirect; } indirect = std::max(indirect, 0); } } for (int i = 0; i <= indirect; ++i) if (isVariableChanged(tok, i, getSettings())) return Action::Invalid; return Action::None; } virtual Action isThisModified(const Token* tok) const { if (isThisChanged(tok, 0, getSettings())) return Action::Invalid; return Action::None; } virtual Action isWritable(const Token* tok, Direction d) const { const ValueFlow::Value* value = getValue(tok); if (!value) return Action::None; if (!(value->isIntValue() || value->isFloatValue() || value->isSymbolicValue() || value->isLifetimeValue())) return Action::None; const Token* parent = tok->astParent(); // Only if its invertible if (value->isImpossible() && !Token::Match(parent, "+=|-=|*=|++|--")) return Action::None; if (value->isLifetimeValue()) { if (value->lifetimeKind != ValueFlow::Value::LifetimeKind::Iterator) return Action::None; if (!Token::Match(parent, "++|--|+=")) return Action::None; return Action::Read | Action::Write; } if (parent && parent->isAssignmentOp() && astIsLHS(tok)) { const Token* rhs = parent->astOperand2(); std::vector<MathLib::bigint> result = evaluateInt(rhs); if (!result.empty()) { ValueFlow::Value rhsValue{result.front()}; Action a; if (!evalAssignment(*value, getAssign(parent, d), rhsValue)) a = Action::Invalid; else a = Action::Write; if (parent->str() != "=") { a |= Action::Read | Action::Incremental; } else { if (!value->isImpossible() && value->equalValue(rhsValue)) a = Action::Idempotent; if (tok->exprId() != 0 && findAstNode(rhs, [&](const Token* child) { return tok->exprId() == child->exprId(); })) a |= Action::Incremental; } return a; } } // increment/decrement if (Token::Match(tok->astParent(), "++|--")) { return Action::Read | Action::Write | Action::Incremental; } return Action::None; } virtual void writeValue(ValueFlow::Value* value, const Token* tok, Direction d) const { if (!value) return; if (!tok->astParent()) return; // Lifetime value doesn't change if (value->isLifetimeValue()) return; if (tok->astParent()->isAssignmentOp()) { const Token* rhs = tok->astParent()->astOperand2(); std::vector<MathLib::bigint> result = evaluateInt(rhs); assert(!result.empty()); ValueFlow::Value rhsValue{result.front()}; if (evalAssignment(*value, getAssign(tok->astParent(), d), rhsValue)) { std::string info("Compound assignment '" + tok->astParent()->str() + "', assigned value is " + value->infoString()); if (tok->astParent()->str() == "=") value->errorPath.clear(); value->errorPath.emplace_back(tok, std::move(info)); } else { assert(false && "Writable value cannot be evaluated"); // TODO: Don't set to zero value->intvalue = 0; } } else if (tok->astParent()->tokType() == Token::eIncDecOp) { bool inc = tok->astParent()->str() == "++"; const std::string opName(inc ? "incremented" : "decremented"); if (d == Direction::Reverse) inc = !inc; value->intvalue += (inc ? 1 : -1); /* Truncate value */ const ValueType *dst = tok->valueType(); if (dst) { const size_t sz = ValueFlow::getSizeOf(*dst, settings); if (sz > 0 && sz < sizeof(MathLib::biguint)) { long long newvalue = ValueFlow::truncateIntValue(value->intvalue, sz, dst->sign); /* Handle overflow/underflow for value bounds */ if (value->bound != ValueFlow::Value::Bound::Point) { if ((newvalue > value->intvalue && !inc) || (newvalue < value->intvalue && inc)) value->invertBound(); } value->intvalue = newvalue; } value->errorPath.emplace_back(tok, tok->str() + " is " + opName + "', new value is " + value->infoString()); } } } virtual bool useSymbolicValues() const { return true; } virtual void internalUpdate(Token* /*tok*/, const ValueFlow::Value& /*v*/, Direction /*d*/) { assert(false && "Internal update unimplemented."); } private: // Returns Action::Match if its an exact match, return Action::Read if it partially matches the lifetime Action analyzeLifetime(const Token* tok) const { if (!tok) return Action::None; if (match(tok)) return Action::Match; if (Token::simpleMatch(tok, ".") && analyzeLifetime(tok->astOperand1()) != Action::None) return Action::Read; if (astIsRHS(tok) && Token::simpleMatch(tok->astParent(), ".")) return analyzeLifetime(tok->astParent()); return Action::None; } std::unordered_map<nonneg int, const Token*> getSymbols(const Token* tok) const { std::unordered_map<nonneg int, const Token*> result; if (!tok) return result; for (const ValueFlow::Value& v : tok->values()) { if (!v.isSymbolicValue()) continue; if (v.isImpossible()) continue; if (!v.tokvalue) continue; if (v.tokvalue->exprId() == 0) continue; if (match(v.tokvalue)) continue; result[v.tokvalue->exprId()] = v.tokvalue; } return result; } Action isGlobalModified(const Token* tok) const { if (tok->function()) { if (!tok->function()->isConstexpr() && !isConstFunctionCall(tok, getSettings().library)) return Action::Invalid; } else if (getSettings().library.getFunction(tok)) { // Assume library function doesn't modify user-global variables return Action::None; } else if (Token::simpleMatch(tok->astParent(), ".") && astIsContainer(tok->astParent()->astOperand1())) { // Assume container member function doesn't modify user-global variables return Action::None; } else if (tok->tokType() == Token::eType && astIsPrimitive(tok->next())) { // Function cast does not modify global variables return Action::None; } else if (!tok->isKeyword() && Token::Match(tok, "%name% (")) { return Action::Invalid; } return Action::None; } static const std::string& invertAssign(const std::string& assign) { static std::unordered_map<std::string, std::string> lookup = {{"=", "="}, {"+=", "-="}, {"-=", "+="}, {"*=", "/="}, {"/=", "*="}, {"<<=", ">>="}, {">>=", "<<="}, {"^=", "^="}}; auto it = lookup.find(assign); if (it == lookup.end()) { return emptyString; } return it->second; } static const std::string& getAssign(const Token* tok, Direction d) { if (d == Direction::Forward) return tok->str(); return invertAssign(tok->str()); } template<class T, class U> static void assignValueIfMutable(T& x, const U& y) { x = y; } template<class T, class U> static void assignValueIfMutable(const T& /*unused*/, const U& /*unused*/) {} static std::string removeAssign(const std::string& assign) { return std::string{assign.cbegin(), assign.cend() - 1}; } template<class T, class U> static T calculateAssign(const std::string& assign, const T& x, const U& y, bool* error = nullptr) { if (assign.empty() || assign.back() != '=') { if (error) *error = true; return T{}; } if (assign == "=") return y; return calculate<T, T>(removeAssign(assign), x, y, error); } template<class Value, REQUIRES("Value must ValueFlow::Value", std::is_convertible<Value&, const ValueFlow::Value&> )> static bool evalAssignment(Value& lhsValue, const std::string& assign, const ValueFlow::Value& rhsValue) { bool error = false; if (lhsValue.isSymbolicValue() && rhsValue.isIntValue()) { if (assign != "+=" && assign != "-=") return false; assignValueIfMutable(lhsValue.intvalue, calculateAssign(assign, lhsValue.intvalue, rhsValue.intvalue, &error)); } else if (lhsValue.isIntValue() && rhsValue.isIntValue()) { assignValueIfMutable(lhsValue.intvalue, calculateAssign(assign, lhsValue.intvalue, rhsValue.intvalue, &error)); } else if (lhsValue.isFloatValue() && rhsValue.isIntValue()) { assignValueIfMutable(lhsValue.floatValue, calculateAssign(assign, lhsValue.floatValue, rhsValue.intvalue, &error)); } else { return false; } return !error; } const Token* findMatch(const Token* tok) const { return findAstNode(tok, [&](const Token* child) { return match(child); }); } bool isSameSymbolicValue(const Token* tok, ValueFlow::Value* value = nullptr) const { if (!useSymbolicValues()) return false; if (Token::Match(tok, "%assign%")) return false; const ValueFlow::Value* currValue = getValue(tok); if (!currValue) return false; // If the same symbolic value is already there then skip if (currValue->isSymbolicValue() && std::any_of(tok->values().cbegin(), tok->values().cend(), [&](const ValueFlow::Value& v) { return v.isSymbolicValue() && currValue->equalValue(v); })) return false; const bool isPoint = currValue->bound == ValueFlow::Value::Bound::Point && currValue->isIntValue(); const bool exact = !currValue->isIntValue() || currValue->isImpossible(); for (const ValueFlow::Value& v : tok->values()) { if (!v.isSymbolicValue()) continue; if (currValue->equalValue(v)) continue; const bool toImpossible = v.isImpossible() && currValue->isKnown(); if (!v.isKnown() && !toImpossible) continue; if (exact && v.intvalue != 0 && !isPoint) continue; std::vector<MathLib::bigint> r; ValueFlow::Value::Bound bound = currValue->bound; if (match(v.tokvalue)) { r = {currValue->intvalue}; } else if (!exact && findMatch(v.tokvalue)) { r = evaluate(Evaluate::Integral, v.tokvalue, tok); if (bound == ValueFlow::Value::Bound::Point) bound = v.bound; } if (!r.empty()) { if (value) { value->errorPath.insert(value->errorPath.end(), v.errorPath.cbegin(), v.errorPath.cend()); value->intvalue = r.front() + v.intvalue; if (toImpossible) value->setImpossible(); value->bound = bound; } return true; } } return false; } Action analyzeMatch(const Token* tok, Direction d) const { const Token* parent = tok->astParent(); if (d == Direction::Reverse && isGlobal() && !dependsOnThis() && Token::Match(parent, ". %name% (")) { Action a = isGlobalModified(parent->next()); if (a != Action::None) return a; } if ((astIsPointer(tok) || astIsSmartPointer(tok)) && (Token::Match(parent, "*|[") || (parent && parent->originalName() == "->")) && getIndirect(tok) <= 0) return Action::Read; Action w = isWritable(tok, d); if (w != Action::None) return w; // Check for modifications by function calls return isModified(tok); } Action analyzeToken(const Token* ref, const Token* tok, Direction d, bool inconclusiveRef) const { if (!ref) return Action::None; // If its an inconclusiveRef then ref != tok assert(!inconclusiveRef || ref != tok); bool inconclusive = false; if (match(ref)) { if (inconclusiveRef) { Action a = isModified(tok); if (a.isModified() || a.isInconclusive()) return Action::Inconclusive; } else { return analyzeMatch(tok, d) | Action::Match; } } else if (ref->isUnaryOp("*") && !match(ref->astOperand1())) { const Token* lifeTok = nullptr; for (const ValueFlow::Value& v:ref->astOperand1()->values()) { if (!v.isLocalLifetimeValue()) continue; if (lifeTok) return Action::None; lifeTok = v.tokvalue; } if (!lifeTok) return Action::None; Action la = analyzeLifetime(lifeTok); if (la.matches()) { Action a = Action::Read; if (isModified(tok).isModified()) a = Action::Invalid; if (Token::Match(tok->astParent(), "%assign%") && astIsLHS(tok)) a |= Action::Invalid; if (inconclusiveRef && a.isModified()) return Action::Inconclusive; return a; } if (la.isRead()) { return isAliasModified(tok); } return Action::None; } else if (isAlias(ref, inconclusive)) { inconclusive |= inconclusiveRef; Action a = isAliasModified(tok); if (inconclusive && a.isModified()) return Action::Inconclusive; return a; } if (isSameSymbolicValue(ref)) return Action::Read | Action::SymbolicMatch; return Action::None; } Action analyze(const Token* tok, Direction d) const override { if (invalid()) return Action::Invalid; // Follow references auto refs = followAllReferences(tok); const bool inconclusiveRefs = refs.size() != 1; if (std::none_of(refs.cbegin(), refs.cend(), [&](const ReferenceToken& ref) { return tok == ref.token; })) refs.emplace_back(ReferenceToken{tok, {}}); for (const ReferenceToken& ref:refs) { Action a = analyzeToken(ref.token, tok, d, inconclusiveRefs && ref.token != tok); if (internalMatch(ref.token)) a |= Action::Internal; if (a != Action::None) return a; } if (dependsOnThis() && exprDependsOnThis(tok, !isVariable())) return isThisModified(tok); // bailout: global non-const variables if (isGlobal() && !dependsOnThis() && Token::Match(tok, "%name% (") && !tok->variable() && !Token::simpleMatch(tok->linkAt(1), ") {")) { return isGlobalModified(tok); } return Action::None; } template<class F> std::vector<MathLib::bigint> evaluateInt(const Token* tok, F getProgramMemory) const { if (tok->hasKnownIntValue()) return {static_cast<int>(tok->values().front().intvalue)}; std::vector<MathLib::bigint> result; ProgramMemory pm = getProgramMemory(); if (Token::Match(tok, "&&|%oror%")) { if (conditionIsTrue(tok, pm, getSettings())) result.push_back(1); if (conditionIsFalse(tok, std::move(pm), getSettings())) result.push_back(0); } else { MathLib::bigint out = 0; bool error = false; execute(tok, pm, &out, &error, getSettings()); if (!error) result.push_back(out); } return result; } std::vector<MathLib::bigint> evaluateInt(const Token* tok) const { return evaluateInt(tok, [&] { return ProgramMemory{getProgramState()}; }); } std::vector<MathLib::bigint> evaluate(Evaluate e, const Token* tok, const Token* ctx = nullptr) const override { if (e == Evaluate::Integral) { return evaluateInt(tok, [&] { return pms.get(tok, ctx, getProgramState()); }); } if (e == Evaluate::ContainerEmpty) { const ValueFlow::Value* value = ValueFlow::findValue(tok->values(), settings, [](const ValueFlow::Value& v) { return v.isKnown() && v.isContainerSizeValue(); }); if (value) return {value->intvalue == 0}; ProgramMemory pm = pms.get(tok, ctx, getProgramState()); MathLib::bigint out = 0; if (pm.getContainerEmptyValue(tok->exprId(), out)) return {static_cast<int>(out)}; return {}; } return {}; } void assume(const Token* tok, bool state, unsigned int flags) override { // Update program state pms.removeModifiedVars(tok); pms.addState(tok, getProgramState()); pms.assume(tok, state, flags & Assume::ContainerEmpty); bool isCondBlock = false; const Token* parent = tok->astParent(); if (parent) { isCondBlock = Token::Match(parent->previous(), "if|while ("); } if (isCondBlock) { const Token* startBlock = parent->link()->next(); if (Token::simpleMatch(startBlock, ";") && Token::simpleMatch(parent->tokAt(-2), "} while (")) startBlock = parent->linkAt(-2); const Token* endBlock = startBlock->link(); if (state) { pms.removeModifiedVars(endBlock); pms.addState(endBlock->previous(), getProgramState()); } else { if (Token::simpleMatch(endBlock, "} else {")) pms.addState(endBlock->linkAt(2)->previous(), getProgramState()); } } if (!(flags & Assume::Quiet)) { if (flags & Assume::ContainerEmpty) { std::string s = state ? "empty" : "not empty"; addErrorPath(tok, "Assuming container is " + s); } else { std::string s = bool_to_string(state); addErrorPath(tok, "Assuming condition is " + s); } } if (!(flags & Assume::Absolute)) makeConditional(); } void updateState(const Token* tok) override { // Update program state pms.removeModifiedVars(tok); pms.addState(tok, getProgramState()); } void update(Token* tok, Action a, Direction d) override { ValueFlow::Value* value = getValue(tok); if (!value) return; ValueFlow::Value localValue; if (a.isSymbolicMatch()) { // Make a copy of the value to modify it localValue = *value; value = &localValue; isSameSymbolicValue(tok, &localValue); } if (a.isInternal()) internalUpdate(tok, *value, d); // Read first when moving forward if (d == Direction::Forward && a.isRead()) setTokenValue(tok, *value, getSettings()); if (a.isInconclusive()) (void)lowerToInconclusive(); if (a.isWrite() && tok->astParent()) { writeValue(value, tok, d); } // Read last when moving in reverse if (d == Direction::Reverse && a.isRead()) setTokenValue(tok, *value, getSettings()); } ValuePtr<Analyzer> reanalyze(Token* /*tok*/, const std::string& /*msg*/) const override { return {}; } }; static bool bifurcate(const Token* tok, const std::set<nonneg int>& varids, const Settings& settings, int depth = 20); static bool bifurcateVariableChanged(const Variable* var, const std::set<nonneg int>& varids, const Token* start, const Token* end, const Settings& settings, int depth = 20) { bool result = false; const Token* tok = start; while ((tok = findVariableChanged( tok->next(), end, var->isPointer(), var->declarationId(), var->isGlobal(), settings))) { if (Token::Match(tok->astParent(), "%assign%")) { if (!bifurcate(tok->astParent()->astOperand2(), varids, settings, depth - 1)) return true; } else { result = true; } } return result; } static bool bifurcate(const Token* tok, const std::set<nonneg int>& varids, const Settings& settings, int depth) { if (depth < 0) return false; if (!tok) return true; if (tok->hasKnownIntValue()) return true; if (tok->isConstOp()) return bifurcate(tok->astOperand1(), varids, settings, depth) && bifurcate(tok->astOperand2(), varids, settings, depth); if (tok->varId() != 0) { if (varids.count(tok->varId()) > 0) return true; const Variable* var = tok->variable(); if (!var) return false; const Token* start = var->declEndToken(); if (!start) return false; if (start->strAt(-1) == ")" || start->strAt(-1) == "}") return false; if (Token::Match(start, "; %varid% =", var->declarationId())) start = start->tokAt(2); if (var->isConst() || !bifurcateVariableChanged(var, varids, start, tok, settings, depth)) return var->isArgument() || bifurcate(start->astOperand2(), varids, settings, depth - 1); return false; } return false; } // Check if its an alias of the variable or is being aliased to this variable template<typename V> static bool isAliasOf(const Variable * var, const Token *tok, nonneg int varid, const V& values, bool* inconclusive = nullptr) { if (tok->varId() == varid) return false; if (tok->varId() == 0) return false; if (isAliasOf(tok, varid, inconclusive)) return true; if (var && !var->isPointer()) return false; // Search through non value aliases return std::any_of(values.begin(), values.end(), [&](const ValueFlow::Value& val) { if (!val.isNonValue()) return false; if (val.isInconclusive()) return false; if (val.isLifetimeValue() && !val.isLocalLifetimeValue()) return false; if (val.isLifetimeValue() && val.lifetimeKind != ValueFlow::Value::LifetimeKind::Address) return false; if (!Token::Match(val.tokvalue, ".|&|*|%var%")) return false; return astHasVar(val.tokvalue, tok->varId()); }); } struct MultiValueFlowAnalyzer : ValueFlowAnalyzer { class SelectValueFromVarIdMapRange { using M = std::unordered_map<nonneg int, ValueFlow::Value>; struct Iterator { using iterator_category = std::forward_iterator_tag; using value_type = const ValueFlow::Value; using pointer = value_type *; using reference = value_type &; using difference_type = std::ptrdiff_t; explicit Iterator(const M::const_iterator & it) : mIt(it) {} reference operator*() const { return mIt->second; } pointer operator->() const { return &mIt->second; } Iterator &operator++() { // cppcheck-suppress postfixOperator - forward iterator needs to perform post-increment mIt++; return *this; } friend bool operator==(const Iterator &a, const Iterator &b) { return a.mIt == b.mIt; } friend bool operator!=(const Iterator &a, const Iterator &b) { return a.mIt != b.mIt; } private: M::const_iterator mIt; }; public: explicit SelectValueFromVarIdMapRange(const M *m) : mMap(m) {} Iterator begin() const { return Iterator(mMap->begin()); } Iterator end() const { return Iterator(mMap->end()); } private: const M *mMap; }; std::unordered_map<nonneg int, ValueFlow::Value> values; std::unordered_map<nonneg int, const Variable*> vars; MultiValueFlowAnalyzer(const std::unordered_map<const Variable*, ValueFlow::Value>& args, const Settings& set) : ValueFlowAnalyzer(set) { for (const auto& p:args) { values[p.first->declarationId()] = p.second; vars[p.first->declarationId()] = p.first; } } virtual const std::unordered_map<nonneg int, const Variable*>& getVars() const { return vars; } const ValueFlow::Value* getValue(const Token* tok) const override { if (tok->varId() == 0) return nullptr; auto it = values.find(tok->varId()); if (it == values.end()) return nullptr; return &it->second; } ValueFlow::Value* getValue(const Token* tok) override { if (tok->varId() == 0) return nullptr; auto it = values.find(tok->varId()); if (it == values.end()) return nullptr; return &it->second; } void makeConditional() override { for (auto&& p:values) { p.second.conditional = true; } } void addErrorPath(const Token* tok, const std::string& s) override { for (auto&& p:values) { p.second.errorPath.emplace_back(tok, s); } } bool isAlias(const Token* tok, bool& inconclusive) const override { const auto range = SelectValueFromVarIdMapRange(&values); for (const auto& p:getVars()) { nonneg int const varid = p.first; const Variable* var = p.second; if (tok->varId() == varid) return true; if (isAliasOf(var, tok, varid, range, &inconclusive)) return true; } return false; } bool lowerToPossible() override { for (auto&& p:values) { if (p.second.isImpossible()) return false; p.second.changeKnownToPossible(); } return true; } bool lowerToInconclusive() override { for (auto&& p:values) { if (p.second.isImpossible()) return false; p.second.setInconclusive(); } return true; } bool isConditional() const override { for (auto&& p:values) { if (p.second.conditional) return true; if (p.second.condition) return !p.second.isImpossible(); } return false; } bool stopOnCondition(const Token* condTok) const override { if (isConditional()) return true; if (!condTok->hasKnownIntValue() && values.count(condTok->varId()) == 0) { const auto& values_ = condTok->values(); return std::any_of(values_.cbegin(), values_.cend(), [](const ValueFlow::Value& v) { return v.isSymbolicValue() && Token::Match(v.tokvalue, "%oror%|&&"); }); } return false; } bool updateScope(const Token* endBlock, bool /*modified*/) const override { const Scope* scope = endBlock->scope(); if (!scope) return false; if (scope->type == Scope::eLambda) { return std::all_of(values.cbegin(), values.cend(), [](const std::pair<nonneg int, ValueFlow::Value>& p) { return p.second.isLifetimeValue(); }); } if (scope->type == Scope::eIf || scope->type == Scope::eElse || scope->type == Scope::eWhile || scope->type == Scope::eFor) { auto pred = [](const ValueFlow::Value& value) { if (value.isKnown()) return true; if (value.isImpossible()) return true; if (value.isLifetimeValue()) return true; return false; }; if (std::all_of(values.cbegin(), values.cend(), std::bind(pred, std::bind(SelectMapValues{}, std::placeholders::_1)))) return true; if (isConditional()) return false; const Token* condTok = getCondTokFromEnd(endBlock); std::set<nonneg int> varids; std::transform(getVars().cbegin(), getVars().cend(), std::inserter(varids, varids.begin()), SelectMapKeys{}); return bifurcate(condTok, varids, getSettings()); } return false; } bool match(const Token* tok) const override { return values.count(tok->varId()) > 0; } ProgramState getProgramState() const override { ProgramState ps; for (const auto& p : values) { const Variable* var = vars.at(p.first); if (!var) continue; ps[var->nameToken()] = p.second; } return ps; } }; ValuePtr<Analyzer> makeMultiValueFlowAnalyzer(const std::unordered_map<const Variable*, ValueFlow::Value>& args, const Settings& settings) { return MultiValueFlowAnalyzer{args, settings}; } struct SingleValueFlowAnalyzer : ValueFlowAnalyzer { std::unordered_map<nonneg int, const Variable*> varids; std::unordered_map<nonneg int, const Variable*> aliases; ValueFlow::Value value; SingleValueFlowAnalyzer(ValueFlow::Value v, const Settings& s) : ValueFlowAnalyzer(s), value(std::move(v)) {} const std::unordered_map<nonneg int, const Variable*>& getVars() const { return varids; } const std::unordered_map<nonneg int, const Variable*>& getAliasedVars() const { return aliases; } const ValueFlow::Value* getValue(const Token* /*tok*/) const override { return &value; } ValueFlow::Value* getValue(const Token* /*tok*/) override { return &value; } void makeConditional() override { value.conditional = true; } bool useSymbolicValues() const override { if (value.isUninitValue()) return false; if (value.isLifetimeValue()) return false; return true; } void addErrorPath(const Token* tok, const std::string& s) override { value.errorPath.emplace_back(tok, s); } template<class T> struct SingleRange { T* x; T* begin() const { return x; } T* end() const { return x+1; } }; template<class T> static SingleRange<T> MakeSingleRange(T& x) { return {&x}; } bool isAlias(const Token* tok, bool& inconclusive) const override { if (value.isLifetimeValue()) return false; for (const auto& m: { std::ref(getVars()), std::ref(getAliasedVars()) }) { for (const auto& p:m.get()) { nonneg int const varid = p.first; const Variable* var = p.second; if (tok->varId() == varid) return true; if (isAliasOf(var, tok, varid, MakeSingleRange(value), &inconclusive)) return true; } } return false; } bool isGlobal() const override { const auto& vars = getVars(); return std::any_of(vars.cbegin(), vars.cend(), [] (const std::pair<nonneg int, const Variable*>& p) { const Variable* var = p.second; return !var->isLocal() && !var->isArgument() && !var->isConst(); }); } bool lowerToPossible() override { if (value.isImpossible()) return false; value.changeKnownToPossible(); return true; } bool lowerToInconclusive() override { if (value.isImpossible()) return false; value.setInconclusive(); return true; } bool isConditional() const override { if (value.conditional) return true; if (value.condition) return !value.isKnown() && !value.isImpossible(); return false; } bool stopOnCondition(const Token* condTok) const override { if (value.isNonValue()) return false; if (value.isImpossible()) return false; if (isConditional() && !value.isKnown() && !value.isImpossible()) return true; if (value.isSymbolicValue()) return false; ConditionState cs = analyzeCondition(condTok); return cs.isUnknownDependent(); } bool updateScope(const Token* endBlock, bool /*modified*/) const override { const Scope* scope = endBlock->scope(); if (!scope) return false; if (scope->type == Scope::eLambda) return value.isLifetimeValue(); if (scope->type == Scope::eIf || scope->type == Scope::eElse || scope->type == Scope::eWhile || scope->type == Scope::eFor) { if (value.isKnown() || value.isImpossible()) return true; if (value.isLifetimeValue()) return true; if (isConditional()) return false; const Token* condTok = getCondTokFromEnd(endBlock); std::set<nonneg int> varids2; std::transform(getVars().cbegin(), getVars().cend(), std::inserter(varids2, varids2.begin()), SelectMapKeys{}); return bifurcate(condTok, varids2, getSettings()); } return false; } ValuePtr<Analyzer> reanalyze(Token* tok, const std::string& msg) const override { ValueFlow::Value newValue = value; newValue.errorPath.emplace_back(tok, msg); return makeAnalyzer(tok, std::move(newValue), settings); } }; struct ExpressionAnalyzer : SingleValueFlowAnalyzer { const Token* expr; bool local = true; bool unknown{}; bool dependOnThis{}; bool uniqueExprId{}; ExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s) : SingleValueFlowAnalyzer(std::move(val), s), expr(e) { assert(e && e->exprId() != 0 && "Not a valid expression"); dependOnThis = exprDependsOnThis(expr); setupExprVarIds(expr); if (value.isSymbolicValue()) { dependOnThis |= exprDependsOnThis(value.tokvalue); setupExprVarIds(value.tokvalue); } uniqueExprId = expr->isUniqueExprId() && (Token::Match(expr, "%cop%") || !isVariableChanged(expr, 0, s)); } static bool nonLocal(const Variable* var, bool deref) { return !var || (!var->isLocal() && !var->isArgument()) || (deref && var->isArgument() && var->isPointer()) || var->isStatic() || var->isReference() || var->isExtern(); } void setupExprVarIds(const Token* start, int depth = 0) { if (depth > settings.vfOptions.maxExprVarIdDepth) { // TODO: add bailout message return; } visitAstNodes(start, [&](const Token* tok) { const bool top = depth == 0 && tok == start; const bool ispointer = astIsPointer(tok) || astIsSmartPointer(tok) || astIsIterator(tok); if (!top || !ispointer || value.indirect != 0) { for (const ValueFlow::Value& v : tok->values()) { if (!(v.isLocalLifetimeValue() || (ispointer && v.isSymbolicValue() && v.isKnown()))) continue; if (!v.tokvalue) continue; if (v.tokvalue == tok) continue; setupExprVarIds(v.tokvalue, depth + 1); } } if (depth == 0 && tok->isIncompleteVar()) { // TODO: Treat incomplete var as global, but we need to update // the alias variables to just expr ids instead of requiring // Variable unknown = true; return ChildrenToVisit::none; } if (tok->varId() > 0) { varids[tok->varId()] = tok->variable(); if (!Token::simpleMatch(tok->previous(), ".")) { const Variable* var = tok->variable(); if (var && var->isReference() && var->isLocal() && Token::Match(var->nameToken(), "%var% [=(]") && !isGlobalData(var->nameToken()->next()->astOperand2())) return ChildrenToVisit::none; const bool deref = tok->astParent() && (tok->astParent()->isUnaryOp("*") || (tok->astParent()->str() == "[" && tok == tok->astParent()->astOperand1())); local &= !nonLocal(tok->variable(), deref); } } return ChildrenToVisit::op1_and_op2; }); } virtual bool skipUniqueExprIds() const { return true; } bool invalid() const override { if (skipUniqueExprIds() && uniqueExprId) return true; return unknown; } ProgramState getProgramState() const override { ProgramState ps; ps[expr] = value; return ps; } bool match(const Token* tok) const override { return tok->exprId() == expr->exprId(); } bool dependsOnThis() const override { return dependOnThis; } bool isGlobal() const override { return !local; } bool isVariable() const override { return expr->varId() > 0; } Action isAliasModified(const Token* tok, int indirect) const override { if (value.isSymbolicValue() && tok->exprId() == value.tokvalue->exprId()) indirect = 0; return SingleValueFlowAnalyzer::isAliasModified(tok, indirect); } }; struct SameExpressionAnalyzer : ExpressionAnalyzer { SameExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s) : ExpressionAnalyzer(e, std::move(val), s) {} bool skipUniqueExprIds() const override { return false; } bool match(const Token* tok) const override { return isSameExpression(true, expr, tok, getSettings(), true, true); } }; ValuePtr<Analyzer> makeSameExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s) { return SameExpressionAnalyzer{e, std::move(val), s}; } struct OppositeExpressionAnalyzer : ExpressionAnalyzer { bool isNot{}; OppositeExpressionAnalyzer(bool pIsNot, const Token* e, ValueFlow::Value val, const Settings& s) : ExpressionAnalyzer(e, std::move(val), s), isNot(pIsNot) {} bool skipUniqueExprIds() const override { return false; } bool match(const Token* tok) const override { return isOppositeCond(isNot, expr, tok, getSettings(), true, true); } }; ValuePtr<Analyzer> makeOppositeExpressionAnalyzer(bool pIsNot, const Token* e, ValueFlow::Value val, const Settings& s) { return OppositeExpressionAnalyzer{pIsNot, e, std::move(val), s}; } struct SubExpressionAnalyzer : ExpressionAnalyzer { using PartialReadContainer = std::vector<std::pair<Token *, ValueFlow::Value>>; // A shared_ptr is used so partial reads can be captured even after forking std::shared_ptr<PartialReadContainer> partialReads; SubExpressionAnalyzer(const Token* e, ValueFlow::Value val, const Settings& s) : ExpressionAnalyzer(e, std::move(val), s), partialReads(std::make_shared<PartialReadContainer>()) {} SubExpressionAnalyzer(const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s) : ExpressionAnalyzer(e, std::move(val), s), partialReads(p) {} virtual bool submatch(const Token* tok, bool exact = true) const = 0; bool isAlias(const Token* tok, bool& inconclusive) const override { if (tok->exprId() == expr->exprId() && tok->astParent() && submatch(tok->astParent(), false)) return false; return ExpressionAnalyzer::isAlias(tok, inconclusive); } bool match(const Token* tok) const override { return tok->astOperand1() && tok->astOperand1()->exprId() == expr->exprId() && submatch(tok); } bool internalMatch(const Token* tok) const override { return tok->exprId() == expr->exprId() && !(astIsLHS(tok) && submatch(tok->astParent(), false)); } void internalUpdate(Token* tok, const ValueFlow::Value& v, Direction /*d*/) override { partialReads->emplace_back(tok, v); } // No reanalysis for subexpression ValuePtr<Analyzer> reanalyze(Token* /*tok*/, const std::string& /*msg*/) const override { return {}; } }; struct MemberExpressionAnalyzer : SubExpressionAnalyzer { std::string varname; MemberExpressionAnalyzer(std::string varname, const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s) : SubExpressionAnalyzer(e, std::move(val), p, s), varname(std::move(varname)) {} bool submatch(const Token* tok, bool exact) const override { if (!Token::Match(tok, ". %var%")) return false; if (!exact) return true; return tok->strAt(1) == varname; } }; ValuePtr<Analyzer> makeMemberExpressionAnalyzer(std::string varname, const Token* e, ValueFlow::Value val, const std::shared_ptr<PartialReadContainer>& p, const Settings& s) { return MemberExpressionAnalyzer{std::move(varname), e, std::move(val), p, s}; } struct ContainerExpressionAnalyzer : ExpressionAnalyzer { ContainerExpressionAnalyzer(const Token* expr, ValueFlow::Value val, const Settings& s) : ExpressionAnalyzer(expr, std::move(val), s) {} bool match(const Token* tok) const override { return tok->exprId() == expr->exprId() || (astIsIterator(tok) && isAliasOf(tok, expr->exprId())); } Action isWritable(const Token* tok, Direction /*d*/) const override { if (astIsIterator(tok)) return Action::None; if (!getValue(tok)) return Action::None; if (!tok->valueType()) return Action::None; if (!astIsContainer(tok)) return Action::None; const Token* parent = tok->astParent(); const Library::Container* container = getLibraryContainer(tok); if (container->stdStringLike && Token::simpleMatch(parent, "+=") && astIsLHS(tok) && parent->astOperand2()) { const Token* rhs = parent->astOperand2(); if (rhs->tokType() == Token::eString) return Action::Read | Action::Write | Action::Incremental; const Library::Container* rhsContainer = getLibraryContainer(rhs); if (rhsContainer && rhsContainer->stdStringLike) { if (std::any_of(rhs->values().cbegin(), rhs->values().cend(), [&](const ValueFlow::Value &rhsval) { return rhsval.isKnown() && rhsval.isContainerSizeValue(); })) return Action::Read | Action::Write | Action::Incremental; } } else if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) { const Library::Container::Action action = container->getAction(tok->astParent()->strAt(1)); if (action == Library::Container::Action::PUSH || action == Library::Container::Action::POP || action == Library::Container::Action::APPEND) { // TODO: handle more actions? std::vector<const Token*> args = getArguments(tok->tokAt(3)); if (args.size() < 2 || action == Library::Container::Action::APPEND) return Action::Read | Action::Write | Action::Incremental; } } return Action::None; } void writeValue(ValueFlow::Value* val, const Token* tok, Direction d) const override { if (!val) return; if (!tok->astParent()) return; if (!tok->valueType()) return; if (!astIsContainer(tok)) return; const Token* parent = tok->astParent(); const Library::Container* container = getLibraryContainer(tok); int n = 0; if (container->stdStringLike && Token::simpleMatch(parent, "+=") && parent->astOperand2()) { const Token* rhs = parent->astOperand2(); const Library::Container* rhsContainer = getLibraryContainer(rhs); if (rhs->tokType() == Token::eString) n = Token::getStrLength(rhs); else if (rhsContainer && rhsContainer->stdStringLike) { auto it = std::find_if(rhs->values().begin(), rhs->values().end(), [&](const ValueFlow::Value& rhsval) { return rhsval.isKnown() && rhsval.isContainerSizeValue(); }); if (it != rhs->values().end()) n = it->intvalue; } } else if (astIsLHS(tok) && Token::Match(tok->astParent(), ". %name% (")) { const Library::Container::Action action = container->getAction(tok->astParent()->strAt(1)); switch (action) { case Library::Container::Action::PUSH: n = 1; break; case Library::Container::Action::POP: n = -1; break; case Library::Container::Action::APPEND: { std::vector<const Token*> args = getArguments(tok->astParent()->tokAt(2)); if (args.size() == 1) // TODO: handle overloads n = ValueFlow::valueFlowGetStrLength(tok->astParent()->tokAt(3)); if (n == 0) // TODO: handle known empty append val->setPossible(); break; } default: break; } } if (d == Direction::Reverse) val->intvalue -= n; else val->intvalue += n; } int getIndirect(const Token* tok) const override { if (tok->valueType()) { return tok->valueType()->pointer; } return ValueFlowAnalyzer::getIndirect(tok); } Action isModified(const Token* tok) const override { Action read = Action::Read; // An iterator won't change the container size if (astIsIterator(tok)) return read; if (Token::Match(tok->astParent(), "%assign%") && astIsLHS(tok)) return Action::Invalid; if (isLikelyStreamRead(tok->astParent())) return Action::Invalid; if (astIsContainer(tok) && ValueFlow::isContainerSizeChanged(tok, getIndirect(tok), getSettings())) return read | Action::Invalid; return read; } }; static const Token* solveExprValue(const Token* expr, ValueFlow::Value& value) { return ValueFlow::solveExprValue( expr, [](const Token* tok) -> std::vector<MathLib::bigint> { if (tok->hasKnownIntValue()) return {tok->values().front().intvalue}; return {}; }, value); } ValuePtr<Analyzer> makeAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings) { if (value.isContainerSizeValue()) return ContainerExpressionAnalyzer(exprTok, std::move(value), settings); const Token* expr = solveExprValue(exprTok, value); return ExpressionAnalyzer(expr, std::move(value), settings); } ValuePtr<Analyzer> makeReverseAnalyzer(const Token* exprTok, ValueFlow::Value value, const Settings& settings) { if (value.isContainerSizeValue()) return ContainerExpressionAnalyzer(exprTok, std::move(value), settings); return ExpressionAnalyzer(exprTok, std::move(value), settings); }
57,967
C++
.cpp
1,416
30.492232
184
0.56257
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,188
symboldatabase.cpp
danmar_cppcheck/lib/symboldatabase.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- #include "symboldatabase.h" #include "astutils.h" #include "errorlogger.h" #include "errortypes.h" #include "keywords.h" #include "library.h" #include "mathlib.h" #include "path.h" #include "platform.h" #include "settings.h" #include "standards.h" #include "templatesimplifier.h" #include "token.h" #include "tokenize.h" #include "tokenlist.h" #include "utils.h" #include "valueflow.h" #include <algorithm> #include <cassert> #include <cstring> #include <initializer_list> #include <iomanip> #include <iostream> #include <iterator> #include <sstream> #include <stack> #include <string> #include <tuple> #include <type_traits> #include <unordered_map> #include <unordered_set> //--------------------------------------------------------------------------- SymbolDatabase::SymbolDatabase(Tokenizer& tokenizer, const Settings& settings, ErrorLogger& errorLogger) : mTokenizer(tokenizer), mSettings(settings), mErrorLogger(errorLogger) { if (!mTokenizer.tokens()) return; if (mSettings.platform.defaultSign == 's' || mSettings.platform.defaultSign == 'S') mDefaultSignedness = ValueType::SIGNED; else if (mSettings.platform.defaultSign == 'u' || mSettings.platform.defaultSign == 'U') mDefaultSignedness = ValueType::UNSIGNED; else mDefaultSignedness = ValueType::UNKNOWN_SIGN; createSymbolDatabaseFindAllScopes(); createSymbolDatabaseClassInfo(); createSymbolDatabaseVariableInfo(); createSymbolDatabaseCopyAndMoveConstructors(); createSymbolDatabaseFunctionScopes(); createSymbolDatabaseClassAndStructScopes(); createSymbolDatabaseFunctionReturnTypes(); createSymbolDatabaseNeedInitialization(); createSymbolDatabaseVariableSymbolTable(); createSymbolDatabaseSetScopePointers(); createSymbolDatabaseSetVariablePointers(); createSymbolDatabaseSetTypePointers(); setValueTypeInTokenList(false); createSymbolDatabaseSetFunctionPointers(true); createSymbolDatabaseSetSmartPointerType(); setValueTypeInTokenList(false); createSymbolDatabaseEnums(); createSymbolDatabaseEscapeFunctions(); createSymbolDatabaseIncompleteVars(); createSymbolDatabaseExprIds(); debugSymbolDatabase(); } static const Token* skipScopeIdentifiers(const Token* tok) { if (Token::Match(tok, ":: %name%")) tok = tok->next(); while (Token::Match(tok, "%name% ::") || (Token::Match(tok, "%name% <") && Token::Match(tok->linkAt(1), ">|>> ::"))) { if (tok->strAt(1) == "::") tok = tok->tokAt(2); else tok = tok->linkAt(1)->tokAt(2); } return tok; } static bool isExecutableScope(const Token* tok) { if (!Token::simpleMatch(tok, "{")) return false; const Token * tok2 = tok->link()->previous(); if (Token::simpleMatch(tok2, "; }")) return true; if (tok2 == tok) return false; if (Token::simpleMatch(tok2, "} }")) { // inner scope const Token* startTok = tok2->link(); if (Token::Match(startTok->previous(), "do|try|else {")) return true; if (Token::Match(startTok->previous(), ")|] {")) return !findLambdaStartToken(tok2); return isExecutableScope(startTok); } return false; } const Token* SymbolDatabase::isEnumDefinition(const Token* tok) { if (!Token::Match(tok, "enum class| %name%| {|:")) return nullptr; while (!Token::Match(tok, "[{:]")) tok = tok->next(); if (tok->str() == "{") return tok; tok = tok->next(); // skip ':' while (Token::Match(tok, "%name%|::")) tok = tok->next(); return Token::simpleMatch(tok, "{") ? tok : nullptr; } void SymbolDatabase::createSymbolDatabaseFindAllScopes() { // create global scope scopeList.emplace_back(this, nullptr, nullptr); // pointer to current scope Scope *scope = &scopeList.back(); // Store the ending of init lists std::stack<std::pair<const Token*, const Scope*>> endInitList; auto inInitList = [&] { if (endInitList.empty()) return false; return endInitList.top().second == scope; }; std::stack<const Token*> inIfCondition; auto addLambda = [this, &scope](const Token* tok, const Token* lambdaEndToken) -> const Token* { const Token* lambdaStartToken = lambdaEndToken->link(); const Token* argStart = lambdaStartToken->astParent(); const Token* funcStart = Token::simpleMatch(argStart, "[") ? argStart : argStart->astParent(); const Function* function = addGlobalFunction(scope, tok, argStart, funcStart); if (!function) mTokenizer.syntaxError(tok); return lambdaStartToken; }; // Store current access in each scope (depends on evaluation progress) std::map<const Scope*, AccessControl> access; // find all scopes for (const Token *tok = mTokenizer.tokens(); tok; tok = tok ? tok->next() : nullptr) { // #5593 suggested to add here: mErrorLogger.reportProgress(mTokenizer.list.getSourceFilePath(), "SymbolDatabase", tok->progressValue()); // Locate next class if ((tok->isCpp() && tok->isKeyword() && ((Token::Match(tok, "class|struct|union|namespace ::| %name% final| {|:|::|<") && !Token::Match(tok->previous(), "new|friend|const|enum|typedef|mutable|volatile|using|)|(|<")) || isEnumDefinition(tok))) || (tok->isC() && tok->isKeyword() && Token::Match(tok, "struct|union|enum %name% {"))) { const Token *tok2 = tok->tokAt(2); if (tok->strAt(1) == "::") tok2 = tok2->next(); else if (tok->isCpp() && tok->strAt(1) == "class") tok2 = tok2->next(); while (Token::Match(tok2, ":: %name%")) tok2 = tok2->tokAt(2); while (Token::Match(tok2, "%name% :: %name%")) tok2 = tok2->tokAt(2); // skip over template args while (tok2 && tok2->str() == "<" && tok2->link()) { tok2 = tok2->link()->next(); while (Token::Match(tok2, ":: %name%")) tok2 = tok2->tokAt(2); } // skip over final if (tok2 && tok2->isCpp() && Token::simpleMatch(tok2, "final")) tok2 = tok2->next(); // make sure we have valid code if (!Token::Match(tok2, "{|:")) { // check for qualified variable if (tok2 && tok2->next()) { if (tok2->strAt(1) == ";") tok = tok2->next(); else if (Token::simpleMatch(tok2->next(), "= {") && Token::simpleMatch(tok2->linkAt(2), "} ;")) tok = tok2->linkAt(2)->next(); else if (Token::Match(tok2->next(), "(|{") && tok2->linkAt(1)->strAt(1) == ";") tok = tok2->linkAt(1)->next(); // skip variable declaration else if (Token::Match(tok2, "*|&|>")) continue; else if (Token::Match(tok2, "%name% (") && Tokenizer::isFunctionHead(tok2->next(), "{;")) continue; else if (Token::Match(tok2, "%name% [|=")) continue; // skip template else if (Token::simpleMatch(tok2, ";") && Token::Match(tok->previous(), "template|> class|struct")) { tok = tok2; continue; } // forward declaration else if (Token::simpleMatch(tok2, ";") && Token::Match(tok, "class|struct|union")) { // TODO: see if it can be used tok = tok2; continue; } // skip constructor else if (Token::simpleMatch(tok2, "(") && Token::simpleMatch(tok2->link(), ") ;")) { tok = tok2->link()->next(); continue; } else throw InternalError(tok2, "SymbolDatabase bailout; unhandled code", InternalError::SYNTAX); continue; } break; // bail } const Token * name = tok->next(); if (name->str() == "class" && name->strAt(-1) == "enum") name = name->next(); Scope *new_scope = findScope(name, scope); if (new_scope) { // only create base list for classes and structures if (new_scope->isClassOrStruct()) { // goto initial '{' if (!new_scope->definedType) mTokenizer.syntaxError(nullptr); // #6808 tok2 = new_scope->definedType->initBaseInfo(tok, tok2); // make sure we have valid code if (!tok2) { break; } } // definition may be different than declaration if (tok->isCpp() && tok->str() == "class") { access[new_scope] = AccessControl::Private; new_scope->type = Scope::eClass; } else if (tok->str() == "struct") { access[new_scope] = AccessControl::Public; new_scope->type = Scope::eStruct; } new_scope->classDef = tok; new_scope->setBodyStartEnd(tok2); // make sure we have valid code if (!new_scope->bodyEnd) { mTokenizer.syntaxError(tok); } scope = new_scope; tok = tok2; } else { scopeList.emplace_back(this, tok, scope); new_scope = &scopeList.back(); if (tok->str() == "class") access[new_scope] = AccessControl::Private; else if (tok->str() == "struct" || tok->str() == "union") access[new_scope] = AccessControl::Public; // fill typeList... if (new_scope->isClassOrStructOrUnion() || new_scope->type == Scope::eEnum) { Type* new_type = findType(name, scope); if (!new_type) { typeList.emplace_back(new_scope->classDef, new_scope, scope); new_type = &typeList.back(); scope->definedTypesMap[new_type->name()] = new_type; } else new_type->classScope = new_scope; new_scope->definedType = new_type; } // only create base list for classes and structures if (new_scope->isClassOrStruct()) { // goto initial '{' tok2 = new_scope->definedType->initBaseInfo(tok, tok2); // make sure we have valid code if (!tok2) { mTokenizer.syntaxError(tok); } } else if (new_scope->type == Scope::eEnum) { if (tok2->str() == ":") { tok2 = tok2->tokAt(2); while (Token::Match(tok2, "%name%|::")) tok2 = tok2->next(); } } new_scope->setBodyStartEnd(tok2); // make sure we have valid code if (!new_scope->bodyEnd) { mTokenizer.syntaxError(tok); } if (new_scope->type == Scope::eEnum) { tok2 = new_scope->addEnum(tok); scope->nestedList.push_back(new_scope); if (!tok2) mTokenizer.syntaxError(tok); } else { // make the new scope the current scope scope->nestedList.push_back(new_scope); scope = new_scope; } tok = tok2; } } // Namespace and unknown macro (#3854) else if (tok->isCpp() && tok->isKeyword() && Token::Match(tok, "namespace %name% %type% (") && tok->tokAt(2)->isUpperCaseName() && Token::simpleMatch(tok->linkAt(3), ") {")) { scopeList.emplace_back(this, tok, scope); Scope *new_scope = &scopeList.back(); access[new_scope] = AccessControl::Public; const Token *tok2 = tok->linkAt(3)->next(); new_scope->setBodyStartEnd(tok2); // make sure we have valid code if (!new_scope->bodyEnd) { scopeList.pop_back(); break; } // make the new scope the current scope scope->nestedList.push_back(new_scope); scope = &scopeList.back(); tok = tok2; } // forward declaration else if (tok->isKeyword() && Token::Match(tok, "class|struct|union %name% ;") && tok->strAt(-1) != "friend") { if (!findType(tok->next(), scope)) { // fill typeList.. typeList.emplace_back(tok, nullptr, scope); Type* new_type = &typeList.back(); scope->definedTypesMap[new_type->name()] = new_type; } tok = tok->tokAt(2); } // using namespace else if (tok->isCpp() && tok->isKeyword() && Token::Match(tok, "using namespace ::| %type% ;|::")) { Scope::UsingInfo using_info; using_info.start = tok; // save location using_info.scope = findNamespace(tok->tokAt(2), scope); scope->usingList.push_back(using_info); // check for global namespace if (tok->strAt(2) == "::") tok = tok->tokAt(4); else tok = tok->tokAt(3); // skip over qualification while (Token::Match(tok, "%type% ::")) tok = tok->tokAt(2); } // using type alias else if (tok->isCpp() && tok->isKeyword() && Token::Match(tok, "using %name% =") && !tok->tokAt(2)->isSimplifiedTypedef()) { if (tok->strAt(-1) != ">" && !findType(tok->next(), scope)) { // fill typeList.. typeList.emplace_back(tok, nullptr, scope); Type* new_type = &typeList.back(); scope->definedTypesMap[new_type->name()] = new_type; } tok = tok->tokAt(3); while (tok && tok->str() != ";") { if (Token::simpleMatch(tok, "decltype (")) tok = tok->linkAt(1); else tok = tok->next(); } } // unnamed struct and union else if (tok->isKeyword() && Token::Match(tok, "struct|union {") && Token::Match(tok->linkAt(1), "} *|&| %name% ;|[|=")) { scopeList.emplace_back(this, tok, scope); Scope *new_scope = &scopeList.back(); access[new_scope] = AccessControl::Public; const Token* varNameTok = tok->linkAt(1)->next(); if (varNameTok->str() == "*") { varNameTok = varNameTok->next(); } else if (varNameTok->str() == "&") { varNameTok = varNameTok->next(); } typeList.emplace_back(tok, new_scope, scope); { Type* new_type = &typeList.back(); new_scope->definedType = new_type; scope->definedTypesMap[new_type->name()] = new_type; } scope->addVariable(varNameTok, tok, tok, access[scope], new_scope->definedType, scope, mSettings); const Token *tok2 = tok->next(); new_scope->setBodyStartEnd(tok2); // make sure we have valid code if (!new_scope->bodyEnd) { scopeList.pop_back(); break; } // make the new scope the current scope scope->nestedList.push_back(new_scope); scope = new_scope; tok = tok2; } // anonymous struct, union and namespace else if (tok->isKeyword() && ((Token::Match(tok, "struct|union {") && Token::simpleMatch(tok->linkAt(1), "} ;")) || Token::simpleMatch(tok, "namespace {"))) { scopeList.emplace_back(this, tok, scope); Scope *new_scope = &scopeList.back(); access[new_scope] = AccessControl::Public; const Token *tok2 = tok->next(); new_scope->setBodyStartEnd(tok2); typeList.emplace_back(tok, new_scope, scope); { Type* new_type = &typeList.back(); new_scope->definedType = new_type; scope->definedTypesMap[new_type->name()] = new_type; } // make sure we have valid code if (!new_scope->bodyEnd) { scopeList.pop_back(); break; } // make the new scope the current scope scope->nestedList.push_back(new_scope); scope = new_scope; tok = tok2; } // forward declared enum else if (tok->isKeyword() && (Token::Match(tok, "enum class| %name% ;") || Token::Match(tok, "enum class| %name% : %name% ;"))) { typeList.emplace_back(tok, nullptr, scope); Type* new_type = &typeList.back(); scope->definedTypesMap[new_type->name()] = new_type; tok = tok->tokAt(2); } // check for end of scope else if (tok == scope->bodyEnd) { do { access.erase(scope); scope = const_cast<Scope*>(scope->nestedIn); } while (scope->type != Scope::eGlobal && succeeds(tok, scope->bodyEnd)); continue; } // check for end of init list else if (inInitList() && tok == endInitList.top().first) { endInitList.pop(); continue; } // check if in class or structure or union else if (scope->isClassOrStructOrUnion()) { const Token *funcStart = nullptr; const Token *argStart = nullptr; const Token *declEnd = nullptr; // What section are we in.. if (tok->str() == "private:") access[scope] = AccessControl::Private; else if (tok->str() == "protected:") access[scope] = AccessControl::Protected; else if (tok->str() == "public:" || tok->str() == "__published:") access[scope] = AccessControl::Public; else if (Token::Match(tok, "public|protected|private %name% :")) { if (tok->str() == "private") access[scope] = AccessControl::Private; else if (tok->str() == "protected") access[scope] = AccessControl::Protected; else access[scope] = AccessControl::Public; tok = tok->tokAt(2); } // class function? else if (isFunction(tok, scope, funcStart, argStart, declEnd)) { if (tok->strAt(-1) != "::" || tok->strAt(-2) == scope->className) { Function function(tok, scope, funcStart, argStart); // save the access type function.access = access[scope]; const Token *end = function.argDef->link(); // count the number of constructors if (function.isConstructor()) scope->numConstructors++; // assume implementation is inline (definition and implementation same) function.token = function.tokenDef; function.arg = function.argDef; // out of line function if (const Token *endTok = Tokenizer::isFunctionHead(end, ";")) { tok = endTok; scope->addFunction(std::move(function)); } // inline function else { // find start of function '{' bool foundInitList = false; while (end && end->str() != "{" && end->str() != ";") { if (end->link() && Token::Match(end, "(|<")) { end = end->link(); } else if (foundInitList && Token::Match(end, "%name%|> {") && Token::Match(end->linkAt(1), "} ,|{")) { end = end->linkAt(1); } else { if (end->str() == ":") foundInitList = true; end = end->next(); } } if (!end || end->str() == ";") continue; scope->addFunction(function); Function* funcptr = &scope->functionList.back(); const Token *tok2 = funcStart; addNewFunction(scope, tok2); if (scope) { scope->functionOf = function.nestedIn; scope->function = funcptr; scope->function->functionScope = scope; } tok = tok2; } } // nested class or friend function? else { /** @todo check entire qualification for match */ const Scope * const nested = scope->findInNestedListRecursive(tok->strAt(-2)); if (nested) addClassFunction(scope, tok, argStart); else { /** @todo handle friend functions */ } } } // friend class declaration? else if (tok->isCpp() && tok->isKeyword() && Token::Match(tok, "friend class|struct| ::| %any% ;|::")) { Type::FriendInfo friendInfo; // save the name start friendInfo.nameStart = tok->strAt(1) == "class" ? tok->tokAt(2) : tok->next(); friendInfo.nameEnd = friendInfo.nameStart; // skip leading "::" if (friendInfo.nameEnd->str() == "::") friendInfo.nameEnd = friendInfo.nameEnd->next(); // skip qualification "name ::" while (friendInfo.nameEnd && friendInfo.nameEnd->strAt(1) == "::") friendInfo.nameEnd = friendInfo.nameEnd->tokAt(2); // fill this in after parsing is complete friendInfo.type = nullptr; if (!scope->definedType) mTokenizer.syntaxError(tok); scope->definedType->friendList.push_back(friendInfo); } } else if (scope->type == Scope::eNamespace || scope->type == Scope::eGlobal) { const Token *funcStart = nullptr; const Token *argStart = nullptr; const Token *declEnd = nullptr; // function? if (isFunction(tok, scope, funcStart, argStart, declEnd)) { // has body? if (declEnd && declEnd->str() == "{") { tok = funcStart; // class function if (tok->previous() && tok->strAt(-1) == "::") addClassFunction(scope, tok, argStart); // class destructor else if (tok->previous() && tok->strAt(-1) == "~" && tok->strAt(-2) == "::") addClassFunction(scope, tok, argStart); // regular function else { const Function* const function = addGlobalFunction(scope, tok, argStart, funcStart); if (!function) mTokenizer.syntaxError(tok); } // syntax error? if (!scope) mTokenizer.syntaxError(tok); } // function prototype? else if (declEnd && declEnd->str() == ";") { if (tok->astParent() && tok->astParent()->str() == "::" && Token::Match(declEnd->previous(), "default|delete")) { addClassFunction(scope, tok, argStart); continue; } bool newFunc = true; // Is this function already in the database? auto range = scope->functionMap.equal_range(tok->str()); for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) { if (it->second->argsMatch(scope, it->second->argDef, argStart, emptyString, 0)) { newFunc = false; break; } } // save function prototype in database if (newFunc) { addGlobalFunctionDecl(scope, tok, argStart, funcStart); } tok = declEnd; continue; } } else if (const Token *lambdaEndToken = findLambdaEndToken(tok)) { tok = addLambda(tok, lambdaEndToken); } } else if (scope->isExecutable()) { if (tok->isKeyword() && Token::Match(tok, "else|try|do {")) { const Token* tok1 = tok->next(); if (tok->str() == "else") scopeList.emplace_back(this, tok, scope, Scope::eElse, tok1); else if (tok->str() == "do") scopeList.emplace_back(this, tok, scope, Scope::eDo, tok1); else //if (tok->str() == "try") scopeList.emplace_back(this, tok, scope, Scope::eTry, tok1); tok = tok1; scope->nestedList.push_back(&scopeList.back()); scope = &scopeList.back(); } else if (tok->isKeyword() && Token::Match(tok, "if|for|while|catch|switch (") && Token::simpleMatch(tok->linkAt(1), ") {")) { const Token *scopeStartTok = tok->linkAt(1)->next(); if (tok->str() == "if") scopeList.emplace_back(this, tok, scope, Scope::eIf, scopeStartTok); else if (tok->str() == "for") { scopeList.emplace_back(this, tok, scope, Scope::eFor, scopeStartTok); } else if (tok->str() == "while") scopeList.emplace_back(this, tok, scope, Scope::eWhile, scopeStartTok); else if (tok->str() == "catch") { scopeList.emplace_back(this, tok, scope, Scope::eCatch, scopeStartTok); } else // if (tok->str() == "switch") scopeList.emplace_back(this, tok, scope, Scope::eSwitch, scopeStartTok); scope->nestedList.push_back(&scopeList.back()); scope = &scopeList.back(); if (scope->type == Scope::eFor) scope->checkVariable(tok->tokAt(2), AccessControl::Local, mSettings); // check for variable declaration and add it to new scope if found else if (scope->type == Scope::eCatch) scope->checkVariable(tok->tokAt(2), AccessControl::Throw, mSettings); // check for variable declaration and add it to new scope if found tok = tok->next(); inIfCondition.push(scopeStartTok); } else if (Token::Match(tok, "%var% {")) { endInitList.emplace(tok->linkAt(1), scope); tok = tok->next(); } else if (const Token *lambdaEndToken = findLambdaEndToken(tok)) { tok = addLambda(tok, lambdaEndToken); } else if (tok->str() == "{") { if (inInitList()) { endInitList.emplace(tok->link(), scope); } else if (!inIfCondition.empty() && tok == inIfCondition.top()) { inIfCondition.pop(); } else if (isExecutableScope(tok)) { scopeList.emplace_back(this, tok, scope, Scope::eUnconditional, tok); scope->nestedList.push_back(&scopeList.back()); scope = &scopeList.back(); } else { endInitList.emplace(tok->link(), scope); } } else if (Token::Match(tok, "extern %type%")) { const Token * ftok = tok->next(); while (Token::Match(ftok, "%name%|*|&")) ftok = ftok->next(); if (!ftok || ftok->str() != "(") continue; ftok = ftok->previous(); if (Token::simpleMatch(ftok->linkAt(1), ") ;")) { const Token *funcStart = nullptr; const Token *argStart = nullptr; const Token *declEnd = nullptr; if (isFunction(ftok, scope, funcStart, argStart, declEnd)) { if (declEnd && declEnd->str() == ";") { bool newFunc = true; // Is this function already in the database? auto range = scope->functionMap.equal_range(ftok->str()); for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) { if (it->second->argsMatch(scope, it->second->argDef, argStart, emptyString, 0)) { newFunc = false; break; } } // save function prototype in database if (newFunc) { Function function(ftok, scope, funcStart, argStart); if (function.isExtern()) { scope->addFunction(std::move(function)); tok = declEnd; } } } } } } // syntax error? if (!scope) mTokenizer.syntaxError(tok); // End of scope or list should be handled above if (tok->str() == "}") mTokenizer.syntaxError(tok); } } } void SymbolDatabase::createSymbolDatabaseClassInfo() { if (mTokenizer.isC()) return; // fill in using info for (Scope& scope : scopeList) { for (Scope::UsingInfo& usingInfo : scope.usingList) { // only find if not already found if (usingInfo.scope == nullptr) { // check scope for match const Scope * const found = findScope(usingInfo.start->tokAt(2), &scope); if (found) { // set found scope usingInfo.scope = found; break; } } } } // fill in base class info for (Type& type : typeList) { // finish filling in base class info for (Type::BaseInfo & i : type.derivedFrom) { const Type* found = findType(i.nameTok, type.enclosingScope, /*lookOutside*/ true); if (found && found->findDependency(&type)) { // circular dependency //mTokenizer.syntaxError(nullptr); } else { i.type = found; } } } // fill in friend info for (Type & type : typeList) { for (Type::FriendInfo &friendInfo : type.friendList) { friendInfo.type = findType(friendInfo.nameStart, type.enclosingScope); } } } void SymbolDatabase::createSymbolDatabaseVariableInfo() { // fill in variable info for (Scope& scope : scopeList) { // find variables scope.getVariableList(mSettings); } // fill in function arguments for (Scope& scope : scopeList) { std::list<Function>::iterator func; for (func = scope.functionList.begin(); func != scope.functionList.end(); ++func) { // add arguments func->addArguments(this, &scope); } } } void SymbolDatabase::createSymbolDatabaseCopyAndMoveConstructors() { // fill in class and struct copy/move constructors for (Scope& scope : scopeList) { if (!scope.isClassOrStruct()) continue; std::list<Function>::iterator func; for (func = scope.functionList.begin(); func != scope.functionList.end(); ++func) { if (!func->isConstructor() || func->minArgCount() != 1) continue; const Variable* firstArg = func->getArgumentVar(0); if (firstArg->type() == scope.definedType) { if (firstArg->isRValueReference()) func->type = Function::eMoveConstructor; else if (firstArg->isReference() && !firstArg->isPointer()) func->type = Function::eCopyConstructor; } if (func->type == Function::eCopyConstructor || func->type == Function::eMoveConstructor) scope.numCopyOrMoveConstructors++; } } } void SymbolDatabase::createSymbolDatabaseFunctionScopes() { // fill in function scopes for (const Scope & scope : scopeList) { if (scope.type == Scope::eFunction) functionScopes.push_back(&scope); } } void SymbolDatabase::createSymbolDatabaseClassAndStructScopes() { // fill in class and struct scopes for (const Scope& scope : scopeList) { if (scope.isClassOrStruct()) classAndStructScopes.push_back(&scope); } } void SymbolDatabase::createSymbolDatabaseFunctionReturnTypes() { // fill in function return types for (Scope& scope : scopeList) { std::list<Function>::iterator func; for (func = scope.functionList.begin(); func != scope.functionList.end(); ++func) { // add return types if (func->retDef) { const Token *type = func->retDef; while (Token::Match(type, "static|const|struct|union|enum")) type = type->next(); if (type) { func->retType = findVariableTypeInBase(&scope, type); if (!func->retType) func->retType = findTypeInNested(type, func->nestedIn); } } } } } void SymbolDatabase::createSymbolDatabaseNeedInitialization() { if (mTokenizer.isC()) { // For C code it is easy, as there are no constructors and no default values for (const Scope& scope : scopeList) { if (scope.definedType) scope.definedType->needInitialization = Type::NeedInitialization::True; } } else { // For C++, it is more difficult: Determine if user defined type needs initialization... unsigned int unknowns = 0; // stop checking when there are no unknowns unsigned int retry = 0; // bail if we don't resolve all the variable types for some reason do { unknowns = 0; for (Scope& scope : scopeList) { if (!scope.isClassOrStructOrUnion()) continue; if (scope.classDef && Token::simpleMatch(scope.classDef->previous(), ">")) // skip uninstantiated template continue; if (!scope.definedType) { mBlankTypes.emplace_back(); scope.definedType = &mBlankTypes.back(); } if (scope.isClassOrStruct() && scope.definedType->needInitialization == Type::NeedInitialization::Unknown) { // check for default constructor bool hasDefaultConstructor = false; for (const Function& func : scope.functionList) { if (func.type == Function::eConstructor) { // check for no arguments: func ( ) if (func.argCount() == 0) { hasDefaultConstructor = true; break; } /** check for arguments with default values */ if (func.argCount() == func.initializedArgCount()) { hasDefaultConstructor = true; break; } } } // User defined types with user defined default constructor doesn't need initialization. // We assume the default constructor initializes everything. // Another check will figure out if the constructor actually initializes everything. if (hasDefaultConstructor) scope.definedType->needInitialization = Type::NeedInitialization::False; // check each member variable to see if it needs initialization else { bool needInitialization = false; bool unknown = false; for (const Variable& var: scope.varlist) { if (var.isStatic()) continue; if (var.isClass() && !var.isReference()) { if (var.type()) { // does this type need initialization? if (var.type()->needInitialization == Type::NeedInitialization::True && !var.hasDefault() && !var.isStatic()) needInitialization = true; else if (var.type()->needInitialization == Type::NeedInitialization::Unknown) { if (!(var.valueType() && var.valueType()->type == ValueType::CONTAINER)) unknown = true; } } } else if (!var.hasDefault()) { needInitialization = true; break; } } if (needInitialization) scope.definedType->needInitialization = Type::NeedInitialization::True; else if (!unknown) scope.definedType->needInitialization = Type::NeedInitialization::False; else { if (scope.definedType->needInitialization == Type::NeedInitialization::Unknown) unknowns++; } } } else if (scope.type == Scope::eUnion && scope.definedType->needInitialization == Type::NeedInitialization::Unknown) scope.definedType->needInitialization = Type::NeedInitialization::True; } retry++; } while (unknowns && retry < 100); // this shouldn't happen so output a debug warning if (retry == 100 && mSettings.debugwarnings) { for (const Scope& scope : scopeList) { if (scope.isClassOrStruct() && scope.definedType->needInitialization == Type::NeedInitialization::Unknown) debugMessage(scope.classDef, "debug", "SymbolDatabase couldn't resolve all user defined types."); } } } } void SymbolDatabase::createSymbolDatabaseVariableSymbolTable() { // create variable symbol table mVariableList.resize(mTokenizer.varIdCount() + 1); std::fill_n(mVariableList.begin(), mVariableList.size(), nullptr); // check all scopes for variables for (Scope& scope : scopeList) { // add all variables for (Variable& var: scope.varlist) { const int varId = var.declarationId(); if (varId) mVariableList[varId] = &var; // fix up variables without type if (!var.type() && !var.typeStartToken()->isStandardType()) { const Type *type = findType(var.typeStartToken(), &scope); if (type) var.type(type); } } // add all function parameters for (Function& func : scope.functionList) { for (Variable& arg: func.argumentList) { // check for named parameters if (arg.nameToken() && arg.declarationId()) { const int declarationId = arg.declarationId(); mVariableList[declarationId] = &arg; // fix up parameters without type if (!arg.type() && !arg.typeStartToken()->isStandardType()) { const Type *type = findTypeInNested(arg.typeStartToken(), &scope); if (type) arg.type(type); } } } } } // fill in missing variables if possible for (const Scope *func: functionScopes) { for (const Token *tok = func->bodyStart->next(); tok && tok != func->bodyEnd; tok = tok->next()) { // check for member variable if (!Token::Match(tok, "%var% .|[")) continue; const Token* tokDot = tok->next(); while (Token::simpleMatch(tokDot, "[")) tokDot = tokDot->link()->next(); if (!Token::Match(tokDot, ". %var%")) continue; const Token *member = tokDot->next(); if (mVariableList[member->varId()] == nullptr) { const Variable *var1 = mVariableList[tok->varId()]; if (var1 && var1->typeScope()) { const Variable* memberVar = var1->typeScope()->getVariable(member->str()); if (memberVar) { // add this variable to the look up table mVariableList[member->varId()] = memberVar; } } } } } } void SymbolDatabase::createSymbolDatabaseSetScopePointers() { auto setScopePointers = [](const Scope &scope, const Token *bodyStart, const Token *bodyEnd) { assert(bodyStart); assert(bodyEnd); const_cast<Token *>(bodyEnd)->scope(&scope); for (auto* tok = const_cast<Token *>(bodyStart); tok != bodyEnd; tok = tok->next()) { if (bodyStart != bodyEnd && tok->str() == "{") { bool isEndOfScope = false; for (Scope* innerScope: scope.nestedList) { const auto &list = innerScope->bodyStartList; if (std::find(list.cbegin(), list.cend(), tok) != list.cend()) { // Is begin of inner scope tok = tok->link(); if (tok->next() == bodyEnd || !tok->next()) { isEndOfScope = true; break; } tok = tok->next(); break; } } if (isEndOfScope) break; } tok->scope(&scope); } }; // Set scope pointers for (const Scope& scope: scopeList) { if (scope.type == Scope::eGlobal) setScopePointers(scope, mTokenizer.list.front(), mTokenizer.list.back()); else { for (const Token *bodyStart: scope.bodyStartList) setScopePointers(scope, bodyStart, bodyStart->link()); } } } void SymbolDatabase::createSymbolDatabaseSetFunctionPointers(bool firstPass) { if (firstPass) { // Set function definition and declaration pointers for (const Scope& scope: scopeList) { for (const Function& func: scope.functionList) { if (func.tokenDef) const_cast<Token *>(func.tokenDef)->function(&func); if (func.token) const_cast<Token *>(func.token)->function(&func); } } } // Set function call pointers const Token* inTemplateArg = nullptr; for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) { if (inTemplateArg == nullptr && tok->link() && tok->str() == "<") inTemplateArg = tok->link(); if (inTemplateArg == tok) inTemplateArg = nullptr; if (tok->isName() && !tok->function() && tok->varId() == 0 && ((tok->astParent() && tok->astParent()->isComparisonOp()) || Token::Match(tok, "%name% [{(,)>;:]]")) && !isReservedName(tok)) { if (tok->strAt(1) == ">" && !tok->linkAt(1)) continue; const Function *function = findFunction(tok); if (!function || (inTemplateArg && function->isConstructor())) continue; tok->function(function); if (tok->strAt(1) != "(") const_cast<Function *>(function)->functionPointerUsage = tok; } } // Set C++ 11 delegate constructor function call pointers for (const Scope& scope: scopeList) { for (const Function& func: scope.functionList) { // look for initializer list if (func.isConstructor() && func.functionScope && func.functionScope->functionOf && func.arg) { const Token * tok = func.arg->link()->next(); if (tok->str() == "noexcept") { const Token * closingParenTok = tok->linkAt(1); if (!closingParenTok || !closingParenTok->next()) { continue; } tok = closingParenTok->next(); } if (tok->str() != ":") { continue; } tok = tok->next(); while (tok && tok != func.functionScope->bodyStart) { if (Token::Match(tok, "%name% {|(")) { if (tok->str() == func.tokenDef->str()) { const Function *function = func.functionScope->functionOf->findFunction(tok); if (function) const_cast<Token *>(tok)->function(function); break; } tok = tok->linkAt(1); } tok = tok->next(); } } } } } void SymbolDatabase::createSymbolDatabaseSetTypePointers() { std::unordered_set<std::string> typenames; for (const Type &t : typeList) { typenames.insert(t.name()); } // Set type pointers for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) { if (!tok->isName() || tok->varId() || tok->function() || tok->type() || tok->enumerator()) continue; if (typenames.find(tok->str()) == typenames.end()) continue; const Type *type = findVariableType(tok->scope(), tok); if (type) tok->type(type); } } void SymbolDatabase::createSymbolDatabaseSetSmartPointerType() { for (Scope &scope: scopeList) { for (Variable &var: scope.varlist) { if (var.valueType() && var.valueType()->smartPointerTypeToken && !var.valueType()->smartPointerType) { ValueType vt(*var.valueType()); vt.smartPointerType = vt.smartPointerTypeToken->type(); var.setValueType(vt); } } } } void SymbolDatabase::fixVarId(VarIdMap & varIds, const Token * vartok, Token * membertok, const Variable * membervar) { VarIdMap::iterator varId = varIds.find(vartok->varId()); if (varId == varIds.end()) { MemberIdMap memberId; if (membertok->varId() == 0) { memberId[membervar->nameToken()->varId()] = mTokenizer.newVarId(); mVariableList.push_back(membervar); } else mVariableList[membertok->varId()] = membervar; varIds.insert(std::make_pair(vartok->varId(), memberId)); varId = varIds.find(vartok->varId()); } MemberIdMap::const_iterator memberId = varId->second.find(membervar->nameToken()->varId()); if (memberId == varId->second.cend()) { if (membertok->varId() == 0) { varId->second.insert(std::make_pair(membervar->nameToken()->varId(), mTokenizer.newVarId())); mVariableList.push_back(membervar); memberId = varId->second.find(membervar->nameToken()->varId()); } else mVariableList[membertok->varId()] = membervar; } if (membertok->varId() == 0) membertok->varId(memberId->second); } static bool isContainerYieldElement(Library::Container::Yield yield); void SymbolDatabase::createSymbolDatabaseSetVariablePointers() { VarIdMap varIds; auto setMemberVar = [&](const Variable* membervar, Token* membertok, const Token* vartok) -> void { if (membervar) { membertok->variable(membervar); if (vartok && (membertok->varId() == 0 || mVariableList[membertok->varId()] == nullptr)) fixVarId(varIds, vartok, membertok, membervar); } }; // Set variable pointers for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) { if (!tok->isName() || tok->isKeyword() || tok->isStandardType()) continue; if (tok->varId()) tok->variable(getVariableFromVarId(tok->varId())); // Set Token::variable pointer for array member variable // Since it doesn't point at a fixed location it doesn't have varid const bool isVar = tok->variable() && (tok->variable()->typeScope() || tok->variable()->isSmartPointer() || (tok->valueType() && (tok->valueType()->type == ValueType::CONTAINER || tok->valueType()->type == ValueType::ITERATOR))); const bool isArrayAccess = isVar && Token::simpleMatch(tok->astParent(), "["); const bool isDirectAccess = isVar && !isArrayAccess && Token::simpleMatch(tok->astParent(), "."); const bool isDerefAccess = isVar && !isDirectAccess && Token::simpleMatch(tok->astParent(), "*") && Token::simpleMatch(tok->astParent()->astParent(), "."); if (isVar && (isArrayAccess || isDirectAccess || isDerefAccess)) { Token* membertok{}; if (isArrayAccess) { membertok = tok->astParent(); while (Token::simpleMatch(membertok, "[")) membertok = membertok->astParent(); if (membertok) membertok = membertok->astOperand2(); } else if (isDirectAccess) { membertok = tok->astParent()->astOperand2(); if (membertok == tok) { Token* gptok = tok->astParent()->astParent(); if (Token::simpleMatch(gptok, ".")) // chained access membertok = gptok->astOperand2(); else if (Token::simpleMatch(gptok, "[") && Token::simpleMatch(gptok->astParent(), ".")) membertok = gptok->astParent()->astOperand2(); } } else { // isDerefAccess membertok = tok->astParent(); while (Token::simpleMatch(membertok, "*")) membertok = membertok->astParent(); if (membertok) membertok = membertok->astOperand2(); } if (membertok && membertok != tok) { const Variable *var = tok->variable(); if (var->typeScope()) { const Variable *membervar = var->typeScope()->getVariable(membertok->str()); setMemberVar(membervar, membertok, tok); } else if (const ::Type *type = var->smartPointerType()) { const Scope *classScope = type->classScope; const Variable *membervar = classScope ? classScope->getVariable(membertok->str()) : nullptr; setMemberVar(membervar, membertok, tok); } else if (tok->valueType() && tok->valueType()->type == ValueType::CONTAINER) { if (const Token* ctt = tok->valueType()->containerTypeToken) { while (ctt && ctt->isKeyword()) ctt = ctt->next(); const Type* ct = findTypeInNested(ctt, tok->scope()); if (ct && ct->classScope && ct->classScope->definedType) { const Variable *membervar = ct->classScope->getVariable(membertok->str()); setMemberVar(membervar, membertok, tok); } } } else if (const Type* iterType = var->iteratorType()) { if (iterType->classScope && iterType->classScope->definedType) { const Variable *membervar = iterType->classScope->getVariable(membertok->str()); setMemberVar(membervar, membertok, tok); } } } } // check for function returning record type // func(...).var // func(...)[...].var else if (tok->function() && tok->strAt(1) == "(" && (Token::Match(tok->linkAt(1), ") . %name% !!(") || (Token::Match(tok->linkAt(1), ") [") && Token::Match(tok->linkAt(1)->linkAt(1), "] . %name% !!(")))) { const Type *type = tok->function()->retType; Token* membertok; if (tok->linkAt(1)->strAt(1) == ".") membertok = tok->linkAt(1)->tokAt(2); else membertok = tok->linkAt(1)->linkAt(1)->tokAt(2); if (type) { const Variable *membervar = membertok->variable(); if (!membervar) { if (type->classScope) { membervar = type->classScope->getVariable(membertok->str()); setMemberVar(membervar, membertok, tok->function()->retDef); } } } else if (mSettings.library.detectSmartPointer(tok->function()->retDef)) { if (const Token* templateArg = Token::findsimplematch(tok->function()->retDef, "<")) { if (const Type* spType = findTypeInNested(templateArg->next(), tok->scope())) { if (spType->classScope) { const Variable* membervar = spType->classScope->getVariable(membertok->str()); setMemberVar(membervar, membertok, tok->function()->retDef); } } } } } else if (Token::simpleMatch(tok->astParent(), ".") && tok->strAt(1) == "(" && astIsContainer(tok->astParent()->astOperand1()) && Token::Match(tok->linkAt(1), ") . %name% !!(")) { const ValueType* vt = tok->astParent()->astOperand1()->valueType(); const Library::Container* cont = vt->container; auto it = cont->functions.find(tok->str()); if (it != cont->functions.end() && isContainerYieldElement(it->second.yield) && vt->containerTypeToken) { Token* memberTok = tok->linkAt(1)->tokAt(2); const Scope* scope = vt->containerTypeToken->scope(); const Type* contType{}; const std::string& typeStr = vt->containerTypeToken->str(); // TODO: handle complex type expressions while (scope && !contType) { contType = scope->findType(typeStr); // find the type stored in the container scope = scope->nestedIn; } if (contType && contType->classScope) { const Variable* membervar = contType->classScope->getVariable(memberTok->str()); setMemberVar(membervar, memberTok, vt->containerTypeToken); } } } } } void SymbolDatabase::createSymbolDatabaseEnums() { // fill in enumerators in enum for (const Scope &scope : scopeList) { if (scope.type != Scope::eEnum) continue; // add enumerators to enumerator tokens for (const Enumerator & i : scope.enumeratorList) const_cast<Token *>(i.name)->enumerator(&i); } std::set<std::string> tokensThatAreNotEnumeratorValues; for (const Scope &scope : scopeList) { if (scope.type != Scope::eEnum) continue; for (const Enumerator & enumerator : scope.enumeratorList) { // look for initialization tokens that can be converted to enumerators and convert them if (enumerator.start) { if (!enumerator.end) mTokenizer.syntaxError(enumerator.start); for (const Token * tok3 = enumerator.start; tok3 && tok3 != enumerator.end->next(); tok3 = tok3->next()) { if (tok3->tokType() == Token::eName) { const Enumerator * e = findEnumerator(tok3, tokensThatAreNotEnumeratorValues); if (e) const_cast<Token *>(tok3)->enumerator(e); } } } } } // find enumerators for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) { const bool isVariable = (tok->tokType() == Token::eVariable && !tok->variable()); if (tok->tokType() != Token::eName && !isVariable) continue; const Enumerator * enumerator = findEnumerator(tok, tokensThatAreNotEnumeratorValues); if (enumerator) { if (isVariable) tok->varId(0); tok->enumerator(enumerator); } } } void SymbolDatabase::createSymbolDatabaseIncompleteVars() { for (Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) { const Scope * scope = tok->scope(); if (!scope) continue; if (!scope->isExecutable()) continue; if (tok->varId() != 0) continue; if (tok->isCast() && !isCPPCast(tok) && tok->link() && tok->str() == "(") { tok = tok->link(); continue; } if (tok->isCpp()) { if (Token::Match(tok, "catch|typeid (") || Token::Match(tok, "static_cast|dynamic_cast|const_cast|reinterpret_cast")) { tok = tok->linkAt(1); continue; } if (tok->str() == "using") { tok = Token::findsimplematch(tok, ";"); continue; } } if (tok->str() == "NULL") continue; if (tok->isKeyword() || !tok->isNameOnly()) continue; if (tok->type()) continue; if (Token::Match(tok->next(), "::|.|(|{|:|%var%")) continue; if (Token::Match(tok->next(), "&|&&|* *| *| )|,|%var%|const")) continue; // Very likely a typelist if (Token::Match(tok->tokAt(-2), "%type% ,") || Token::Match(tok->next(), ", %type%")) continue; // Inside template brackets if (Token::simpleMatch(tok->next(), "<") && tok->linkAt(1)) { tok = tok->linkAt(1); continue; } // Skip goto labels if (Token::simpleMatch(tok->previous(), "goto")) continue; std::string fstr = tok->str(); const Token* ftok = tok->previous(); while (Token::simpleMatch(ftok, "::")) { if (!Token::Match(ftok->previous(), "%name%")) break; fstr.insert(0, ftok->strAt(-1) + "::"); ftok = ftok->tokAt(-2); } if (mSettings.library.functions().find(fstr) != mSettings.library.functions().end()) continue; if (tok->isCpp()) { const Token* parent = tok->astParent(); while (Token::Match(parent, "::|[|{")) parent = parent->astParent(); if (Token::simpleMatch(parent, "new")) continue; // trailing return type if (Token::simpleMatch(ftok, ".") && ftok->originalName() == "->" && Token::Match(ftok->tokAt(-1), "[])]")) continue; } tok->isIncompleteVar(true); } } void SymbolDatabase::createSymbolDatabaseEscapeFunctions() { for (const Scope& scope : scopeList) { if (scope.type != Scope::eFunction) continue; Function * function = scope.function; if (!function) continue; if (Token::findsimplematch(scope.bodyStart, "return", scope.bodyEnd)) continue; function->isEscapeFunction(isReturnScope(scope.bodyEnd, mSettings.library, nullptr, true)); } } static bool isExpression(const Token* tok) { if (!tok) return false; if (Token::simpleMatch(tok, "{") && tok->scope() && tok->scope()->bodyStart != tok && (tok->astOperand1() || tok->astOperand2())) return true; if (!Token::Match(tok, "(|.|[|::|?|:|++|--|%cop%|%assign%")) return false; if (Token::Match(tok, "*|&|&&")) { const Token* vartok = findAstNode(tok, [&](const Token* tok2) { const Variable* var = tok2->variable(); if (!var) return false; return var->nameToken() == tok2; }); if (vartok) return false; } return true; } static std::string getIncompleteNameID(const Token* tok) { std::string result = tok->str() + "@"; while (Token::Match(tok->astParent(), ".|::")) tok = tok->astParent(); return result + tok->expressionString(); } namespace { struct ExprIdKey { std::string parentOp; nonneg int operand1; nonneg int operand2; bool operator<(const ExprIdKey& k) const { return std::tie(parentOp, operand1, operand2) < std::tie(k.parentOp, k.operand1, k.operand2); } }; using ExprIdMap = std::map<ExprIdKey, nonneg int>; void setParentExprId(Token* tok, ExprIdMap& exprIdMap, nonneg int &id) { for (;;) { if (!tok->astParent() || tok->astParent()->isControlFlowKeyword()) break; const Token* op1 = tok->astParent()->astOperand1(); if (op1 && op1->exprId() == 0 && !Token::Match(op1, "[{[]")) break; const Token* op2 = tok->astParent()->astOperand2(); if (op2 && op2->exprId() == 0 && !((tok->astParent()->astParent() && tok->astParent()->isAssignmentOp() && tok->astParent()->astParent()->isAssignmentOp()) || isLambdaCaptureList(op2) || (op2->str() == "(" && isLambdaCaptureList(op2->astOperand1())) || Token::simpleMatch(op2, "{ }") || (Token::simpleMatch(tok->astParent(), "[") && op2->str() == "{"))) break; if (tok->astParent()->isExpandedMacro() || Token::Match(tok->astParent(), "++|--")) { tok->astParent()->exprId(id); ++id; tok = tok->astParent(); continue; } ExprIdKey key; key.parentOp = tok->astParent()->str(); key.operand1 = op1 ? op1->exprId() : 0; key.operand2 = op2 ? op2->exprId() : 0; if (tok->astParent()->isCast() && tok->astParent()->str() == "(") { const Token* typeStartToken; const Token* typeEndToken; if (tok->astParent()->astOperand2()) { typeStartToken = tok->astParent()->astOperand1(); typeEndToken = tok; } else { typeStartToken = tok->astParent()->next(); typeEndToken = tok->astParent()->link(); } std::string type; for (const Token* t = typeStartToken; t != typeEndToken; t = t->next()) { type += " " + t->str(); } key.parentOp += type; } for (const auto& ref: followAllReferences(op1)) { if (ref.token->exprId() != 0) { // cppcheck-suppress useStlAlgorithm key.operand1 = ref.token->exprId(); break; } } for (const auto& ref: followAllReferences(op2)) { if (ref.token->exprId() != 0) { // cppcheck-suppress useStlAlgorithm key.operand2 = ref.token->exprId(); break; } } if (key.operand1 > key.operand2 && key.operand2 && Token::Match(tok->astParent(), "%or%|%oror%|+|*|&|&&|^|==|!=")) { // In C++ the order of operands of + might matter if (!tok->isCpp() || key.parentOp != "+" || !tok->astParent()->valueType() || tok->astParent()->valueType()->isIntegral() || tok->astParent()->valueType()->isFloat() || tok->astParent()->valueType()->pointer > 0) std::swap(key.operand1, key.operand2); } const auto it = exprIdMap.find(key); if (it == exprIdMap.end()) { exprIdMap[key] = id; tok->astParent()->exprId(id); ++id; } else { tok->astParent()->exprId(it->second); } tok = tok->astParent(); } } } void SymbolDatabase::createSymbolDatabaseExprIds() { // Find highest varId nonneg int maximumVarId = 0; for (const Token* tok = mTokenizer.list.front(); tok; tok = tok->next()) { maximumVarId = std::max(tok->varId(), maximumVarId); } nonneg int id = maximumVarId + 1; // Find incomplete vars that are used in constant context std::unordered_map<std::string, nonneg int> unknownConstantIds; const Token* inConstExpr = nullptr; for (const Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) { if (Token::Match(tok, "decltype|sizeof|typeof (") && tok->linkAt(1)) { tok = tok->linkAt(1)->previous(); } else if (tok == inConstExpr) { inConstExpr = nullptr; } else if (inConstExpr) { if (!tok->isIncompleteVar()) continue; if (!isExpression(tok->astParent())) continue; const std::string& name = getIncompleteNameID(tok); if (unknownConstantIds.count(name) > 0) continue; unknownConstantIds[name] = id++; } else if (tok->link() && tok->str() == "<") { inConstExpr = tok->link(); } else if (Token::Match(tok, "%var% [") && tok->variable() && tok->variable()->nameToken() == tok) { inConstExpr = tok->linkAt(1); } } auto exprScopes = functionScopes; // functions + global lambdas + namespaces std::copy_if(scopeList.front().nestedList.begin(), scopeList.front().nestedList.end(), std::back_inserter(exprScopes), [](const Scope* scope) { return scope && (scope->type == Scope::eLambda || scope->type == Scope::eNamespace); }); for (const Scope * scope : exprScopes) { std::unordered_map<std::string, nonneg int> unknownIds; // Assign IDs to incomplete vars which are part of an expression // Such variables should be assumed global for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isIncompleteVar()) continue; if (!isExpression(tok->astParent())) continue; const std::string& name = getIncompleteNameID(tok); nonneg int sid = 0; if (unknownConstantIds.count(name) > 0) { sid = unknownConstantIds.at(name); tok->isIncompleteConstant(true); } else if (unknownIds.count(name) == 0) { sid = id++; unknownIds[name] = sid; } else { sid = unknownIds.at(name); } assert(sid > 0); tok->exprId(sid); } // Assign IDs ExprIdMap exprIdMap; std::map<std::string, std::pair<nonneg int, const Token*>> baseIds; for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { if (tok->varId() > 0) { tok->exprId(tok->varId()); if (tok->astParent() && tok->astParent()->exprId() == 0) setParentExprId(tok, exprIdMap, id); } else if (tok->astParent() && !tok->astOperand1() && !tok->astOperand2()) { if (tok->tokType() == Token::Type::eBracket) continue; if (tok->astParent()->str() == "=") continue; if (tok->isControlFlowKeyword()) continue; if (Token::Match(tok, "%name% <") && tok->linkAt(1)) { tok->exprId(id); ++id; } else { const auto it = baseIds.find(tok->str()); if (it != baseIds.end() && compareTokenFlags(tok, it->second.second, /*macro*/ true)) { tok->exprId(it->second.first); } else { baseIds[tok->str()] = { id, tok }; tok->exprId(id); ++id; } } setParentExprId(tok, exprIdMap, id); } } for (auto* tok = const_cast<Token*>(scope->bodyStart); tok != scope->bodyEnd; tok = tok->next()) { if (tok->varId() == 0 && tok->exprId() > 0 && tok->astParent() && !tok->astOperand1() && !tok->astOperand2()) { if (tok->isNumber() || tok->isKeyword() || Token::Match(tok->astParent(), ".|::") || (Token::simpleMatch(tok->astParent(), "(") && precedes(tok, tok->astParent()))) tok->exprId(0); } } } // Mark expressions that are unique std::vector<std::pair<Token*, int>> uniqueExprId(id); for (Token* tok = mTokenizer.list.front(); tok; tok = tok->next()) { const auto id2 = tok->exprId(); if (id2 == 0 || id2 <= maximumVarId) continue; uniqueExprId[id2].first = tok; uniqueExprId[id2].second++; } for (const auto& p : uniqueExprId) { if (!p.first || p.second != 1) continue; if (p.first->variable()) { const Variable* var = p.first->variable(); if (var->nameToken() != p.first) continue; } p.first->setUniqueExprId(); } } void SymbolDatabase::setArrayDimensionsUsingValueFlow() { // set all unknown array dimensions for (const Variable *var : mVariableList) { // check each array variable if (!var || !var->isArray()) continue; // check each array dimension for (const Dimension &const_dimension : var->dimensions()) { auto &dimension = const_cast<Dimension &>(const_dimension); if (dimension.num != 0 || !dimension.tok) continue; if (Token::Match(dimension.tok->previous(), "[<,]")) { if (dimension.known) continue; if (!Token::Match(dimension.tok->previous(), "[<,]")) continue; // In template arguments, there might not be AST // Determine size by using the "raw tokens" TokenList tokenList(&mSettings); tokenList.setLang(dimension.tok->isCpp() ? Standards::Language::CPP : Standards::Language::C); tokenList.addtoken(";", 0, 0, 0, false); bool fail = false; for (const Token *tok = dimension.tok; tok && !Token::Match(tok, "[,>]"); tok = tok->next()) { if (!tok->isName()) tokenList.addtoken(tok->str(), 0, 0, 0, false); else if (tok->hasKnownIntValue()) tokenList.addtoken(std::to_string(tok->getKnownIntValue()), 0, 0, 0, false); else { fail = true; break; } } if (fail) continue; tokenList.addtoken(";", 0, 0, 0, false); for (Token *tok = tokenList.front(); tok;) { if (TemplateSimplifier::simplifyNumericCalculations(tok, false)) tok = tokenList.front(); else tok = tok->next(); } if (Token::Match(tokenList.front(), "; %num% ;")) { dimension.known = true; dimension.num = MathLib::toBigNumber(tokenList.front()->strAt(1)); } continue; } // Normal array [..dimension..] dimension.known = false; // check for a single token dimension if (dimension.tok->hasKnownIntValue()) { dimension.known = true; dimension.num = dimension.tok->getKnownIntValue(); continue; } if (dimension.tok->valueType() && dimension.tok->valueType()->pointer == 0) { int bits = 0; switch (dimension.tok->valueType()->type) { case ValueType::Type::CHAR: bits = mSettings.platform.char_bit; break; case ValueType::Type::SHORT: bits = mSettings.platform.short_bit; break; case ValueType::Type::INT: bits = mSettings.platform.int_bit; break; case ValueType::Type::LONG: bits = mSettings.platform.long_bit; break; case ValueType::Type::LONGLONG: bits = mSettings.platform.long_long_bit; break; default: break; } if (bits > 0 && bits <= 62) { if (dimension.tok->valueType()->sign == ValueType::Sign::UNSIGNED) dimension.num = 1LL << bits; else dimension.num = 1LL << (bits - 1); } } } } } SymbolDatabase::~SymbolDatabase() { // Clear scope, type, function and variable pointers for (Token* tok = mTokenizer.list.front(); tok; tok = tok->next()) { tok->scope(nullptr); tok->type(nullptr); tok->function(nullptr); tok->variable(nullptr); tok->enumerator(nullptr); tok->setValueType(nullptr); } } bool SymbolDatabase::isFunction(const Token *tok, const Scope* outerScope, const Token *&funcStart, const Token *&argStart, const Token*& declEnd) const { if (tok->varId()) return false; // function returning function pointer? '... ( ... %name% ( ... ))( ... ) {' // function returning reference to array '... ( & %name% ( ... ))[ ... ] {' // TODO: Activate this again if ((false) && tok->str() == "(" && tok->strAt(1) != "*" && // NOLINT(readability-simplify-boolean-expr) (tok->link()->strAt(-1) == ")" || Token::simpleMatch(tok->link()->tokAt(-2), ") const"))) { const Token* tok2 = tok->link()->next(); if (tok2 && tok2->str() == "(" && Token::Match(tok2->link()->next(), "{|;|const|=")) { const Token* argStartTok; if (tok->link()->strAt(-1) == "const") argStartTok = tok->link()->linkAt(-2); else argStartTok = tok->link()->linkAt(-1); funcStart = argStartTok->previous(); argStart = argStartTok; declEnd = Token::findmatch(tok2->link()->next(), "{|;"); return true; } if (tok2 && tok2->str() == "[") { while (tok2 && tok2->str() == "[") tok2 = tok2->link()->next(); if (Token::Match(tok2, "{|;|const|=")) { const Token* argStartTok; if (tok->link()->strAt(-1) == "const") argStartTok = tok->link()->linkAt(-2); else argStartTok = tok->link()->linkAt(-1); funcStart = argStartTok->previous(); argStart = argStartTok; declEnd = Token::findmatch(tok2, "{|;"); return true; } } } else if (!tok->isName() || !tok->next() || !tok->linkAt(1)) return false; // regular function? else if (Token::Match(tok, "%name% (") && !isReservedName(tok) && tok->previous() && (Token::Match(tok->previous(), "%name%|>|&|&&|*|::|~") || // Either a return type or scope qualifier in front of tok outerScope->isClassOrStructOrUnion())) { // or a ctor/dtor const Token* tok1 = tok->previous(); const Token* tok2 = tok->linkAt(1)->next(); if (!Tokenizer::isFunctionHead(tok->next(), ";:{")) return false; // skip over destructor "~" if (tok1->str() == "~") tok1 = tok1->previous(); // skip over qualification while (Token::simpleMatch(tok1, "::")) { tok1 = tok1->previous(); if (tok1 && tok1->isName()) tok1 = tok1->previous(); else if (tok1 && tok1->str() == ">" && tok1->link() && Token::Match(tok1->link()->previous(), "%name%")) tok1 = tok1->link()->tokAt(-2); } // skip over const, noexcept, throw, override, final and volatile specifiers while (Token::Match(tok2, "const|noexcept|throw|override|final|volatile|&|&&")) { tok2 = tok2->next(); if (tok2 && tok2->str() == "(") tok2 = tok2->link()->next(); } // skip over trailing return type bool hasTrailingRet = false; if (tok2 && tok2->str() == ".") { hasTrailingRet = true; for (tok2 = tok2->next(); tok2; tok2 = tok2->next()) { if (Token::Match(tok2, ";|{|=|override|final")) break; if (tok2->link() && Token::Match(tok2, "<|[|(")) tok2 = tok2->link(); } } // done if constructor or destructor if (!Token::Match(tok1, "{|}|;|public:|protected:|private:") && tok1) { // skip over pointers and references while (Token::Match(tok1, "%type%|*|&|&&") && !endsWith(tok1->str(), ':') && (!isReservedName(tok1) || tok1->str() == "const")) tok1 = tok1->previous(); // skip over decltype if (Token::simpleMatch(tok1, ")") && tok1->link() && Token::simpleMatch(tok1->link()->previous(), "decltype (")) tok1 = tok1->link()->tokAt(-2); // skip over template if (tok1 && tok1->str() == ">") { if (tok1->link()) tok1 = tok1->link()->previous(); else return false; } // function can't have number or variable as return type if (tok1 && (tok1->isNumber() || tok1->varId())) return false; // skip over return type if (tok1 && tok1->isName()) { if (tok1->str() == "return") return false; if (tok1->str() != "friend") tok1 = tok1->previous(); } // skip over qualification while (Token::simpleMatch(tok1, "::")) { tok1 = tok1->previous(); if (tok1 && tok1->isName()) tok1 = tok1->previous(); else if (tok1 && tok1->str() == ">" && tok1->link() && Token::Match(tok1->link()->previous(), "%name%")) tok1 = tok1->link()->tokAt(-2); else if (Token::simpleMatch(tok1, ")") && tok1->link() && Token::simpleMatch(tok1->link()->previous(), "decltype (")) tok1 = tok1->link()->tokAt(-2); } // skip over modifiers and other stuff while (Token::Match(tok1, "const|static|extern|template|virtual|struct|class|enum|%name%")) { // friend type func(); is not a function if (tok1->isCpp() && tok1->str() == "friend" && tok2->str() == ";") return false; tok1 = tok1->previous(); } // should be at a sequence point if this is a function if (!Token::Match(tok1, ">|{|}|;|public:|protected:|private:") && tok1) return false; } if (tok2 && (Token::Match(tok2, ";|{|=") || (tok2->isUpperCaseName() && Token::Match(tok2, "%name% ;|{")) || (tok2->isUpperCaseName() && Token::Match(tok2, "%name% (") && tok2->linkAt(1)->strAt(1) == "{") || Token::Match(tok2, ": ::| %name% (|::|<|{") || Token::Match(tok2, "&|&&| ;|{") || Token::Match(tok2, "= delete|default ;") || (hasTrailingRet && Token::Match(tok2, "final|override")))) { funcStart = tok; argStart = tok->next(); declEnd = Token::findmatch(tok2, "{|;"); return true; } } // UNKNOWN_MACRO(a,b) { ... } else if (outerScope->type == Scope::eGlobal && Token::Match(tok, "%name% (") && tok->isUpperCaseName() && Token::simpleMatch(tok->linkAt(1), ") {") && (!tok->previous() || Token::Match(tok->previous(), "[;{}]"))) { funcStart = tok; argStart = tok->next(); declEnd = tok->linkAt(1)->next(); return true; } // template constructor? else if (Token::Match(tok, "%name% <") && Token::simpleMatch(tok->linkAt(1), "> (")) { if (tok->isKeyword() || tok->isStandardType() || !outerScope->isClassOrStructOrUnion()) return false; const Token* tok2 = tok->linkAt(1)->linkAt(1); if (Token::Match(tok2, ") const| ;|{|=") || Token::Match(tok2, ") : ::| %name% (|::|<|{") || Token::Match(tok2, ") const| noexcept {|;|(")) { funcStart = tok; argStart = tok2->link(); declEnd = Token::findmatch(tok2->next(), "{|;"); return true; } } // regular C function with missing return or invalid C++ ? else if (Token::Match(tok, "%name% (") && !isReservedName(tok) && Token::simpleMatch(tok->linkAt(1), ") {") && (!tok->previous() || Token::Match(tok->previous(), ";|}"))) { if (tok->isC()) { returnImplicitIntError(tok); funcStart = tok; argStart = tok->next(); declEnd = tok->linkAt(1)->next(); return true; } mTokenizer.syntaxError(tok); } return false; } void SymbolDatabase::validateExecutableScopes() const { const std::size_t functions = functionScopes.size(); for (std::size_t i = 0; i < functions; ++i) { const Scope* const scope = functionScopes[i]; const Function* const function = scope->function; if (scope->isExecutable() && !function) { const std::list<const Token*> callstack(1, scope->classDef); const std::string msg = std::string("Executable scope '") + scope->classDef->str() + "' with unknown function."; const ErrorMessage errmsg(callstack, &mTokenizer.list, Severity::debug, "symbolDatabaseWarning", msg, Certainty::normal); mErrorLogger.reportErr(errmsg); } } } namespace { const Function* getFunctionForArgumentvariable(const Variable * const var) { if (const Scope* scope = var->nameToken()->scope()) { auto it = std::find_if(scope->functionList.begin(), scope->functionList.end(), [&](const Function& function) { for (nonneg int arg = 0; arg < function.argCount(); ++arg) { if (var == function.getArgumentVar(arg)) return true; } return false; }); if (it != scope->functionList.end()) return &*it; } return nullptr; } } void SymbolDatabase::validateVariables() const { for (auto iter = mVariableList.cbegin(); iter!=mVariableList.cend(); ++iter) { const Variable * const var = *iter; if (var) { if (!var->scope()) { const Function* function = getFunctionForArgumentvariable(var); if (!var->isArgument() || (!function || function->hasBody())) { // variables which only appear in a function declaration do not have a scope throw InternalError(var->nameToken(), "Analysis failed (variable without scope). If the code is valid then please report this failure.", InternalError::INTERNAL); } } } } } void SymbolDatabase::validate() const { if (mSettings.debugwarnings) { validateExecutableScopes(); } validateVariables(); } void SymbolDatabase::clangSetVariables(const std::vector<const Variable *> &variableList) { mVariableList = variableList; } void SymbolDatabase::debugSymbolDatabase() const { if (!mSettings.debugnormal && !mSettings.debugwarnings) return; for (const Token* tok = mTokenizer.list.front(); tok != mTokenizer.list.back(); tok = tok->next()) { if (tok->astParent() && tok->astParent()->getTokenDebug() == tok->getTokenDebug()) continue; if (tok->getTokenDebug() == TokenDebug::ValueType) { std::string msg = "Value type is "; ErrorPath errorPath; if (tok->valueType()) { msg += tok->valueType()->str(); errorPath.insert(errorPath.end(), tok->valueType()->debugPath.cbegin(), tok->valueType()->debugPath.cend()); } else { msg += "missing"; } errorPath.emplace_back(tok, ""); mErrorLogger.reportErr( {errorPath, &mTokenizer.list, Severity::debug, "valueType", msg, CWE{0}, Certainty::normal}); } } } Variable::Variable(const Token *name_, const std::string &clangType, const Token *typeStart, const Token *typeEnd, nonneg int index_, AccessControl access_, const Type *type_, const Scope *scope_) : mNameToken(name_), mTypeStartToken(typeStart), mTypeEndToken(typeEnd), mIndex(index_), mAccess(access_), mFlags(0), mType(type_), mScope(scope_) { if (!mTypeStartToken && mTypeEndToken) { mTypeStartToken = mTypeEndToken; while (Token::Match(mTypeStartToken->previous(), "%type%|*|&")) mTypeStartToken = mTypeStartToken->previous(); } while (Token::Match(mTypeStartToken, "const|struct|static")) { if (mTypeStartToken->str() == "static") setFlag(fIsStatic, true); mTypeStartToken = mTypeStartToken->next(); } if (Token::simpleMatch(mTypeEndToken, "&")) setFlag(fIsReference, true); else if (Token::simpleMatch(mTypeEndToken, "&&")) { setFlag(fIsReference, true); setFlag(fIsRValueRef, true); } std::string::size_type pos = clangType.find('['); if (pos != std::string::npos) { setFlag(fIsArray, true); do { const std::string::size_type pos1 = pos+1; pos = clangType.find(']', pos1); Dimension dim; dim.tok = nullptr; dim.known = pos > pos1; if (pos > pos1) dim.num = MathLib::toBigNumber(clangType.substr(pos1, pos - pos1)); else dim.num = 0; mDimensions.push_back(dim); ++pos; } while (pos < clangType.size() && clangType[pos] == '['); } // Is there initialization in variable declaration const Token *initTok = mNameToken ? mNameToken->next() : nullptr; while (initTok && initTok->str() == "[") initTok = initTok->link()->next(); if (Token::Match(initTok, "=|{") || (initTok && initTok->isSplittedVarDeclEq())) setFlag(fIsInit, true); } Variable::Variable(const Variable &var, const Scope *scope) { *this = var; mScope = scope; } Variable::Variable(const Variable &var) { *this = var; } Variable::~Variable() { delete mValueType; } Variable& Variable::operator=(const Variable &var) & { if (this == &var) return *this; ValueType* vt = nullptr; if (var.mValueType) vt = new ValueType(*var.mValueType); mNameToken = var.mNameToken; mTypeStartToken = var.mTypeStartToken; mTypeEndToken = var.mTypeEndToken; mIndex = var.mIndex; mAccess = var.mAccess; mFlags = var.mFlags; mType = var.mType; mScope = var.mScope; mDimensions = var.mDimensions; delete mValueType; mValueType = vt; return *this; } bool Variable::isMember() const { return mScope && mScope->isClassOrStructOrUnion(); } bool Variable::isPointerArray() const { return isArray() && nameToken() && nameToken()->previous() && (nameToken()->strAt(-1) == "*"); } bool Variable::isUnsigned() const { return mValueType ? (mValueType->sign == ValueType::Sign::UNSIGNED) : mTypeStartToken->isUnsigned(); } const Token * Variable::declEndToken() const { Token const * declEnd = typeStartToken(); while (declEnd && !Token::Match(declEnd, "[;,)={]")) { if (declEnd->link() && Token::Match(declEnd,"(|[|<")) declEnd = declEnd->link(); declEnd = declEnd->next(); } return declEnd; } void Variable::evaluate(const Settings& settings) { // Is there initialization in variable declaration const Token *initTok = mNameToken ? mNameToken->next() : nullptr; while (Token::Match(initTok, "[")) { initTok = initTok->link()->next(); if (Token::simpleMatch(initTok, ")")) initTok = initTok->next(); } if (Token::Match(initTok, "[={(]") || (initTok && initTok->isSplittedVarDeclEq())) setFlag(fIsInit, true); const Library & lib = settings.library; // TODO: ValueType::parseDecl() is also performing a container lookup bool isContainer = false; if (mNameToken) setFlag(fIsArray, arrayDimensions(settings, isContainer)); if (mTypeStartToken) setValueType(ValueType::parseDecl(mTypeStartToken,settings)); const Token* tok = mTypeStartToken; while (tok && tok->previous() && tok->previous()->isName()) tok = tok->previous(); const Token* end = mTypeEndToken; if (end) end = end->next(); while (tok != end) { if (tok->str() == "static") setFlag(fIsStatic, true); else if (tok->str() == "extern") setFlag(fIsExtern, true); else if (tok->str() == "volatile" || Token::simpleMatch(tok, "std :: atomic <")) setFlag(fIsVolatile, true); else if (tok->str() == "mutable") setFlag(fIsMutable, true); else if (tok->str() == "const") setFlag(fIsConst, true); else if (tok->str() == "constexpr") { setFlag(fIsConst, true); setFlag(fIsStatic, true); } else if (tok->str() == "*") { setFlag(fIsPointer, !isArray() || (isContainer && !Token::Match(tok->next(), "%name% [")) || Token::Match(tok, "* const| %name% )")); setFlag(fIsConst, false); // Points to const, isn't necessarily const itself } else if (tok->str() == "&") { if (isReference()) setFlag(fIsRValueRef, true); setFlag(fIsReference, true); } else if (tok->str() == "&&") { // Before simplification, && isn't split up setFlag(fIsRValueRef, true); setFlag(fIsReference, true); // Set also fIsReference } if (tok->isAttributeMaybeUnused()) { setFlag(fIsMaybeUnused, true); } if (tok->str() == "<" && tok->link()) tok = tok->link(); else tok = tok->next(); } while (Token::Match(mTypeStartToken, "static|const|constexpr|volatile %any%")) mTypeStartToken = mTypeStartToken->next(); while (mTypeEndToken && mTypeEndToken->previous() && Token::Match(mTypeEndToken, "const|volatile")) mTypeEndToken = mTypeEndToken->previous(); if (mTypeStartToken) { std::string strtype = mTypeStartToken->str(); for (const Token *typeToken = mTypeStartToken; Token::Match(typeToken, "%type% :: %type%"); typeToken = typeToken->tokAt(2)) strtype += "::" + typeToken->strAt(2); setFlag(fIsClass, !lib.podtype(strtype) && !mTypeStartToken->isStandardType() && !isEnumType() && !isPointer() && strtype != "..."); setFlag(fIsStlType, Token::simpleMatch(mTypeStartToken, "std ::")); setFlag(fIsStlString, ::isStlStringType(mTypeStartToken)); setFlag(fIsSmartPointer, mTypeStartToken->isCpp() && lib.isSmartPointer(mTypeStartToken)); } if (mAccess == AccessControl::Argument) { tok = mNameToken; if (!tok) { // Argument without name tok = mTypeEndToken; // back up to start of array dimensions while (tok && tok->str() == "]") tok = tok->link()->previous(); // add array dimensions if present if (tok && tok->strAt(1) == "[") setFlag(fIsArray, arrayDimensions(settings, isContainer)); } if (!tok) return; tok = tok->next(); while (tok->str() == "[") tok = tok->link(); setFlag(fHasDefault, tok->str() == "="); } // check for C++11 member initialization if (mScope && mScope->isClassOrStruct()) { // type var = x or // type var = {x} // type var = x; gets simplified to: type var ; var = x ; Token const * declEnd = declEndToken(); if ((Token::Match(declEnd, "; %name% =") && declEnd->strAt(1) == mNameToken->str()) || Token::Match(declEnd, "=|{")) setFlag(fHasDefault, true); } if (mTypeStartToken) { if (Token::Match(mTypeStartToken, "float|double")) setFlag(fIsFloatType, true); } } void Variable::setValueType(const ValueType &valueType) { if (valueType.type == ValueType::Type::UNKNOWN_TYPE) { const Token *declType = Token::findsimplematch(mTypeStartToken, "decltype (", mTypeEndToken); if (declType && !declType->next()->valueType()) return; } auto* vt = new ValueType(valueType); delete mValueType; mValueType = vt; if ((mValueType->pointer > 0) && (!isArray() || Token::Match(mNameToken->previous(), "( * %name% )"))) setFlag(fIsPointer, true); setFlag(fIsConst, mValueType->constness & (1U << mValueType->pointer)); setFlag(fIsVolatile, mValueType->volatileness & (1U << mValueType->pointer)); if (mValueType->smartPointerType) setFlag(fIsSmartPointer, true); } const Type* Variable::smartPointerType() const { if (!isSmartPointer()) return nullptr; if (mValueType->smartPointerType) return mValueType->smartPointerType; // TODO: Cache result, handle more complex type expression const Token* typeTok = typeStartToken(); while (Token::Match(typeTok, "%name%|::")) typeTok = typeTok->next(); if (Token::Match(typeTok, "< %name% >")) { // cppcheck-suppress shadowFunction - TODO: fix this const Scope* scope = typeTok->scope(); const Type* ptrType{}; while (scope && !ptrType) { ptrType = scope->findType(typeTok->strAt(1)); scope = scope->nestedIn; } return ptrType; } return nullptr; } const Type* Variable::iteratorType() const { if (!mValueType || mValueType->type != ValueType::ITERATOR) return nullptr; if (mValueType->containerTypeToken) return mValueType->containerTypeToken->type(); return nullptr; } bool Variable::isStlStringViewType() const { return getFlag(fIsStlType) && valueType() && valueType()->container && valueType()->container->stdStringLike && valueType()->container->view; } std::string Variable::getTypeName() const { std::string ret; // TODO: For known types, generate the full type name for (const Token *typeTok = mTypeStartToken; Token::Match(typeTok, "%name%|::") && typeTok->varId() == 0; typeTok = typeTok->next()) { ret += typeTok->str(); if (Token::simpleMatch(typeTok->next(), "<") && typeTok->linkAt(1)) // skip template arguments typeTok = typeTok->linkAt(1); } return ret; } static bool isOperator(const Token *tokenDef) { if (!tokenDef) return false; if (tokenDef->isOperatorKeyword()) return true; const std::string &name = tokenDef->str(); return name.size() > 8 && startsWith(name,"operator") && std::strchr("+-*/%&|~^<>!=[(", name[8]); } static bool isTrailingReturnType(const Token* tok) { while (tok && tok->isKeyword()) tok = tok->next(); return Token::Match(tok, "&|&&| ."); } Function::Function(const Token *tok, const Scope *scope, const Token *tokDef, const Token *tokArgDef) : tokenDef(tokDef), argDef(tokArgDef), nestedIn(scope) { // operator function if (::isOperator(tokenDef)) { isOperator(true); // 'operator =' is special if (tokenDef->str() == "operator=") type = Function::eOperatorEqual; } else if (tokenDef->str() == "[") { type = Function::eLambda; } // class constructor/destructor else if (scope->isClassOrStructOrUnion() && ((tokenDef->str() == scope->className) || (tokenDef->str().substr(0, scope->className.size()) == scope->className && tokenDef->str().size() > scope->className.size() + 1 && tokenDef->str()[scope->className.size() + 1] == '<'))) { // destructor if (tokenDef->strAt(-1) == "~") { type = Function::eDestructor; isNoExcept(true); } // constructor of any kind else type = Function::eConstructor; isExplicit(tokenDef->strAt(-1) == "explicit" || tokenDef->strAt(-2) == "explicit"); } const Token *tok1 = setFlags(tok, scope); // find the return type if (!isConstructor() && !isDestructor()) { // @todo auto type deduction should be checked // @todo attributes and exception specification can also precede trailing return type if (isTrailingReturnType(argDef->link()->next())) { // Trailing return type hasTrailingReturnType(true); if (argDef->link()->strAt(1) == ".") retDef = argDef->link()->tokAt(2); else if (argDef->link()->strAt(2) == ".") retDef = argDef->link()->tokAt(3); else if (argDef->link()->strAt(3) == ".") retDef = argDef->link()->tokAt(4); } else if (!isLambda()) { if (tok1->str() == ">") tok1 = tok1->next(); while (Token::Match(tok1, "extern|virtual|static|friend|struct|union|enum")) tok1 = tok1->next(); retDef = tok1; } } const Token *end = argDef->link(); // parse function attributes.. tok = end->next(); while (tok) { if (tok->str() == "const") isConst(true); else if (tok->str() == "&") hasLvalRefQualifier(true); else if (tok->str() == "&&") hasRvalRefQualifier(true); else if (tok->str() == "override") setFlag(fHasOverrideSpecifier, true); else if (tok->str() == "final") setFlag(fHasFinalSpecifier, true); else if (tok->str() == "volatile") isVolatile(true); else if (tok->str() == "noexcept") { isNoExcept(!Token::simpleMatch(tok->next(), "( false )")); if (tok->strAt(1) == "(") tok = tok->linkAt(1); } else if (Token::simpleMatch(tok, "throw (")) { isThrow(true); if (tok->strAt(2) != ")") throwArg = tok->next(); tok = tok->linkAt(1); } else if (Token::Match(tok, "= 0|default|delete ;")) { const std::string& modifier = tok->strAt(1); isPure(modifier == "0"); isDefault(modifier == "default"); isDelete(modifier == "delete"); } else if (tok->str() == ".") { // trailing return type // skip over return type while (tok && !Token::Match(tok->next(), ";|{|override|final")) tok = tok->next(); } else break; if (tok) tok = tok->next(); } if (Tokenizer::isFunctionHead(end, ":{")) { // assume implementation is inline (definition and implementation same) token = tokenDef; arg = argDef; isInline(true); hasBody(true); } } Function::Function(const Token *tokenDef, const std::string &clangType) : tokenDef(tokenDef) { // operator function if (::isOperator(tokenDef)) { isOperator(true); // 'operator =' is special if (tokenDef->str() == "operator=") type = Function::eOperatorEqual; } setFlags(tokenDef, tokenDef->scope()); if (endsWith(clangType, " const")) isConst(true); } const Token *Function::setFlags(const Token *tok1, const Scope *scope) { if (tok1->isInline()) isInlineKeyword(true); // look for end of previous statement while (tok1->previous() && !Token::Match(tok1->previous(), ";|}|{|public:|protected:|private:")) { tok1 = tok1->previous(); if (tok1->isInline()) isInlineKeyword(true); // extern function if (tok1->isExternC() || tok1->str() == "extern") { isExtern(true); } // virtual function else if (tok1->str() == "virtual") { hasVirtualSpecifier(true); } // static function else if (tok1->str() == "static") { isStatic(true); if (scope->type == Scope::eNamespace || scope->type == Scope::eGlobal) isStaticLocal(true); } // friend function else if (tok1->str() == "friend") { isFriend(true); } // constexpr function else if (tok1->str() == "constexpr") { isConstexpr(true); } // decltype else if (tok1->str() == ")" && Token::simpleMatch(tok1->link()->previous(), "decltype (")) { tok1 = tok1->link()->previous(); } else if (tok1->link() && tok1->str() == ">") { // Function template if (Token::simpleMatch(tok1->link()->previous(), "template <")) { templateDef = tok1->link()->previous(); break; } tok1 = tok1->link(); } } return tok1; } std::string Function::fullName() const { std::string ret = name(); for (const Scope *s = nestedIn; s; s = s->nestedIn) { if (!s->className.empty()) ret = s->className + "::" + ret; } ret += "("; for (const Variable &a : argumentList) ret += (a.index() == 0 ? "" : ",") + a.name(); return ret + ")"; } static std::string qualifiedName(const Scope *scope) { std::string name = scope->className; while (scope->nestedIn) { if (!scope->nestedIn->className.empty()) name = (scope->nestedIn->className + " :: ") + name; scope = scope->nestedIn; } return name; } static bool usingNamespace(const Scope *scope, const Token *first, const Token *second, int &offset) { // check if qualifications match first before checking if using is needed const Token *tok1 = first; const Token *tok2 = second; bool match = false; while (Token::Match(tok1, "%type% :: %type%") && Token::Match(tok2, "%type% :: %type%")) { if (tok1->str() == tok2->str()) { tok1 = tok1->tokAt(2); tok2 = tok2->tokAt(2); match = true; } else { match = false; break; } } if (match) return false; offset = 0; std::string name = first->str(); while (Token::Match(first, "%type% :: %type%")) { if (offset) name += (" :: " + first->str()); offset += 2; first = first->tokAt(2); if (first->str() == second->str()) { break; } } if (offset) { while (scope) { for (const auto & info : scope->usingList) { if (info.scope) { if (name == qualifiedName(info.scope)) return true; } // no scope so get name from using else { const Token *start = info.start->tokAt(2); std::string nsName; while (start && start->str() != ";") { if (!nsName.empty()) nsName += " "; nsName += start->str(); start = start->next(); } if (nsName == name) return true; } } scope = scope->nestedIn; } } return false; } static bool typesMatch( const Scope *first_scope, const Token *first_token, const Scope *second_scope, const Token *second_token, const Token *&new_first, const Token *&new_second) { // get first type const Type* first_type = first_scope->check->findType(first_token, first_scope, /*lookOutside*/ true); if (first_type) { // get second type const Type* second_type = second_scope->check->findType(second_token, second_scope, /*lookOutside*/ true); // check if types match if (first_type == second_type) { const Token* tok1 = first_token; while (tok1 && tok1->str() != first_type->name()) tok1 = tok1->next(); const Token *tok2 = second_token; while (tok2 && tok2->str() != second_type->name()) tok2 = tok2->next(); // update parser token positions if (tok1 && tok2) { new_first = tok1->previous(); new_second = tok2->previous(); return true; } } } return false; } bool Function::argsMatch(const Scope *scope, const Token *first, const Token *second, const std::string &path, nonneg int path_length) const { if (!first->isCpp()) // C does not support overloads return true; int arg_path_length = path_length; int offset = 0; int openParen = 0; // check for () == (void) and (void) == () if ((Token::simpleMatch(first, "( )") && Token::simpleMatch(second, "( void )")) || (Token::simpleMatch(first, "( void )") && Token::simpleMatch(second, "( )"))) return true; auto skipTopLevelConst = [](const Token* start) -> const Token* { const Token* tok = start->next(); if (Token::simpleMatch(tok, "const")) { tok = tok->next(); while (Token::Match(tok, "%name%|%type%|::")) tok = tok->next(); if (Token::Match(tok, ",|)|=")) return start->next(); } return start; }; while (first->str() == second->str() && first->isLong() == second->isLong() && first->isUnsigned() == second->isUnsigned()) { if (first->str() == "(") openParen++; // at end of argument list else if (first->str() == ")") { if (openParen == 1) return true; --openParen; } // skip optional type information if (Token::Match(first->next(), "struct|enum|union|class")) first = first->next(); if (Token::Match(second->next(), "struct|enum|union|class")) second = second->next(); // skip const on type passed by value const Token* const oldSecond = second; first = skipTopLevelConst(first); second = skipTopLevelConst(second); // skip default value assignment if (oldSecond == second && first->strAt(1) == "=") { first = first->nextArgument(); if (first) first = first->tokAt(-2); if (second->strAt(1) == "=") { second = second->nextArgument(); if (second) second = second->tokAt(-2); if (!first || !second) { // End of argument list (first or second) return !first && !second; } } else if (!first) { // End of argument list (first) return !second->nextArgument(); // End of argument list (second) } } else if (oldSecond == second && second->strAt(1) == "=") { second = second->nextArgument(); if (second) second = second->tokAt(-2); if (!second) { // End of argument list (second) return !first->nextArgument(); } } // definition missing variable name else if ((first->strAt(1) == "," && second->strAt(1) != ",") || (Token::Match(first, "!!( )") && second->strAt(1) != ")")) { second = second->next(); // skip default value assignment if (second->strAt(1) == "=") { do { second = second->next(); } while (!Token::Match(second->next(), ",|)")); } } else if (first->strAt(1) == "[" && second->strAt(1) != "[") second = second->next(); // function missing variable name else if ((second->strAt(1) == "," && first->strAt(1) != ",") || (Token::Match(second, "!!( )") && first->strAt(1) != ")")) { first = first->next(); // skip default value assignment if (first->strAt(1) == "=") { do { first = first->next(); } while (!Token::Match(first->next(), ",|)")); } } else if (second->strAt(1) == "[" && first->strAt(1) != "[") first = first->next(); // unnamed parameters else if (Token::Match(first, "(|, %type% ,|)") && Token::Match(second, "(|, %type% ,|)")) { if (first->next()->expressionString() != second->next()->expressionString()) break; first = first->next(); second = second->next(); continue; } // argument list has different number of arguments else if (openParen == 1 && second->str() == ")" && first->str() != ")") break; // check for type * x == type x[] else if (Token::Match(first->next(), "* %name%| ,|)|=") && Token::Match(second->next(), "%name%| [ ] ,|)")) { do { first = first->next(); } while (!Token::Match(first->next(), ",|)")); do { second = second->next(); } while (!Token::Match(second->next(), ",|)")); } // const after * else if (first->strAt(1) == "*" && second->strAt(1) == "*" && ((first->strAt(2) != "const" && second->strAt(2) == "const") || (first->strAt(2) == "const" && second->strAt(2) != "const"))) { if (first->strAt(2) != "const") { if (Token::Match(first->tokAt(2), "%name%| ,|)") && Token::Match(second->tokAt(3), "%name%| ,|)")) { first = first->tokAt(Token::Match(first->tokAt(2), "%name%") ? 2 : 1); second = second->tokAt(Token::Match(second->tokAt(3), "%name%") ? 3 : 2); } else { first = first->next(); second = second->tokAt(2); } } else { if (Token::Match(second->tokAt(2), "%name%| ,|)") && Token::Match(first->tokAt(3), "%name%| ,|)")) { first = first->tokAt(Token::Match(first->tokAt(3), "%name%") ? 3 : 2); second = second->tokAt(Token::Match(second->tokAt(2), "%name%") ? 2 : 1); } else { first = first->tokAt(2); second = second->next(); } } } // variable names are different else if ((Token::Match(first->next(), "%name% ,|)|=|[") && Token::Match(second->next(), "%name% ,|)|[")) && (first->strAt(1) != second->strAt(1))) { // skip variable names first = first->next(); second = second->next(); // skip default value assignment if (first->strAt(1) == "=") { do { first = first->next(); } while (!Token::Match(first->next(), ",|)")); } } // using namespace else if (usingNamespace(scope, first->next(), second->next(), offset)) first = first->tokAt(offset); // same type with different qualification else if (typesMatch(scope, first->next(), nestedIn, second->next(), first, second)) ; // variable with class path else if (arg_path_length && Token::Match(first->next(), "%name%") && first->strAt(1) != "const") { std::string param = path; if (Token::simpleMatch(second->next(), param.c_str(), param.size())) { // check for redundant qualification before skipping it if (!Token::simpleMatch(first->next(), param.c_str(), param.size())) { second = second->tokAt(arg_path_length); arg_path_length = 0; } } // nested or base class variable else if (arg_path_length <= 2 && Token::Match(first->next(), "%name%") && (Token::Match(second->next(), "%name% :: %name%") || (Token::Match(second->next(), "%name% <") && Token::Match(second->linkAt(1), "> :: %name%"))) && ((second->strAt(1) == scope->className) || (scope->nestedIn && second->strAt(1) == scope->nestedIn->className) || (scope->definedType && scope->definedType->isDerivedFrom(second->strAt(1)))) && (first->strAt(1) == second->strAt(3))) { if (Token::Match(second->next(), "%name% <")) second = second->linkAt(1)->next(); else second = second->tokAt(2); } // remove class name else if (arg_path_length > 2 && first->strAt(1) != second->strAt(1)) { std::string short_path = path; int short_path_length = arg_path_length; // remove last " :: " short_path.resize(short_path.size() - 4); short_path_length--; // remove last name std::string::size_type lastSpace = short_path.find_last_of(' '); if (lastSpace != std::string::npos) { short_path.resize(lastSpace+1); short_path_length--; if (short_path[short_path.size() - 1] == '>') { short_path.resize(short_path.size() - 3); while (short_path[short_path.size() - 1] == '<') { lastSpace = short_path.find_last_of(' '); short_path.resize(lastSpace+1); short_path_length--; } } } param = std::move(short_path); if (Token::simpleMatch(second->next(), param.c_str(), param.size())) { second = second->tokAt(short_path_length); arg_path_length = 0; } } } first = first->next(); second = second->next(); // reset path length if (first->str() == "," || second->str() == ",") arg_path_length = path_length; } return false; } static bool isUnknownType(const Token* start, const Token* end) { while (Token::Match(start, "const|volatile")) start = start->next(); start = skipScopeIdentifiers(start); if (start->tokAt(1) == end && !start->type() && !start->isStandardType()) return true; // TODO: Try to deduce the type of the expression if (Token::Match(start, "decltype|typeof")) return true; return false; } static const Token* getEnableIfReturnType(const Token* start) { if (!start) return nullptr; for (const Token* tok = start->next(); precedes(tok, start->link()); tok = tok->next()) { if (tok->link() && Token::Match(tok, "(|[|{|<")) { tok = tok->link(); continue; } if (Token::simpleMatch(tok, ",")) return tok->next(); } return nullptr; } template<class Predicate> static bool checkReturns(const Function* function, bool unknown, bool emptyEnableIf, Predicate pred) { if (!function) return false; if (function->type != Function::eFunction && function->type != Function::eOperatorEqual && function->type != Function::eLambda) return false; const Token* defStart = function->retDef; if (!defStart) return unknown; const Token* defEnd = function->returnDefEnd(); if (!defEnd) return unknown; if (defEnd == defStart) return unknown; if (pred(defStart, defEnd)) return true; if (Token::Match(defEnd->tokAt(-1), "*|&|&&")) return false; // void STDCALL foo() while (defEnd->previous() != defStart && Token::Match(defEnd->tokAt(-2), "%name%|> %name%") && !Token::Match(defEnd->tokAt(-2), "const|volatile")) defEnd = defEnd->previous(); // enable_if const Token* enableIfEnd = nullptr; if (Token::simpleMatch(defEnd->previous(), ">")) enableIfEnd = defEnd->previous(); else if (Token::simpleMatch(defEnd->tokAt(-3), "> :: type")) enableIfEnd = defEnd->tokAt(-3); if (enableIfEnd && enableIfEnd->link() && Token::Match(enableIfEnd->link()->previous(), "enable_if|enable_if_t|EnableIf")) { if (const Token* start = getEnableIfReturnType(enableIfEnd->link())) { defStart = start; defEnd = enableIfEnd; } else { return emptyEnableIf; } } assert(defEnd != defStart); if (pred(defStart, defEnd)) return true; if (isUnknownType(defStart, defEnd)) return unknown; return false; } bool Function::returnsConst(const Function* function, bool unknown) { return checkReturns(function, unknown, false, [](const Token* defStart, const Token* defEnd) { return Token::findsimplematch(defStart, "const", defEnd); }); } bool Function::returnsReference(const Function* function, bool unknown, bool includeRValueRef) { return checkReturns(function, unknown, false, [includeRValueRef](const Token* /*defStart*/, const Token* defEnd) { return includeRValueRef ? Token::Match(defEnd->previous(), "&|&&") : Token::simpleMatch(defEnd->previous(), "&"); }); } bool Function::returnsPointer(const Function* function, bool unknown) { return checkReturns(function, unknown, false, [](const Token* /*defStart*/, const Token* defEnd) { return Token::simpleMatch(defEnd->previous(), "*"); }); } bool Function::returnsStandardType(const Function* function, bool unknown) { return checkReturns(function, unknown, true, [](const Token* /*defStart*/, const Token* defEnd) { return defEnd->previous() && defEnd->previous()->isStandardType(); }); } bool Function::returnsVoid(const Function* function, bool unknown) { return checkReturns(function, unknown, true, [](const Token* /*defStart*/, const Token* defEnd) { return Token::simpleMatch(defEnd->previous(), "void"); }); } std::vector<const Token*> Function::findReturns(const Function* f) { std::vector<const Token*> result; if (!f) return result; const Scope* scope = f->functionScope; if (!scope) return result; if (!scope->bodyStart) return result; for (const Token* tok = scope->bodyStart->next(); tok && tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() == "{" && tok->scope() && (tok->scope()->type == Scope::eLambda || tok->scope()->type == Scope::eClass)) { tok = tok->link(); continue; } if (Token::simpleMatch(tok->astParent(), "return")) { result.push_back(tok); } // Skip lambda functions since the scope may not be set correctly const Token* lambdaEndToken = findLambdaEndToken(tok); if (lambdaEndToken) { tok = lambdaEndToken; } } return result; } const Token * Function::constructorMemberInitialization() const { if (!isConstructor() || !arg) return nullptr; if (Token::simpleMatch(arg->link(), ") :")) return arg->link()->next(); if (Token::simpleMatch(arg->link(), ") noexcept (") && arg->link()->linkAt(2)->strAt(1) == ":") return arg->link()->linkAt(2)->next(); return nullptr; } bool Function::isSafe(const Settings &settings) const { if (settings.safeChecks.externalFunctions) { if (nestedIn->type == Scope::ScopeType::eNamespace && token->fileIndex() != 0) return true; if (nestedIn->type == Scope::ScopeType::eGlobal && (token->fileIndex() != 0 || !isStatic())) return true; } if (settings.safeChecks.internalFunctions) { if (nestedIn->type == Scope::ScopeType::eNamespace && token->fileIndex() == 0) return true; if (nestedIn->type == Scope::ScopeType::eGlobal && (token->fileIndex() == 0 || isStatic())) return true; } if (settings.safeChecks.classes && access == AccessControl::Public && (nestedIn->type == Scope::ScopeType::eClass || nestedIn->type == Scope::ScopeType::eStruct)) return true; return false; } Function* SymbolDatabase::addGlobalFunction(Scope*& scope, const Token*& tok, const Token *argStart, const Token* funcStart) { Function* function = nullptr; // Lambda functions are always unique if (tok->str() != "[") { auto range = scope->functionMap.equal_range(tok->str()); for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) { const Function *f = it->second; if (f->hasBody()) continue; if (f->argsMatch(scope, f->argDef, argStart, emptyString, 0)) { function = const_cast<Function *>(it->second); break; } } } if (!function) function = addGlobalFunctionDecl(scope, tok, argStart, funcStart); function->arg = argStart; function->token = funcStart; function->hasBody(true); addNewFunction(scope, tok); if (scope) { scope->function = function; function->functionScope = scope; return function; } return nullptr; } Function* SymbolDatabase::addGlobalFunctionDecl(Scope*& scope, const Token *tok, const Token *argStart, const Token* funcStart) { Function function(tok, scope, funcStart, argStart); scope->addFunction(std::move(function)); return &scope->functionList.back(); } void SymbolDatabase::addClassFunction(Scope *&scope, const Token *&tok, const Token *argStart) { const bool destructor(tok->strAt(-1) == "~"); const bool has_const(argStart->link()->strAt(1) == "const"); const bool lval(argStart->link()->strAt(has_const ? 2 : 1) == "&"); const bool rval(argStart->link()->strAt(has_const ? 2 : 1) == "&&"); int count = 0; std::string path; unsigned int path_length = 0; const Token *tok1 = tok; if (destructor) tok1 = tok1->previous(); // back up to head of path while (tok1 && tok1->previous() && tok1->strAt(-1) == "::" && tok1->tokAt(-2) && ((tok1->tokAt(-2)->isName() && !tok1->tokAt(-2)->isStandardType()) || (tok1->strAt(-2) == ">" && tok1->linkAt(-2) && Token::Match(tok1->linkAt(-2)->previous(), "%name%")))) { count++; const Token * tok2 = tok1->tokAt(-2); if (tok2->str() == ">") tok2 = tok2->link()->previous(); if (tok2) { do { path = tok1->strAt(-1) + " " + path; tok1 = tok1->previous(); path_length++; } while (tok1 != tok2); } else return; // syntax error ? } // syntax error? if (!tok1) return; // add global namespace if present if (tok1->strAt(-1) == "::") { path_length++; path.insert(0, ":: "); } // search for match for (std::list<Scope>::iterator it1 = scopeList.begin(); it1 != scopeList.end(); ++it1) { Scope *scope1 = &(*it1); bool match = false; // check in namespace if using found if (scope == scope1 && !scope1->usingList.empty()) { std::vector<Scope::UsingInfo>::const_iterator it2; for (it2 = scope1->usingList.cbegin(); it2 != scope1->usingList.cend(); ++it2) { if (it2->scope) { Function * func = findFunctionInScope(tok1, it2->scope, path, path_length); if (func) { if (!func->hasBody()) { const Token *closeParen = tok->linkAt(1); if (closeParen) { const Token *eq = Tokenizer::isFunctionHead(closeParen, ";"); if (eq && Token::simpleMatch(eq->tokAt(-2), "= default ;")) { func->isDefault(true); return; } } func->hasBody(true); func->token = tok; func->arg = argStart; addNewFunction(scope, tok); if (scope) { scope->functionOf = func->nestedIn; scope->function = func; scope->function->functionScope = scope; } return; } } } } } const bool isAnonymousNamespace = (scope1->type == Scope::eNamespace && scope1->className.empty()); if ((scope1->className == tok1->str() && (scope1->type != Scope::eFunction)) || isAnonymousNamespace) { // do the scopes match (same scope) or do their names match (multiple namespaces) if ((scope == scope1->nestedIn) || (scope && scope->className == scope1->nestedIn->className && !scope->className.empty() && scope->type == scope1->nestedIn->type)) { // nested scopes => check that they match { const Scope *s1 = scope; const Scope *s2 = scope1->nestedIn; while (s1 && s2) { if (s1->className != s2->className) break; s1 = s1->nestedIn; s2 = s2->nestedIn; } // Not matching scopes if (s1 || s2) continue; } Scope *scope2 = scope1; while (scope2 && count > 1) { count--; if (tok1->strAt(1) == "<") tok1 = tok1->linkAt(1)->tokAt(2); else tok1 = tok1->tokAt(2); scope2 = scope2->findRecordInNestedList(tok1->str()); } if (scope2 && isAnonymousNamespace) scope2 = scope2->findRecordInNestedList(tok1->str()); if (count == 1 && scope2) { match = true; scope1 = scope2; } } } if (match) { auto range = scope1->functionMap.equal_range(tok->str()); for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) { auto * func = const_cast<Function *>(it->second); if (!func->hasBody()) { if (func->argsMatch(scope1, func->argDef, tok->next(), path, path_length)) { const Token *closeParen = tok->linkAt(1); if (closeParen) { const Token *eq = Tokenizer::isFunctionHead(closeParen, ";"); if (eq && Token::simpleMatch(eq->tokAt(-2), "= default ;")) { func->isDefault(true); return; } if (func->type == Function::eDestructor && destructor) { func->hasBody(true); } else if (func->type != Function::eDestructor && !destructor) { // normal function? const bool hasConstKeyword = closeParen->strAt(1) == "const"; if ((func->isConst() == hasConstKeyword) && (func->hasLvalRefQualifier() == lval) && (func->hasRvalRefQualifier() == rval)) { func->hasBody(true); } } } if (func->hasBody()) { func->token = tok; func->arg = argStart; addNewFunction(scope, tok); if (scope) { scope->functionOf = scope1; scope->function = func; scope->function->functionScope = scope; } return; } } } } } } // class function of unknown class addNewFunction(scope, tok); } void SymbolDatabase::addNewFunction(Scope *&scope, const Token *&tok) { const Token *tok1 = tok; scopeList.emplace_back(this, tok1, scope); Scope *newScope = &scopeList.back(); // find start of function '{' bool foundInitList = false; while (tok1 && tok1->str() != "{" && tok1->str() != ";") { if (tok1->link() && Token::Match(tok1, "(|[|<")) { tok1 = tok1->link(); } else if (foundInitList && Token::Match(tok1, "%name%|> {") && Token::Match(tok1->linkAt(1), "} ,|{")) { tok1 = tok1->linkAt(1); } else { if (tok1->str() == ":") foundInitList = true; tok1 = tok1->next(); } } if (tok1 && tok1->str() == "{") { newScope->setBodyStartEnd(tok1); // syntax error? if (!newScope->bodyEnd) { mTokenizer.unmatchedToken(tok1); } else { scope->nestedList.push_back(newScope); scope = newScope; } } else if (tok1 && Token::Match(tok1->tokAt(-2), "= default|delete ;")) { scopeList.pop_back(); } else { throw InternalError(tok, "Analysis failed (function not recognized). If the code is valid then please report this failure."); } tok = tok1; } bool Type::isClassType() const { return classScope && classScope->type == Scope::ScopeType::eClass; } bool Type::isEnumType() const { //We explicitly check for "enum" because a forward declared enum doesn't get its own scope return (classDef && classDef->str() == "enum") || (classScope && classScope->type == Scope::ScopeType::eEnum); } bool Type::isStructType() const { return classScope && classScope->type == Scope::ScopeType::eStruct; } bool Type::isUnionType() const { return classScope && classScope->type == Scope::ScopeType::eUnion; } const Token *Type::initBaseInfo(const Token *tok, const Token *tok1) { // goto initial '{' const Token *tok2 = tok1; while (tok2 && tok2->str() != "{") { // skip unsupported templates if (tok2->str() == "<") tok2 = tok2->link(); // check for base classes else if (Token::Match(tok2, ":|,")) { tok2 = tok2->next(); // check for invalid code if (!tok2 || !tok2->next()) return nullptr; Type::BaseInfo base; if (tok2->str() == "virtual") { base.isVirtual = true; tok2 = tok2->next(); } if (tok2->str() == "public") { base.access = AccessControl::Public; tok2 = tok2->next(); } else if (tok2->str() == "protected") { base.access = AccessControl::Protected; tok2 = tok2->next(); } else if (tok2->str() == "private") { base.access = AccessControl::Private; tok2 = tok2->next(); } else { if (tok->str() == "class") base.access = AccessControl::Private; else if (tok->str() == "struct") base.access = AccessControl::Public; } if (!tok2) return nullptr; if (tok2->str() == "virtual") { base.isVirtual = true; tok2 = tok2->next(); } if (!tok2) return nullptr; base.nameTok = tok2; // handle global namespace if (tok2->str() == "::") { tok2 = tok2->next(); } // handle derived base classes while (Token::Match(tok2, "%name% ::")) { tok2 = tok2->tokAt(2); } if (!tok2) return nullptr; base.name = tok2->str(); tok2 = tok2->next(); // add unhandled templates if (tok2 && tok2->link() && tok2->str() == "<") { for (const Token* const end = tok2->link()->next(); tok2 != end; tok2 = tok2->next()) { base.name += tok2->str(); } } const Type * baseType = classScope->check->findType(base.nameTok, enclosingScope); if (baseType && !baseType->findDependency(this)) base.type = baseType; // save pattern for base class name derivedFrom.push_back(std::move(base)); } else tok2 = tok2->next(); } return tok2; } std::string Type::name() const { const Token* start = classDef->next(); if (classScope && classScope->enumClass && isEnumType()) start = start->tokAt(1); else if (start->str() == "class") start = start->tokAt(1); else if (!start->isName()) return emptyString; const Token* next = start; while (Token::Match(next, "::|<|>|(|)|[|]|*|&|&&|%name%")) { if (Token::Match(next, "<|(|[") && next->link()) next = next->link(); next = next->next(); } std::string result; for (const Token* tok = start; tok != next; tok = tok->next()) { if (!result.empty()) result += ' '; result += tok->str(); } return result; } void SymbolDatabase::debugMessage(const Token *tok, const std::string &type, const std::string &msg) const { if (tok && mSettings.debugwarnings) { const std::list<const Token*> locationList(1, tok); const ErrorMessage errmsg(locationList, &mTokenizer.list, Severity::debug, type, msg, Certainty::normal); mErrorLogger.reportErr(errmsg); } } void SymbolDatabase::returnImplicitIntError(const Token *tok) const { if (tok && mSettings.severity.isEnabled(Severity::portability) && (tok->isC() && mSettings.standards.c != Standards::C89)) { const std::list<const Token*> locationList(1, tok); const ErrorMessage errmsg(locationList, &mTokenizer.list, Severity::portability, "returnImplicitInt", "Omitted return type of function '" + tok->str() + "' defaults to int, this is not supported by ISO C99 and later standards.", Certainty::normal); mErrorLogger.reportErr(errmsg); } } const Function* Type::getFunction(const std::string& funcName) const { if (classScope) { const std::multimap<std::string, const Function *>::const_iterator it = classScope->functionMap.find(funcName); if (it != classScope->functionMap.end()) return it->second; } for (const Type::BaseInfo & i : derivedFrom) { if (i.type) { const Function* const func = i.type->getFunction(funcName); if (func) return func; } } return nullptr; } bool Type::hasCircularDependencies(std::set<BaseInfo>* ancestors) const { std::set<BaseInfo> knownAncestors; if (!ancestors) { ancestors=&knownAncestors; } for (auto parent=derivedFrom.cbegin(); parent!=derivedFrom.cend(); ++parent) { if (!parent->type) continue; if (this==parent->type) return true; if (ancestors->find(*parent)!=ancestors->end()) return true; ancestors->insert(*parent); if (parent->type->hasCircularDependencies(ancestors)) return true; } return false; } bool Type::findDependency(const Type* ancestor) const { return this == ancestor || std::any_of(derivedFrom.cbegin(), derivedFrom.cend(), [&](const BaseInfo& d) { return d.type && (d.type == this || d.type->findDependency(ancestor)); }); } bool Type::isDerivedFrom(const std::string & ancestor) const { for (std::vector<BaseInfo>::const_iterator parent=derivedFrom.cbegin(); parent!=derivedFrom.cend(); ++parent) { if (parent->name == ancestor) return true; if (parent->type && parent->type->isDerivedFrom(ancestor)) return true; } return false; } bool Variable::arrayDimensions(const Settings& settings, bool& isContainer) { isContainer = false; const Library::Container* container = (mTypeStartToken && mTypeStartToken->isCpp()) ? settings.library.detectContainer(mTypeStartToken) : nullptr; if (container && container->arrayLike_indexOp && container->size_templateArgNo > 0) { const Token* tok = Token::findsimplematch(mTypeStartToken, "<"); if (tok) { isContainer = true; Dimension dimension_; tok = tok->next(); for (int i = 0; i < container->size_templateArgNo && tok; i++) { tok = tok->nextTemplateArgument(); } if (Token::Match(tok, "%num% [,>]")) { dimension_.tok = tok; dimension_.known = true; dimension_.num = MathLib::toBigNumber(tok->str()); } else if (tok) { dimension_.tok = tok; dimension_.known = false; } mDimensions.push_back(dimension_); return true; } } const Token *dim = mNameToken; if (!dim) { // Argument without name dim = mTypeEndToken; // back up to start of array dimensions while (dim && dim->str() == "]") dim = dim->link()->previous(); } if (dim) dim = dim->next(); if (dim && dim->str() == ")") dim = dim->next(); bool arr = false; while (dim && dim->next() && dim->str() == "[") { Dimension dimension_; dimension_.known = false; // check for empty array dimension [] if (dim->strAt(1) != "]") { dimension_.tok = dim->astOperand2(); // TODO: only perform when ValueFlow is enabled // TODO: collect timing information for this call? ValueFlow::valueFlowConstantFoldAST(const_cast<Token *>(dimension_.tok), settings); if (dimension_.tok && dimension_.tok->hasKnownIntValue()) { dimension_.num = dimension_.tok->getKnownIntValue(); dimension_.known = true; } } mDimensions.push_back(dimension_); dim = dim->link()->next(); arr = true; } return arr; } static std::string scopeTypeToString(Scope::ScopeType type) { switch (type) { case Scope::ScopeType::eGlobal: return "Global"; case Scope::ScopeType::eClass: return "Class"; case Scope::ScopeType::eStruct: return "Struct"; case Scope::ScopeType::eUnion: return "Union"; case Scope::ScopeType::eNamespace: return "Namespace"; case Scope::ScopeType::eFunction: return "Function"; case Scope::ScopeType::eIf: return "If"; case Scope::ScopeType::eElse: return "Else"; case Scope::ScopeType::eFor: return "For"; case Scope::ScopeType::eWhile: return "While"; case Scope::ScopeType::eDo: return "Do"; case Scope::ScopeType::eSwitch: return "Switch"; case Scope::ScopeType::eTry: return "Try"; case Scope::ScopeType::eCatch: return "Catch"; case Scope::ScopeType::eUnconditional: return "Unconditional"; case Scope::ScopeType::eLambda: return "Lambda"; case Scope::ScopeType::eEnum: return "Enum"; } return "Unknown"; } static std::ostream & operator << (std::ostream & s, Scope::ScopeType type) { s << scopeTypeToString(type); return s; } static std::string accessControlToString(AccessControl access) { switch (access) { case AccessControl::Public: return "Public"; case AccessControl::Protected: return "Protected"; case AccessControl::Private: return "Private"; case AccessControl::Global: return "Global"; case AccessControl::Namespace: return "Namespace"; case AccessControl::Argument: return "Argument"; case AccessControl::Local: return "Local"; case AccessControl::Throw: return "Throw"; } return "Unknown"; } static const char* functionTypeToString(Function::Type type) { switch (type) { case Function::eConstructor: return "Constructor"; case Function::eCopyConstructor: return "CopyConstructor"; case Function::eMoveConstructor: return "MoveConstructor"; case Function::eOperatorEqual: return "OperatorEqual"; case Function::eDestructor: return "Destructor"; case Function::eFunction: return "Function"; case Function::eLambda: return "Lambda"; default: return "Unknown"; } } static std::string tokenToString(const Token* tok, const Tokenizer& tokenizer) { std::ostringstream oss; if (tok) { oss << tok->str() << " "; oss << tokenizer.list.fileLine(tok) << " "; } oss << tok; return oss.str(); } static std::string scopeToString(const Scope* scope, const Tokenizer& tokenizer) { std::ostringstream oss; if (scope) { oss << scope->type << " "; if (!scope->className.empty()) oss << scope->className << " "; if (scope->classDef) oss << tokenizer.list.fileLine(scope->classDef) << " "; } oss << scope; return oss.str(); } static std::string tokenType(const Token * tok) { std::ostringstream oss; if (tok) { if (tok->isUnsigned()) oss << "unsigned "; else if (tok->isSigned()) oss << "signed "; if (tok->isComplex()) oss << "_Complex "; if (tok->isLong()) oss << "long "; oss << tok->str(); } return oss.str(); } void SymbolDatabase::printVariable(const Variable *var, const char *indent) const { std::cout << indent << "mNameToken: " << tokenToString(var->nameToken(), mTokenizer) << std::endl; if (var->nameToken()) { std::cout << indent << " declarationId: " << var->declarationId() << std::endl; } std::cout << indent << "mTypeStartToken: " << tokenToString(var->typeStartToken(), mTokenizer) << std::endl; std::cout << indent << "mTypeEndToken: " << tokenToString(var->typeEndToken(), mTokenizer) << std::endl; if (var->typeStartToken()) { const Token * autoTok = nullptr; std::cout << indent << " "; for (const Token * tok = var->typeStartToken(); tok != var->typeEndToken()->next(); tok = tok->next()) { std::cout << " " << tokenType(tok); if (tok->str() == "auto") autoTok = tok; } std::cout << std::endl; if (autoTok) { const ValueType * valueType = autoTok->valueType(); std::cout << indent << " auto valueType: " << valueType << std::endl; if (var->typeStartToken()->valueType()) { std::cout << indent << " " << valueType->str() << std::endl; } } } else if (var->valueType()) { std::cout << indent << " " << var->valueType()->str() << std::endl; } std::cout << indent << "mIndex: " << var->index() << std::endl; std::cout << indent << "mAccess: " << accessControlToString(var->accessControl()) << std::endl; std::cout << indent << "mFlags: " << std::endl; std::cout << indent << " isMutable: " << var->isMutable() << std::endl; std::cout << indent << " isStatic: " << var->isStatic() << std::endl; std::cout << indent << " isExtern: " << var->isExtern() << std::endl; std::cout << indent << " isLocal: " << var->isLocal() << std::endl; std::cout << indent << " isConst: " << var->isConst() << std::endl; std::cout << indent << " isClass: " << var->isClass() << std::endl; std::cout << indent << " isArray: " << var->isArray() << std::endl; std::cout << indent << " isPointer: " << var->isPointer() << std::endl; std::cout << indent << " isReference: " << var->isReference() << std::endl; std::cout << indent << " isRValueRef: " << var->isRValueReference() << std::endl; std::cout << indent << " hasDefault: " << var->hasDefault() << std::endl; std::cout << indent << " isStlType: " << var->isStlType() << std::endl; std::cout << indent << "mType: "; if (var->type()) { std::cout << var->type()->type() << " " << var->type()->name(); std::cout << " " << mTokenizer.list.fileLine(var->type()->classDef); std::cout << " " << var->type() << std::endl; } else std::cout << "none" << std::endl; if (var->nameToken()) { const ValueType * valueType = var->nameToken()->valueType(); std::cout << indent << "valueType: " << valueType << std::endl; if (valueType) { std::cout << indent << " " << valueType->str() << std::endl; } } std::cout << indent << "mScope: " << scopeToString(var->scope(), mTokenizer) << std::endl; std::cout << indent << "mDimensions:"; for (std::size_t i = 0; i < var->dimensions().size(); i++) { std::cout << " " << var->dimension(i); if (!var->dimensions()[i].known) std::cout << "?"; } std::cout << std::endl; } void SymbolDatabase::printOut(const char *title) const { std::cout << std::setiosflags(std::ios::boolalpha); if (title) std::cout << "\n### " << title << " ###\n"; for (std::list<Scope>::const_iterator scope = scopeList.cbegin(); scope != scopeList.cend(); ++scope) { std::cout << "Scope: " << &*scope << " " << scope->type << std::endl; std::cout << " className: " << scope->className << std::endl; std::cout << " classDef: " << tokenToString(scope->classDef, mTokenizer) << std::endl; std::cout << " bodyStart: " << tokenToString(scope->bodyStart, mTokenizer) << std::endl; std::cout << " bodyEnd: " << tokenToString(scope->bodyEnd, mTokenizer) << std::endl; // find the function body if not implemented inline for (auto func = scope->functionList.cbegin(); func != scope->functionList.cend(); ++func) { std::cout << " Function: " << &*func << std::endl; std::cout << " name: " << tokenToString(func->tokenDef, mTokenizer) << std::endl; std::cout << " type: " << functionTypeToString(func->type) << std::endl; std::cout << " access: " << accessControlToString(func->access) << std::endl; std::cout << " hasBody: " << func->hasBody() << std::endl; std::cout << " isInline: " << func->isInline() << std::endl; std::cout << " isConst: " << func->isConst() << std::endl; std::cout << " hasVirtualSpecifier: " << func->hasVirtualSpecifier() << std::endl; std::cout << " isPure: " << func->isPure() << std::endl; std::cout << " isStatic: " << func->isStatic() << std::endl; std::cout << " isStaticLocal: " << func->isStaticLocal() << std::endl; std::cout << " isExtern: " << func->isExtern() << std::endl; std::cout << " isFriend: " << func->isFriend() << std::endl; std::cout << " isExplicit: " << func->isExplicit() << std::endl; std::cout << " isDefault: " << func->isDefault() << std::endl; std::cout << " isDelete: " << func->isDelete() << std::endl; std::cout << " hasOverrideSpecifier: " << func->hasOverrideSpecifier() << std::endl; std::cout << " hasFinalSpecifier: " << func->hasFinalSpecifier() << std::endl; std::cout << " isNoExcept: " << func->isNoExcept() << std::endl; std::cout << " isThrow: " << func->isThrow() << std::endl; std::cout << " isOperator: " << func->isOperator() << std::endl; std::cout << " hasLvalRefQual: " << func->hasLvalRefQualifier() << std::endl; std::cout << " hasRvalRefQual: " << func->hasRvalRefQualifier() << std::endl; std::cout << " isVariadic: " << func->isVariadic() << std::endl; std::cout << " isVolatile: " << func->isVolatile() << std::endl; std::cout << " hasTrailingReturnType: " << func->hasTrailingReturnType() << std::endl; std::cout << " attributes:"; if (func->isAttributeConst()) std::cout << " const "; if (func->isAttributePure()) std::cout << " pure "; if (func->isAttributeNoreturn()) std::cout << " noreturn "; if (func->isAttributeNothrow()) std::cout << " nothrow "; if (func->isAttributeConstructor()) std::cout << " constructor "; if (func->isAttributeDestructor()) std::cout << " destructor "; if (func->isAttributeNodiscard()) std::cout << " nodiscard "; std::cout << std::endl; std::cout << " noexceptArg: " << (func->noexceptArg ? func->noexceptArg->str() : "none") << std::endl; std::cout << " throwArg: " << (func->throwArg ? func->throwArg->str() : "none") << std::endl; std::cout << " tokenDef: " << tokenToString(func->tokenDef, mTokenizer) << std::endl; std::cout << " argDef: " << tokenToString(func->argDef, mTokenizer) << std::endl; if (!func->isConstructor() && !func->isDestructor()) std::cout << " retDef: " << tokenToString(func->retDef, mTokenizer) << std::endl; if (func->retDef) { std::cout << " "; for (const Token * tok = func->retDef; tok && tok != func->tokenDef && !Token::Match(tok, "{|;|override|final"); tok = tok->next()) std::cout << " " << tokenType(tok); std::cout << std::endl; } std::cout << " retType: " << func->retType << std::endl; if (const ValueType* valueType = func->tokenDef->next()->valueType()) { std::cout << " valueType: " << valueType << std::endl; std::cout << " " << valueType->str() << std::endl; } if (func->hasBody()) { std::cout << " token: " << tokenToString(func->token, mTokenizer) << std::endl; std::cout << " arg: " << tokenToString(func->arg, mTokenizer) << std::endl; } std::cout << " nestedIn: " << scopeToString(func->nestedIn, mTokenizer) << std::endl; std::cout << " functionScope: " << scopeToString(func->functionScope, mTokenizer) << std::endl; for (auto var = func->argumentList.cbegin(); var != func->argumentList.cend(); ++var) { std::cout << " Variable: " << &*var << std::endl; printVariable(&*var, " "); } } for (auto var = scope->varlist.cbegin(); var != scope->varlist.cend(); ++var) { std::cout << " Variable: " << &*var << std::endl; printVariable(&*var, " "); } if (scope->type == Scope::eEnum) { std::cout << " enumType: "; if (scope->enumType) { std::cout << scope->enumType->stringify(false, true, false); } else std::cout << "int"; std::cout << std::endl; std::cout << " enumClass: " << scope->enumClass << std::endl; for (const Enumerator &enumerator : scope->enumeratorList) { std::cout << " Enumerator: " << enumerator.name->str() << " = "; if (enumerator.value_known) std::cout << enumerator.value; if (enumerator.start) { const Token * tok = enumerator.start; std::cout << (enumerator.value_known ? " " : "") << "[" << tok->str(); while (tok && tok != enumerator.end) { if (tok->next()) std::cout << " " << tok->strAt(1); tok = tok->next(); } std::cout << "]"; } std::cout << std::endl; } } std::cout << " nestedIn: " << scope->nestedIn; if (scope->nestedIn) { std::cout << " " << scope->nestedIn->type << " " << scope->nestedIn->className; } std::cout << std::endl; std::cout << " definedType: " << scope->definedType << std::endl; std::cout << " nestedList[" << scope->nestedList.size() << "] = ("; std::size_t count = scope->nestedList.size(); for (std::vector<Scope*>::const_iterator nsi = scope->nestedList.cbegin(); nsi != scope->nestedList.cend(); ++nsi) { std::cout << " " << (*nsi) << " " << (*nsi)->type << " " << (*nsi)->className; if (count-- > 1) std::cout << ","; } std::cout << " )" << std::endl; for (auto use = scope->usingList.cbegin(); use != scope->usingList.cend(); ++use) { std::cout << " using: " << use->scope << " " << use->start->strAt(2); const Token *tok1 = use->start->tokAt(3); while (tok1 && tok1->str() == "::") { std::cout << "::" << tok1->strAt(1); tok1 = tok1->tokAt(2); } std::cout << " " << mTokenizer.list.fileLine(use->start) << std::endl; } std::cout << " functionOf: " << scopeToString(scope->functionOf, mTokenizer) << std::endl; std::cout << " function: " << scope->function; if (scope->function) std::cout << " " << scope->function->name(); std::cout << std::endl; } for (std::list<Type>::const_iterator type = typeList.cbegin(); type != typeList.cend(); ++type) { std::cout << "Type: " << &(*type) << std::endl; std::cout << " name: " << type->name() << std::endl; std::cout << " classDef: " << tokenToString(type->classDef, mTokenizer) << std::endl; std::cout << " classScope: " << type->classScope << std::endl; std::cout << " enclosingScope: " << type->enclosingScope; if (type->enclosingScope) { std::cout << " " << type->enclosingScope->type << " " << type->enclosingScope->className; } std::cout << std::endl; std::cout << " needInitialization: " << (type->needInitialization == Type::NeedInitialization::Unknown ? "Unknown" : type->needInitialization == Type::NeedInitialization::True ? "True" : type->needInitialization == Type::NeedInitialization::False ? "False" : "Invalid") << std::endl; std::cout << " derivedFrom[" << type->derivedFrom.size() << "] = ("; std::size_t count = type->derivedFrom.size(); for (const Type::BaseInfo & i : type->derivedFrom) { if (i.isVirtual) std::cout << "Virtual "; std::cout << (i.access == AccessControl::Public ? " Public" : i.access == AccessControl::Protected ? " Protected" : i.access == AccessControl::Private ? " Private" : " Unknown"); if (i.type) std::cout << " " << i.type; else std::cout << " Unknown"; std::cout << " " << i.name; if (count-- > 1) std::cout << ","; } std::cout << " )" << std::endl; std::cout << " friendList[" << type->friendList.size() << "] = ("; for (size_t i = 0; i < type->friendList.size(); i++) { if (type->friendList[i].type) std::cout << type->friendList[i].type; else std::cout << " Unknown"; std::cout << ' '; if (type->friendList[i].nameEnd) std::cout << type->friendList[i].nameEnd->str(); if (i+1 < type->friendList.size()) std::cout << ','; } std::cout << " )" << std::endl; } for (std::size_t i = 1; i < mVariableList.size(); i++) { std::cout << "mVariableList[" << i << "]: " << mVariableList[i]; if (mVariableList[i]) { std::cout << " " << mVariableList[i]->name() << " " << mTokenizer.list.fileLine(mVariableList[i]->nameToken()); } std::cout << std::endl; } std::cout << std::resetiosflags(std::ios::boolalpha); } void SymbolDatabase::printXml(std::ostream &out) const { std::string outs; std::set<const Variable *> variables; // Scopes.. outs += " <scopes>\n"; for (std::list<Scope>::const_iterator scope = scopeList.cbegin(); scope != scopeList.cend(); ++scope) { outs += " <scope"; outs += " id=\""; outs += id_string(&*scope); outs += "\""; outs += " type=\""; outs += scopeTypeToString(scope->type); outs += "\""; if (!scope->className.empty()) { outs += " className=\""; outs += ErrorLogger::toxml(scope->className); outs += "\""; } if (scope->bodyStart) { outs += " bodyStart=\""; outs += id_string(scope->bodyStart); outs += '\"'; } if (scope->bodyEnd) { outs += " bodyEnd=\""; outs += id_string(scope->bodyEnd); outs += '\"'; } if (scope->nestedIn) { outs += " nestedIn=\""; outs += id_string(scope->nestedIn); outs += "\""; } if (scope->function) { outs += " function=\""; outs += id_string(scope->function); outs += "\""; } if (scope->definedType) { outs += " definedType=\""; outs += id_string(scope->definedType); outs += "\""; } if (scope->functionList.empty() && scope->varlist.empty()) outs += "/>\n"; else { outs += ">\n"; if (!scope->functionList.empty()) { outs += " <functionList>\n"; for (std::list<Function>::const_iterator function = scope->functionList.cbegin(); function != scope->functionList.cend(); ++function) { outs += " <function id=\""; outs += id_string(&*function); outs += "\" token=\""; outs += id_string(function->token); outs += "\" tokenDef=\""; outs += id_string(function->tokenDef); outs += "\" name=\""; outs += ErrorLogger::toxml(function->name()); outs += '\"'; outs += " type=\""; outs += functionTypeToString(function->type); outs += '\"'; if (function->nestedIn->definedType) { if (function->hasVirtualSpecifier()) outs += " hasVirtualSpecifier=\"true\""; else if (function->isImplicitlyVirtual()) outs += " isImplicitlyVirtual=\"true\""; } if (function->access == AccessControl::Public || function->access == AccessControl::Protected || function->access == AccessControl::Private) { outs += " access=\""; outs += accessControlToString(function->access); outs +="\""; } if (function->isOperator()) outs += " isOperator=\"true\""; if (function->isExplicit()) outs += " isExplicit=\"true\""; if (function->hasOverrideSpecifier()) outs += " hasOverrideSpecifier=\"true\""; if (function->hasFinalSpecifier()) outs += " hasFinalSpecifier=\"true\""; if (function->isInlineKeyword()) outs += " isInlineKeyword=\"true\""; if (function->isStatic()) outs += " isStatic=\"true\""; if (function->isAttributeNoreturn()) outs += " isAttributeNoreturn=\"true\""; if (const Function* overriddenFunction = function->getOverriddenFunction()) { outs += " overriddenFunction=\""; outs += id_string(overriddenFunction); outs += "\""; } if (function->isAttributeConst()) outs += " isAttributeConst=\"true\""; if (function->isAttributePure()) outs += " isAttributePure=\"true\""; if (function->argCount() == 0U) outs += "/>\n"; else { outs += ">\n"; for (unsigned int argnr = 0; argnr < function->argCount(); ++argnr) { const Variable *arg = function->getArgumentVar(argnr); outs += " <arg nr=\""; outs += std::to_string(argnr+1); outs += "\" variable=\""; outs += id_string(arg); outs += "\"/>\n"; variables.insert(arg); } outs += " </function>\n"; } } outs += " </functionList>\n"; } if (!scope->varlist.empty()) { outs += " <varlist>\n"; for (std::list<Variable>::const_iterator var = scope->varlist.cbegin(); var != scope->varlist.cend(); ++var) { outs += " <var id=\""; outs += id_string(&*var); outs += "\"/>\n"; } outs += " </varlist>\n"; } outs += " </scope>\n"; } } outs += " </scopes>\n"; if (!typeList.empty()) { outs += " <types>\n"; for (const Type& type:typeList) { outs += " <type id=\""; outs += id_string(&type); outs += "\" classScope=\""; outs += id_string(type.classScope); outs += "\""; if (type.derivedFrom.empty()) { outs += "/>\n"; continue; } outs += ">\n"; for (const Type::BaseInfo& baseInfo: type.derivedFrom) { outs += " <derivedFrom"; outs += " access=\""; outs += accessControlToString(baseInfo.access); outs += "\""; outs += " type=\""; outs += id_string(baseInfo.type); outs += "\""; outs += " isVirtual=\""; outs += bool_to_string(baseInfo.isVirtual); outs += "\""; outs += " nameTok=\""; outs += id_string(baseInfo.nameTok); outs += "\""; outs += "/>\n"; } outs += " </type>\n"; } outs += " </types>\n"; } // Variables.. for (const Variable *var : mVariableList) variables.insert(var); outs += " <variables>\n"; for (const Variable *var : variables) { if (!var) continue; outs += " <var id=\""; outs += id_string(var); outs += '\"'; outs += " nameToken=\""; outs += id_string(var->nameToken()); outs += '\"'; outs += " typeStartToken=\""; outs += id_string(var->typeStartToken()); outs += '\"'; outs += " typeEndToken=\""; outs += id_string(var->typeEndToken()); outs += '\"'; outs += " access=\""; outs += accessControlToString(var->mAccess); outs += '\"'; outs += " scope=\""; outs += id_string(var->scope()); outs += '\"'; if (var->valueType()) { outs += " constness=\""; outs += std::to_string(var->valueType()->constness); outs += '\"'; outs += " volatileness=\""; outs += std::to_string(var->valueType()->volatileness); outs += '\"'; } outs += " isArray=\""; outs += bool_to_string(var->isArray()); outs += '\"'; outs += " isClass=\""; outs += bool_to_string(var->isClass()); outs += '\"'; outs += " isConst=\""; outs += bool_to_string(var->isConst()); outs += '\"'; outs += " isExtern=\""; outs += bool_to_string(var->isExtern()); outs += '\"'; outs += " isPointer=\""; outs += bool_to_string(var->isPointer()); outs += '\"'; outs += " isReference=\""; outs += bool_to_string(var->isReference()); outs += '\"'; outs += " isStatic=\""; outs += bool_to_string(var->isStatic()); outs += '\"'; outs += " isVolatile=\""; outs += bool_to_string(var->isVolatile()); outs += '\"'; outs += "/>\n"; } outs += " </variables>\n"; out << outs; } //--------------------------------------------------------------------------- static const Type* findVariableTypeIncludingUsedNamespaces(const SymbolDatabase* symbolDatabase, const Scope* scope, const Token* typeTok) { const Type* argType = symbolDatabase->findVariableType(scope, typeTok); if (argType) return argType; // look for variable type in any using namespace in this scope or above while (scope) { for (const Scope::UsingInfo &ui : scope->usingList) { if (ui.scope) { argType = symbolDatabase->findVariableType(ui.scope, typeTok); if (argType) return argType; } } scope = scope->nestedIn; } return nullptr; } //--------------------------------------------------------------------------- void Function::addArguments(const SymbolDatabase *symbolDatabase, const Scope *scope) { // check for non-empty argument list "( ... )" const Token * start = arg ? arg : argDef; if (!Token::simpleMatch(start, "(")) return; if (!(start && start->link() != start->next() && !Token::simpleMatch(start, "( void )"))) return; unsigned int count = 0; for (const Token* tok = start->next(); tok; tok = tok->next()) { if (Token::Match(tok, ",|)")) return; // Syntax error const Token* startTok = tok; const Token* endTok = nullptr; const Token* nameTok = nullptr; do { if (Token::simpleMatch(tok, "decltype (")) { tok = tok->linkAt(1)->next(); continue; } if (tok != startTok && !nameTok && Token::Match(tok, "( & %var% ) [")) { nameTok = tok->tokAt(2); endTok = nameTok->previous(); tok = tok->link(); } else if (tok != startTok && !nameTok && Token::Match(tok, "( * %var% ) (") && Token::Match(tok->link()->linkAt(1), ") [,)]")) { nameTok = tok->tokAt(2); endTok = nameTok->previous(); tok = tok->link()->linkAt(1); } else if (tok != startTok && !nameTok && Token::Match(tok, "( * %var% ) [")) { nameTok = tok->tokAt(2); endTok = nameTok->previous(); tok = tok->link(); } else if (tok->varId() != 0) { nameTok = tok; endTok = tok->previous(); } else if (tok->str() == "[") { // skip array dimension(s) tok = tok->link(); while (tok->strAt(1) == "[") tok = tok->linkAt(1); } else if (tok->str() == "<") { tok = tok->link(); if (!tok) // something is wrong so just bail out return; } tok = tok->next(); if (!tok) // something is wrong so just bail return; } while (tok->str() != "," && tok->str() != ")" && tok->str() != "="); const Token *typeTok = startTok; // skip over stuff to get to type while (Token::Match(typeTok, "const|volatile|enum|struct|::")) typeTok = typeTok->next(); if (Token::Match(typeTok, ",|)")) { // #8333 symbolDatabase->mTokenizer.syntaxError(typeTok); } if (Token::Match(typeTok, "%type% <") && Token::Match(typeTok->linkAt(1), "> :: %type%")) typeTok = typeTok->linkAt(1)->tokAt(2); // skip over qualification while (Token::Match(typeTok, "%type% ::")) { typeTok = typeTok->tokAt(2); if (Token::Match(typeTok, "%type% <") && Token::Match(typeTok->linkAt(1), "> :: %type%")) typeTok = typeTok->linkAt(1)->tokAt(2); } // check for argument with no name or missing varid if (!endTok) { if (tok->previous()->isName() && !Token::Match(tok->tokAt(-1), "const|volatile")) { if (tok->previous() != typeTok) { nameTok = tok->previous(); endTok = nameTok->previous(); if (hasBody()) symbolDatabase->debugMessage(nameTok, "varid0", "Function::addArguments found argument \'" + nameTok->str() + "\' with varid 0."); } else endTok = typeTok; } else endTok = tok->previous(); } const ::Type *argType = nullptr; if (!typeTok->isStandardType()) { argType = findVariableTypeIncludingUsedNamespaces(symbolDatabase, scope, typeTok); // save type const_cast<Token *>(typeTok)->type(argType); } // skip default values if (tok->str() == "=") { do { if (tok->link() && Token::Match(tok, "[{[(<]")) tok = tok->link(); tok = tok->next(); } while (tok->str() != "," && tok->str() != ")"); } // skip over stuff before type while (Token::Match(startTok, "enum|struct|const|volatile")) startTok = startTok->next(); if (startTok == nameTok) break; argumentList.emplace_back(nameTok, startTok, endTok, count++, AccessControl::Argument, argType, functionScope, symbolDatabase->mSettings); if (tok->str() == ")") { // check for a variadic function or a variadic template function if (Token::simpleMatch(endTok, "...")) isVariadic(true); break; } } // count default arguments for (const Token* tok = argDef->next(); tok && tok != argDef->link(); tok = tok->next()) { if (tok->str() == "=") { initArgCount++; if (tok->strAt(1) == "[") { const Token* lambdaStart = tok->next(); if (type == eLambda) tok = findLambdaEndTokenWithoutAST(lambdaStart); else { tok = findLambdaEndToken(lambdaStart); if (!tok) tok = findLambdaEndTokenWithoutAST(lambdaStart); } if (!tok) throw InternalError(lambdaStart, "Analysis failed (lambda not recognized). If the code is valid then please report this failure.", InternalError::INTERNAL); } } } } bool Function::isImplicitlyVirtual(bool defaultVal) const { if (hasVirtualSpecifier() || hasOverrideSpecifier() || hasFinalSpecifier()) return true; bool foundAllBaseClasses = true; if (getOverriddenFunction(&foundAllBaseClasses)) //If it overrides a base class's method then it's virtual return true; if (foundAllBaseClasses) //If we've seen all the base classes and none of the above were true then it must not be virtual return false; return defaultVal; //If we can't see all the bases classes then we can't say conclusively } std::vector<const Function*> Function::getOverloadedFunctions() const { std::vector<const Function*> result; const Scope* scope = nestedIn; while (scope) { const bool isMemberFunction = scope->isClassOrStruct() && !isStatic(); for (std::multimap<std::string, const Function*>::const_iterator it = scope->functionMap.find(tokenDef->str()); it != scope->functionMap.end() && it->first == tokenDef->str(); ++it) { const Function* func = it->second; if (isMemberFunction && isMemberFunction == func->isStatic()) continue; result.push_back(func); } if (isMemberFunction) break; scope = scope->nestedIn; } return result; } const Function *Function::getOverriddenFunction(bool *foundAllBaseClasses) const { if (foundAllBaseClasses) *foundAllBaseClasses = true; if (!nestedIn->isClassOrStruct()) return nullptr; return getOverriddenFunctionRecursive(nestedIn->definedType, foundAllBaseClasses); } // prevent recursion if base is the same except for different template parameters static bool isDerivedFromItself(const std::string& thisName, const std::string& baseName) { if (thisName.back() != '>') return false; const auto pos = thisName.find('<'); if (pos == std::string::npos) return false; return thisName.compare(0, pos + 1, baseName, 0, pos + 1) == 0; } const Function * Function::getOverriddenFunctionRecursive(const ::Type* baseType, bool *foundAllBaseClasses) const { // check each base class for (const ::Type::BaseInfo & i : baseType->derivedFrom) { const ::Type* derivedFromType = i.type; // check if base class exists in database if (!derivedFromType || !derivedFromType->classScope) { if (foundAllBaseClasses) *foundAllBaseClasses = false; continue; } const Scope *parent = derivedFromType->classScope; // check if function defined in base class auto range = parent->functionMap.equal_range(tokenDef->str()); for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) { const Function * func = it->second; if (func->isImplicitlyVirtual()) { // Base is virtual and of same name const Token *temp1 = func->tokenDef->previous(); const Token *temp2 = tokenDef->previous(); bool match = true; // check for matching return parameters while (!Token::Match(temp1, "virtual|public:|private:|protected:|{|}|;")) { if (temp1->str() != temp2->str() && !(temp1->type() && temp2->type() && temp2->type()->isDerivedFrom(temp1->type()->name()))) { match = false; break; } temp1 = temp1->previous(); temp2 = temp2->previous(); } // check for matching function parameters match = match && argsMatch(baseType->classScope, func->argDef, argDef, emptyString, 0); // check for matching cv-ref qualifiers match = match && isConst() == func->isConst() && isVolatile() == func->isVolatile() && hasRvalRefQualifier() == func->hasRvalRefQualifier() && hasLvalRefQualifier() == func->hasLvalRefQualifier(); // it's a match if (match) { return func; } } } if (isDestructor()) { auto it = std::find_if(parent->functionList.begin(), parent->functionList.end(), [](const Function& f) { return f.isDestructor() && f.isImplicitlyVirtual(); }); if (it != parent->functionList.end()) return &*it; } if (!derivedFromType->derivedFrom.empty() && !derivedFromType->hasCircularDependencies() && !isDerivedFromItself(baseType->classScope->className, i.name)) { // avoid endless recursion, see #5289 Crash: Stack overflow in isImplicitlyVirtual_rec when checking SVN and // #5590 with a loop within the class hierarchy. const Function *func = getOverriddenFunctionRecursive(derivedFromType, foundAllBaseClasses); if (func) { return func; } } } return nullptr; } const Variable* Function::getArgumentVar(nonneg int num) const { if (num < argumentList.size()) { auto it = argumentList.begin(); std::advance(it, num); return &*it; } return nullptr; } //--------------------------------------------------------------------------- Scope::Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_, ScopeType type_, const Token *start_) : check(check_), classDef(classDef_), nestedIn(nestedIn_), type(type_) { setBodyStartEnd(start_); } Scope::Scope(const SymbolDatabase *check_, const Token *classDef_, const Scope *nestedIn_) : check(check_), classDef(classDef_), nestedIn(nestedIn_) { const Token *nameTok = classDef; if (!classDef) { type = Scope::eGlobal; } else if (classDef->str() == "class" && classDef->isCpp()) { type = Scope::eClass; nameTok = nameTok->next(); } else if (classDef->str() == "struct") { type = Scope::eStruct; nameTok = nameTok->next(); } else if (classDef->str() == "union") { type = Scope::eUnion; nameTok = nameTok->next(); } else if (classDef->str() == "namespace") { type = Scope::eNamespace; nameTok = nameTok->next(); } else if (classDef->str() == "enum") { type = Scope::eEnum; nameTok = nameTok->next(); if (nameTok->str() == "class") { enumClass = true; nameTok = nameTok->next(); } } else if (classDef->str() == "[") { type = Scope::eLambda; } else { type = Scope::eFunction; } // skip over qualification if present nameTok = skipScopeIdentifiers(nameTok); if (nameTok && ((type == Scope::eEnum && Token::Match(nameTok, ":|{")) || nameTok->str() != "{")) // anonymous and unnamed structs/unions don't have a name className = nameTok->str(); } AccessControl Scope::defaultAccess() const { switch (type) { case eGlobal: return AccessControl::Global; case eClass: return AccessControl::Private; case eStruct: return AccessControl::Public; case eUnion: return AccessControl::Public; case eNamespace: return AccessControl::Namespace; default: return AccessControl::Local; } } void Scope::addVariable(const Token *token_, const Token *start_, const Token *end_, AccessControl access_, const Type *type_, const Scope *scope_, const Settings& settings) { // keep possible size_t -> int truncation outside emplace_back() to have a single line // C4267 VC++ warning instead of several dozens lines const int varIndex = varlist.size(); varlist.emplace_back(token_, start_, end_, varIndex, access_, type_, scope_, settings); } // Get variable list.. void Scope::getVariableList(const Settings& settings) { if (!bodyStartList.empty()) { for (const Token *bs: bodyStartList) getVariableList(settings, bs->next(), bs->link()); } // global scope else if (type == Scope::eGlobal) getVariableList(settings, check->mTokenizer.tokens(), nullptr); // forward declaration else return; } void Scope::getVariableList(const Settings& settings, const Token* start, const Token* end) { // Variable declared in condition: if (auto x = bar()) if (Token::Match(classDef, "if|while ( %type%") && Token::simpleMatch(classDef->next()->astOperand2(), "=")) { checkVariable(classDef->tokAt(2), defaultAccess(), settings); } AccessControl varaccess = defaultAccess(); for (const Token *tok = start; tok && tok != end; tok = tok->next()) { // syntax error? if (tok->next() == nullptr) break; // Is it a function? if (tok->str() == "{") { tok = tok->link(); continue; } // Is it a nested class or structure? if (tok->isKeyword() && Token::Match(tok, "class|struct|union|namespace %type% :|{")) { tok = tok->tokAt(2); while (tok && tok->str() != "{") tok = tok->next(); if (tok) { // skip implementation tok = tok->link(); continue; } break; } if (tok->isKeyword() && Token::Match(tok, "struct|union {")) { if (Token::Match(tok->linkAt(1), "} %name% ;|[")) { tok = tok->linkAt(1)->tokAt(2); continue; } if (Token::simpleMatch(tok->linkAt(1), "} ;")) { tok = tok->next(); continue; } } // Borland C++: Skip all variables in the __published section. // These are automatically initialized. else if (tok->str() == "__published:") { for (; tok; tok = tok->next()) { if (tok->str() == "{") tok = tok->link(); if (Token::Match(tok->next(), "private:|protected:|public:")) break; } if (tok) continue; break; } // "private:" "public:" "protected:" etc else if (tok->str() == "public:") { varaccess = AccessControl::Public; continue; } else if (tok->str() == "protected:") { varaccess = AccessControl::Protected; continue; } else if (tok->str() == "private:") { varaccess = AccessControl::Private; continue; } // Is it a forward declaration? else if (tok->isKeyword() && Token::Match(tok, "class|struct|union %name% ;")) { tok = tok->tokAt(2); continue; } // Borland C++: Ignore properties.. else if (tok->str() == "__property") continue; // skip return, goto and delete else if (tok->isKeyword() && Token::Match(tok, "return|delete|goto")) { while (tok->next() && tok->strAt(1) != ";" && tok->strAt(1) != "}" /* ticket #4994 */) { tok = tok->next(); } continue; } // skip case/default if (tok->isKeyword() && Token::Match(tok, "case|default")) { while (tok->next() && !Token::Match(tok->next(), "[:;{}]")) tok = tok->next(); continue; } // Search for start of statement.. if (tok->previous() && !Token::Match(tok->previous(), ";|{|}|public:|protected:|private:")) continue; if (tok->str() == ";") continue; tok = checkVariable(tok, varaccess, settings); if (!tok) break; } } const Token *Scope::checkVariable(const Token *tok, AccessControl varaccess, const Settings& settings) { // Is it a throw..? if (tok->isKeyword() && Token::Match(tok, "throw %any% (") && Token::simpleMatch(tok->linkAt(2), ") ;")) { return tok->linkAt(2); } if (tok->isKeyword() && Token::Match(tok, "throw %any% :: %any% (") && Token::simpleMatch(tok->linkAt(4), ") ;")) { return tok->linkAt(4); } // friend? if (tok->isKeyword() && Token::Match(tok, "friend %type%") && tok->next()->varId() == 0) { const Token *next = Token::findmatch(tok->tokAt(2), ";|{"); if (next && next->str() == "{") next = next->link(); return next; } // skip const|volatile|static|mutable|extern while (tok && tok->isKeyword() && Token::Match(tok, "const|constexpr|volatile|static|mutable|extern")) { tok = tok->next(); } // the start of the type tokens does not include the above modifiers const Token *typestart = tok; // C++17 structured bindings if (tok && tok->isCpp() && (settings.standards.cpp >= Standards::CPP17) && Token::Match(tok, "auto &|&&| [")) { const Token *typeend = Token::findsimplematch(typestart, "[")->previous(); for (tok = typeend->tokAt(2); Token::Match(tok, "%name%|,"); tok = tok->next()) { if (tok->varId()) addVariable(tok, typestart, typeend, varaccess, nullptr, this, settings); } return typeend->linkAt(1); } while (tok && tok->isKeyword() && Token::Match(tok, "class|struct|union|enum")) { tok = tok->next(); } // This is the start of a statement const Token *vartok = nullptr; const Token *typetok = nullptr; if (tok && isVariableDeclaration(tok, vartok, typetok)) { // If the vartok was set in the if-blocks above, create a entry for this variable.. tok = vartok->next(); while (Token::Match(tok, "[|{")) tok = tok->link()->next(); if (vartok->varId() == 0) { if (!vartok->isBoolean()) check->debugMessage(vartok, "varid0", "Scope::checkVariable found variable \'" + vartok->str() + "\' with varid 0."); return tok; } const Type *vType = nullptr; if (typetok) { vType = findVariableTypeIncludingUsedNamespaces(check, this, typetok); const_cast<Token *>(typetok)->type(vType); } // skip "enum" or "struct" if (Token::Match(typestart, "enum|struct")) typestart = typestart->next(); addVariable(vartok, typestart, vartok->previous(), varaccess, vType, this, settings); } return tok; } const Variable *Scope::getVariable(const std::string &varname) const { auto it = std::find_if(varlist.begin(), varlist.end(), [&varname](const Variable& var) { return var.name() == varname; }); if (it != varlist.end()) return &*it; if (definedType) { for (const Type::BaseInfo& baseInfo: definedType->derivedFrom) { if (baseInfo.type && baseInfo.type->classScope) { if (const Variable* var = baseInfo.type->classScope->getVariable(varname)) return var; } } } return nullptr; } static const Token* skipPointers(const Token* tok) { while (Token::Match(tok, "*|&|&&") || (Token::Match(tok, "( [*&]") && Token::Match(tok->link()->next(), "(|["))) { tok = tok->next(); if (tok && tok->strAt(-1) == "(" && Token::Match(tok, "%type% ::")) tok = tok->tokAt(2); } if (Token::simpleMatch(tok, "( *") && Token::simpleMatch(tok->link()->previous(), "] ) ;")) { const Token *tok2 = skipPointers(tok->next()); if (Token::Match(tok2, "%name% [") && Token::simpleMatch(tok2->linkAt(1), "] ) ;")) return tok2; } return tok; } static const Token* skipPointersAndQualifiers(const Token* tok) { tok = skipPointers(tok); while (Token::Match(tok, "const|static|volatile")) { tok = tok->next(); tok = skipPointers(tok); } return tok; } bool Scope::isVariableDeclaration(const Token* const tok, const Token*& vartok, const Token*& typetok) const { if (!tok) return false; const bool isCPP = tok->isCpp(); if (isCPP && Token::Match(tok, "throw|new")) return false; const bool isCPP11 = isCPP && check->mSettings.standards.cpp >= Standards::CPP11; if (isCPP11 && tok->str() == "using") return false; const Token* localTypeTok = skipScopeIdentifiers(tok); const Token* localVarTok = nullptr; while (Token::simpleMatch(localTypeTok, "alignas (") && Token::Match(localTypeTok->linkAt(1), ") %name%")) localTypeTok = localTypeTok->linkAt(1)->next(); if (Token::Match(localTypeTok, "%type% <")) { if (Token::Match(tok, "const_cast|dynamic_cast|reinterpret_cast|static_cast <")) return false; const Token* closeTok = localTypeTok->linkAt(1); if (closeTok) { localVarTok = skipPointers(closeTok->next()); if (Token::Match(localVarTok, ":: %type% %name% [;=({]")) { if (localVarTok->strAt(3) != "(" || Token::Match(localVarTok->linkAt(3), "[)}] ;")) { localTypeTok = localVarTok->next(); localVarTok = localVarTok->tokAt(2); } } } } else if (Token::Match(localTypeTok, "%type%")) { if (isCPP11 && Token::simpleMatch(localTypeTok, "decltype (") && Token::Match(localTypeTok->linkAt(1), ") %name%|*|&|&&")) localVarTok = skipPointersAndQualifiers(localTypeTok->linkAt(1)->next()); else { localVarTok = skipPointersAndQualifiers(localTypeTok->next()); if (isCPP11 && Token::simpleMatch(localVarTok, "decltype (") && Token::Match(localVarTok->linkAt(1), ") %name%|*|&|&&")) localVarTok = skipPointersAndQualifiers(localVarTok->linkAt(1)->next()); } } if (!localVarTok) return false; while (Token::Match(localVarTok, "const|*|&")) localVarTok = localVarTok->next(); if (Token::Match(localVarTok, "%name% ;|=") || (localVarTok && localVarTok->varId() && localVarTok->strAt(1) == ":")) { vartok = localVarTok; typetok = localTypeTok; } else if (Token::Match(localVarTok, "%name% )|[") && localVarTok->str() != "operator") { vartok = localVarTok; typetok = localTypeTok; } else if (localVarTok && localVarTok->varId() && Token::Match(localVarTok, "%name% (|{") && Token::Match(localVarTok->linkAt(1), ")|} ;")) { vartok = localVarTok; typetok = localTypeTok; } else if (type == eCatch && Token::Match(localVarTok, "%name% )")) { vartok = localVarTok; typetok = localTypeTok; } return nullptr != vartok; } const Token * Scope::addEnum(const Token * tok) { const Token * tok2 = tok->next(); // skip over class if present if (tok2->isCpp() && tok2->str() == "class") tok2 = tok2->next(); // skip over name tok2 = tok2->next(); // save type if present if (tok2->str() == ":") { tok2 = tok2->next(); enumType = tok2; while (Token::Match(tok2, "%name%|::")) tok2 = tok2->next(); } // add enumerators if (tok2->str() == "{") { const Token * end = tok2->link(); tok2 = tok2->next(); while (Token::Match(tok2, "%name% =|,|}") || (Token::Match(tok2, "%name% (") && Token::Match(tok2->linkAt(1), ") ,|}"))) { Enumerator enumerator(this); // save enumerator name enumerator.name = tok2; // skip over name tok2 = tok2->next(); if (tok2->str() == "=") { // skip over "=" tok2 = tok2->next(); if (tok2->str() == "}") return nullptr; enumerator.start = tok2; while (!Token::Match(tok2, ",|}")) { if (tok2->link()) tok2 = tok2->link(); enumerator.end = tok2; tok2 = tok2->next(); } } else if (tok2->str() == "(") { // skip over unknown macro tok2 = tok2->link()->next(); } if (tok2->str() == ",") { enumeratorList.push_back(enumerator); tok2 = tok2->next(); } else if (tok2->str() == "}") { enumeratorList.push_back(enumerator); break; } } if (tok2 == end) { tok2 = tok2->next(); if (tok2 && tok2->str() != ";" && (tok2->isCpp() || tok2->str() != ")")) tok2 = nullptr; } else tok2 = nullptr; } else tok2 = nullptr; return tok2; } static const Scope* findEnumScopeInBase(const Scope* scope, const std::string& tokStr) { if (scope->definedType) { const std::vector<Type::BaseInfo>& derivedFrom = scope->definedType->derivedFrom; for (const Type::BaseInfo& i : derivedFrom) { const Type *derivedFromType = i.type; if (derivedFromType && derivedFromType->classScope) { if (const Scope* enumScope = derivedFromType->classScope->findRecordInNestedList(tokStr)) return enumScope; } } } return nullptr; } static const Enumerator* findEnumeratorInUsingList(const Scope* scope, const std::string& name) { for (const auto& u : scope->usingList) { if (!u.scope) continue; for (const Scope* nested : u.scope->nestedList) { if (nested->type != Scope::eEnum) continue; const Enumerator* e = nested->findEnumerator(name); if (e && !(e->scope && e->scope->enumClass)) return e; } } return nullptr; } const Enumerator * SymbolDatabase::findEnumerator(const Token * tok, std::set<std::string>& tokensThatAreNotEnumeratorValues) const { if (tok->isKeyword()) return nullptr; const std::string& tokStr = tok->str(); const Scope* scope = tok->scope(); // check for qualified name if (tok->strAt(-1) == "::") { // find first scope const Token *tok1 = tok; while (Token::Match(tok1->tokAt(-2), "%name% ::")) tok1 = tok1->tokAt(-2); if (tok1->strAt(-1) == "::") scope = &scopeList.front(); else { const Scope* temp = nullptr; if (scope) temp = scope->findRecordInNestedList(tok1->str()); // find first scope while (scope && scope->nestedIn) { if (!temp) temp = scope->nestedIn->findRecordInNestedList(tok1->str()); if (!temp && scope->functionOf) { temp = scope->functionOf->findRecordInNestedList(tok1->str()); const Scope* nested = scope->functionOf->nestedIn; while (!temp && nested) { temp = nested->findRecordInNestedList(tok1->str()); nested = nested->nestedIn; } } if (!temp) temp = findEnumScopeInBase(scope, tok1->str()); if (temp) { scope = temp; break; } scope = scope->nestedIn; } } if (scope) { tok1 = tok1->tokAt(2); while (scope && Token::Match(tok1, "%name% ::")) { scope = scope->findRecordInNestedList(tok1->str()); tok1 = tok1->tokAt(2); } if (scope) { const Enumerator * enumerator = scope->findEnumerator(tokStr); if (enumerator) // enum class return enumerator; // enum for (std::vector<Scope *>::const_iterator it = scope->nestedList.cbegin(), end = scope->nestedList.cend(); it != end; ++it) { enumerator = (*it)->findEnumerator(tokStr); if (enumerator && !(enumerator->scope && enumerator->scope->enumClass)) return enumerator; } } } } else { // unqualified name if (tokensThatAreNotEnumeratorValues.find(tokStr) != tokensThatAreNotEnumeratorValues.end()) return nullptr; if (tok->scope()->type == Scope::eGlobal) { const Token* astTop = tok->astTop(); if (Token::simpleMatch(astTop, ":") && Token::simpleMatch(astTop->astOperand1(), "(")) { // ctor init list const Token* ctor = astTop->astOperand1()->previous(); if (ctor && ctor->function() && ctor->function()->nestedIn) scope = ctor->function()->nestedIn; } } const Enumerator * enumerator = scope->findEnumerator(tokStr); if (!enumerator) enumerator = findEnumeratorInUsingList(scope, tokStr); if (enumerator && !(enumerator->scope && enumerator->scope->enumClass)) return enumerator; if (Token::simpleMatch(tok->astParent(), ".")) { const Token* varTok = tok->astParent()->astOperand1(); if (varTok && varTok->variable() && varTok->variable()->type() && varTok->variable()->type()->classScope) scope = varTok->variable()->type()->classScope; } else if (Token::simpleMatch(tok->astParent(), "[")) { const Token* varTok = tok->astParent()->previous(); if (varTok && varTok->variable() && varTok->variable()->scope() && Token::simpleMatch(tok->astParent()->astOperand1(), "::")) scope = varTok->variable()->scope(); } for (std::vector<Scope *>::const_iterator s = scope->nestedList.cbegin(); s != scope->nestedList.cend(); ++s) { enumerator = (*s)->findEnumerator(tokStr); if (enumerator && !(enumerator->scope && enumerator->scope->enumClass)) return enumerator; } if (scope->definedType) { const std::vector<Type::BaseInfo> & derivedFrom = scope->definedType->derivedFrom; for (const Type::BaseInfo & i : derivedFrom) { const Type *derivedFromType = i.type; if (derivedFromType && derivedFromType->classScope) { enumerator = derivedFromType->classScope->findEnumerator(tokStr); if (enumerator && !(enumerator->scope && enumerator->scope->enumClass)) return enumerator; } } } while (scope->nestedIn) { if (scope->type == Scope::eFunction && scope->functionOf) scope = scope->functionOf; else scope = scope->nestedIn; enumerator = scope->findEnumerator(tokStr); if (!enumerator) enumerator = findEnumeratorInUsingList(scope, tokStr); if (enumerator && !(enumerator->scope && enumerator->scope->enumClass)) return enumerator; for (std::vector<Scope*>::const_iterator s = scope->nestedList.cbegin(); s != scope->nestedList.cend(); ++s) { enumerator = (*s)->findEnumerator(tokStr); if (enumerator && !(enumerator->scope && enumerator->scope->enumClass)) return enumerator; if (tok->isCpp() && (*s)->type == Scope::eNamespace && Token::simpleMatch((*s)->classDef, "namespace {")) { for (const Scope* nested : (*s)->nestedList) { if (nested->type != Scope::eEnum) continue; enumerator = nested->findEnumerator(tokStr); if (enumerator && !(enumerator->scope && enumerator->scope->enumClass)) return enumerator; } } } } } tokensThatAreNotEnumeratorValues.insert(tokStr); return nullptr; } //--------------------------------------------------------------------------- const Type* SymbolDatabase::findVariableTypeInBase(const Scope* scope, const Token* typeTok) { if (scope && scope->definedType && !scope->definedType->derivedFrom.empty()) { const std::vector<Type::BaseInfo> &derivedFrom = scope->definedType->derivedFrom; for (const Type::BaseInfo & i : derivedFrom) { const Type *base = i.type; if (base && base->classScope) { if (base->classScope == scope) return nullptr; const Type * type = base->classScope->findType(typeTok->str()); if (type) return type; type = findVariableTypeInBase(base->classScope, typeTok); if (type) return type; } } } return nullptr; } //--------------------------------------------------------------------------- const Type* SymbolDatabase::findVariableType(const Scope *start, const Token *typeTok) const { const Scope *scope = start; // check if type does not have a namespace if (typeTok->strAt(-1) != "::" && typeTok->strAt(1) != "::") { // check if type same as scope if (start->isClassOrStruct() && typeTok->str() == start->className) return start->definedType; while (scope) { // look for type in this scope const Type * type = scope->findType(typeTok->str()); if (type) return type; // look for type in base classes if possible if (scope->isClassOrStruct()) { type = findVariableTypeInBase(scope, typeTok); if (type) return type; } // check if in member function class to see if it's present in class if (scope->type == Scope::eFunction && scope->functionOf) { const Scope *scope1 = scope->functionOf; type = scope1->findType(typeTok->str()); if (type) return type; type = findVariableTypeInBase(scope1, typeTok); if (type) return type; } scope = scope->nestedIn; } } // check for a qualified name and use it when given else if (typeTok->strAt(-1) == "::") { // check if type is not part of qualification if (typeTok->strAt(1) == "::") return nullptr; // find start of qualified function name const Token *tok1 = typeTok; while ((Token::Match(tok1->tokAt(-2), "%type% ::") && !tok1->tokAt(-2)->isKeyword()) || (Token::simpleMatch(tok1->tokAt(-2), "> ::") && tok1->linkAt(-2) && Token::Match(tok1->linkAt(-2)->tokAt(-1), "%type%"))) { if (tok1->strAt(-1) == "::") tok1 = tok1->tokAt(-2); else tok1 = tok1->linkAt(-2)->tokAt(-1); } // check for global scope if (tok1->strAt(-1) == "::") { scope = &scopeList.front(); scope = scope->findRecordInNestedList(tok1->str()); } // find start of qualification else { while (scope) { if (scope->className == tok1->str()) break; const Scope *scope1 = scope->findRecordInNestedList(tok1->str()); if (scope1) { scope = scope1; break; } if (scope->type == Scope::eFunction && scope->functionOf) scope = scope->functionOf; else scope = scope->nestedIn; } } if (scope) { // follow qualification while (scope && (Token::Match(tok1, "%type% ::") || (Token::Match(tok1, "%type% <") && Token::simpleMatch(tok1->linkAt(1), "> ::")))) { if (tok1->strAt(1) == "::") tok1 = tok1->tokAt(2); else tok1 = tok1->linkAt(1)->tokAt(2); const Scope * temp = scope->findRecordInNestedList(tok1->str()); if (!temp) { // look in base classes const Type * type = findVariableTypeInBase(scope, tok1); if (type) return type; } scope = temp; } if (scope && scope->definedType) return scope->definedType; } } return nullptr; } static bool hasEmptyCaptureList(const Token* tok) { if (!Token::simpleMatch(tok, "{")) return false; const Token* listTok = tok->astParent(); if (Token::simpleMatch(listTok, "(")) listTok = listTok->astParent(); return Token::simpleMatch(listTok, "[ ]"); } bool Scope::hasInlineOrLambdaFunction(const Token** tokStart) const { return std::any_of(nestedList.begin(), nestedList.end(), [&](const Scope* s) { // Inline function if (s->type == Scope::eUnconditional && Token::simpleMatch(s->bodyStart->previous(), ") {")) { if (tokStart) *tokStart = nullptr; // bailout for e.g. loop-like macros return true; } // Lambda function if (s->type == Scope::eLambda && !hasEmptyCaptureList(s->bodyStart)) { if (tokStart) *tokStart = s->bodyStart; return true; } if (s->hasInlineOrLambdaFunction(tokStart)) return true; return false; }); } void Scope::findFunctionInBase(const std::string & name, nonneg int args, std::vector<const Function *> & matches) const { if (isClassOrStruct() && definedType && !definedType->derivedFrom.empty()) { const std::vector<Type::BaseInfo> &derivedFrom = definedType->derivedFrom; for (const Type::BaseInfo & i : derivedFrom) { const Type *base = i.type; if (base && base->classScope) { if (base->classScope == this) // Ticket #5120, #5125: Recursive class; tok should have been found already continue; auto range = base->classScope->functionMap.equal_range(name); for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) { const Function *func = it->second; if ((func->isVariadic() && args >= (func->argCount() - 1)) || (args == func->argCount() || (args < func->argCount() && args >= func->minArgCount()))) { matches.push_back(func); } } base->classScope->findFunctionInBase(name, args, matches); } } } } const Scope *Scope::findRecordInBase(const std::string & name) const { if (isClassOrStruct() && definedType && !definedType->derivedFrom.empty()) { const std::vector<Type::BaseInfo> &derivedFrom = definedType->derivedFrom; for (const Type::BaseInfo & i : derivedFrom) { const Type *base = i.type; if (base && base->classScope) { if (base->classScope == this) // Recursive class; tok should have been found already continue; if (base->name() == name) { return base->classScope; } const ::Type * t = base->classScope->findType(name); if (t) return t->classScope; } } } return nullptr; } std::vector<const Scope*> Scope::findAssociatedScopes() const { std::vector<const Scope*> result = {this}; if (isClassOrStruct() && definedType && !definedType->derivedFrom.empty()) { const std::vector<Type::BaseInfo>& derivedFrom = definedType->derivedFrom; for (const Type::BaseInfo& i : derivedFrom) { const Type* base = i.type; if (base && base->classScope) { if (contains(result, base->classScope)) continue; std::vector<const Scope*> baseScopes = base->classScope->findAssociatedScopes(); result.insert(result.end(), baseScopes.cbegin(), baseScopes.cend()); } } } return result; } //--------------------------------------------------------------------------- static void checkVariableCallMatch(const Variable* callarg, const Variable* funcarg, size_t& same, size_t& fallback1, size_t& fallback2) { if (callarg) { const ValueType::MatchResult res = ValueType::matchParameter(callarg->valueType(), callarg, funcarg); if (res == ValueType::MatchResult::SAME) { same++; return; } if (res == ValueType::MatchResult::FALLBACK1) { fallback1++; return; } if (res == ValueType::MatchResult::FALLBACK2) { fallback2++; return; } if (res == ValueType::MatchResult::NOMATCH) return; const bool ptrequals = callarg->isArrayOrPointer() == funcarg->isArrayOrPointer(); const bool constEquals = !callarg->isArrayOrPointer() || ((callarg->typeStartToken()->strAt(-1) == "const") == (funcarg->typeStartToken()->strAt(-1) == "const")); if (ptrequals && constEquals && callarg->typeStartToken()->str() == funcarg->typeStartToken()->str() && callarg->typeStartToken()->isUnsigned() == funcarg->typeStartToken()->isUnsigned() && callarg->typeStartToken()->isLong() == funcarg->typeStartToken()->isLong()) { same++; } else if (callarg->isArrayOrPointer()) { if (ptrequals && constEquals && funcarg->typeStartToken()->str() == "void") fallback1++; else if (constEquals && funcarg->isStlStringType() && Token::Match(callarg->typeStartToken(), "char|wchar_t")) fallback2++; } else if (ptrequals) { const bool takesInt = Token::Match(funcarg->typeStartToken(), "char|short|int|long"); const bool takesFloat = Token::Match(funcarg->typeStartToken(), "float|double"); const bool passesInt = Token::Match(callarg->typeStartToken(), "char|short|int|long"); const bool passesFloat = Token::Match(callarg->typeStartToken(), "float|double"); if ((takesInt && passesInt) || (takesFloat && passesFloat)) fallback1++; else if ((takesInt && passesFloat) || (takesFloat && passesInt)) fallback2++; } } } static std::string getTypeString(const Token *typeToken) { if (!typeToken) return ""; while (Token::Match(typeToken, "%name%|*|&|::")) { if (typeToken->str() == "::") { std::string ret; while (Token::Match(typeToken, ":: %name%")) { ret += "::" + typeToken->strAt(1); typeToken = typeToken->tokAt(2); if (typeToken->str() == "<") { for (const Token *tok = typeToken; tok != typeToken->link(); tok = tok->next()) ret += tok->str(); ret += ">"; typeToken = typeToken->link()->next(); } } return ret; } if (Token::Match(typeToken, "%name% const| %var%|*|&")) { return typeToken->str(); } typeToken = typeToken->next(); } return ""; } static bool hasMatchingConstructor(const Scope* classScope, const ValueType* argType) { if (!classScope || !argType) return false; return std::any_of(classScope->functionList.cbegin(), classScope->functionList.cend(), [&](const Function& f) { if (!f.isConstructor() || f.argCount() != 1 || !f.getArgumentVar(0)) return false; const ValueType* vt = f.getArgumentVar(0)->valueType(); return vt && vt->type == argType->type && (argType->sign == ValueType::Sign::UNKNOWN_SIGN || vt->sign == argType->sign) && vt->pointer == argType->pointer && (vt->constness & 1) >= (argType->constness & 1) && (vt->volatileness & 1) >= (argType->volatileness & 1); }); } const Function* Scope::findFunction(const Token *tok, bool requireConst, Reference ref) const { const bool isCall = Token::Match(tok->next(), "(|{"); const std::vector<const Token *> arguments = getArguments(tok); std::vector<const Function *> matches; // find all the possible functions that could match const std::size_t args = arguments.size(); auto addMatchingFunctions = [&](const Scope *scope) { auto range = scope->functionMap.equal_range(tok->str()); for (std::multimap<std::string, const Function *>::const_iterator it = range.first; it != range.second; ++it) { const Function *func = it->second; if (ref == Reference::LValue && func->hasRvalRefQualifier()) continue; if (func->isDestructor() && !Token::simpleMatch(tok->tokAt(-1), "~")) continue; if (!isCall || args == func->argCount() || (func->isVariadic() && args >= (func->minArgCount() - 1)) || (args < func->argCount() && args >= func->minArgCount())) { matches.push_back(func); } } }; addMatchingFunctions(this); // check in anonymous namespaces for (const Scope *nestedScope : nestedList) { if (nestedScope->type == eNamespace && nestedScope->className.empty()) addMatchingFunctions(nestedScope); } const std::size_t numberOfMatchesNonBase = matches.size(); // check in base classes findFunctionInBase(tok->str(), args, matches); // Non-call => Do not match parameters if (!isCall) { return matches.empty() ? nullptr : matches[0]; } std::vector<const Function*> fallback1Func, fallback2Func; // check each function against the arguments in the function call for a match for (std::size_t i = 0; i < matches.size();) { if (i > 0 && i == numberOfMatchesNonBase && fallback1Func.empty() && !fallback2Func.empty()) break; bool constFallback = false; const Function * func = matches[i]; size_t same = 0; if (requireConst && !func->isConst()) { i++; continue; } if (!requireConst || !func->isConst()) { // get the function this call is in const Scope * scope = tok->scope(); // check if this function is a member function if (scope && scope->functionOf && scope->functionOf->isClassOrStruct() && scope->function && func->nestedIn == scope->functionOf) { // check if isConst mismatches if (scope->function->isConst() != func->isConst()) { if (scope->function->isConst()) { ++i; continue; } constFallback = true; } } } size_t fallback1 = 0; size_t fallback2 = 0; bool erased = false; for (std::size_t j = 0; j < args; ++j) { // don't check variadic arguments if (func->isVariadic() && j > (func->argCount() - 1)) { break; } const Variable *funcarg = func->getArgumentVar(j); if (!arguments[j]->valueType()) { const Token *vartok = arguments[j]; int pointer = 0; while (vartok && (vartok->isUnaryOp("&") || vartok->isUnaryOp("*"))) { pointer += vartok->isUnaryOp("&") ? 1 : -1; vartok = vartok->astOperand1(); } if (vartok && vartok->variable()) { const Token *callArgTypeToken = vartok->variable()->typeStartToken(); const Token *funcArgTypeToken = funcarg->typeStartToken(); auto parseDecl = [](const Token *typeToken) -> ValueType { ValueType ret; while (Token::Match(typeToken->previous(), "%name%")) typeToken = typeToken->previous(); while (Token::Match(typeToken, "%name%|*|&|::|<")) { if (typeToken->str() == "const") ret.constness |= (1 << ret.pointer); else if (typeToken->str() == "volatile") ret.volatileness |= (1 << ret.pointer); else if (typeToken->str() == "*") ret.pointer++; else if (typeToken->str() == "<") { if (!typeToken->link()) break; typeToken = typeToken->link(); } typeToken = typeToken->next(); } return ret; }; const std::string type1 = getTypeString(callArgTypeToken); const std::string type2 = getTypeString(funcArgTypeToken); if (!type1.empty() && type1 == type2) { ValueType callArgType = parseDecl(callArgTypeToken); callArgType.pointer += pointer; ValueType funcArgType = parseDecl(funcArgTypeToken); callArgType.sign = funcArgType.sign = ValueType::Sign::SIGNED; callArgType.type = funcArgType.type = ValueType::Type::INT; const ValueType::MatchResult res = ValueType::matchParameter(&callArgType, &funcArgType); if (res == ValueType::MatchResult::SAME) ++same; else if (res == ValueType::MatchResult::FALLBACK1) ++fallback1; else if (res == ValueType::MatchResult::FALLBACK2) ++fallback2; continue; } } } // check for a match with a variable if (Token::Match(arguments[j], "%var% ,|)")) { const Variable * callarg = arguments[j]->variable(); checkVariableCallMatch(callarg, funcarg, same, fallback1, fallback2); } else if (funcarg->isStlStringType() && arguments[j]->valueType() && arguments[j]->valueType()->pointer == 1 && arguments[j]->valueType()->type == ValueType::Type::CHAR) fallback2++; // check for a match with nullptr else if (funcarg->isPointer() && Token::Match(arguments[j], "nullptr|NULL ,|)")) same++; else if (funcarg->isPointer() && MathLib::isNullValue(arguments[j]->str())) fallback1++; else if (!funcarg->isPointer() && funcarg->type() && hasMatchingConstructor(funcarg->type()->classScope, arguments[j]->valueType())) fallback2++; // Try to evaluate the apparently more complex expression else if (arguments[j]->isCpp()) { const Token *vartok = arguments[j]; if (vartok->str() == ".") { const Token* rml = nextAfterAstRightmostLeaf(vartok); if (rml) vartok = rml->previous(); } while (vartok->isUnaryOp("&") || vartok->isUnaryOp("*")) vartok = vartok->astOperand1(); const Variable* var = vartok->variable(); // smart pointer deref? bool unknownDeref = false; if (var && vartok->astParent() && vartok->astParent()->str() == "*") { if (var->isSmartPointer() && var->valueType() && var->valueType()->smartPointerTypeToken) var = var->valueType()->smartPointerTypeToken->variable(); else unknownDeref = true; } const Token* valuetok = arguments[j]; if (valuetok->str() == "::") { const Token* rml = nextAfterAstRightmostLeaf(valuetok); if (rml) valuetok = rml->previous(); } if (vartok->isEnumerator()) valuetok = vartok; const ValueType::MatchResult res = ValueType::matchParameter(valuetok->valueType(), var, funcarg); if (res == ValueType::MatchResult::SAME) ++same; else if (res == ValueType::MatchResult::FALLBACK1) ++fallback1; else if (res == ValueType::MatchResult::FALLBACK2) ++fallback2; else if (res == ValueType::MatchResult::NOMATCH) { if (unknownDeref) continue; // can't match so remove this function from possible matches matches.erase(matches.begin() + i); erased = true; break; } } else // C code: if number of arguments match then do not match types fallback1++; } const size_t hasToBe = func->isVariadic() ? (func->argCount() - 1) : args; // check if all arguments matched if (same == hasToBe) { if (constFallback || (!requireConst && func->isConst())) fallback1Func.emplace_back(func); else return func; } else { if (same + fallback1 == hasToBe) fallback1Func.emplace_back(func); else if (same + fallback2 + fallback1 == hasToBe) fallback2Func.emplace_back(func); } if (!erased) ++i; } // Fallback cases for (const auto& fb : { fallback1Func, fallback2Func }) { if (fb.size() == 1) return fb.front(); if (fb.size() == 2) { if (fb[0]->isConst() && !fb[1]->isConst()) return fb[1]; if (fb[1]->isConst() && !fb[0]->isConst()) return fb[0]; } } // remove pure virtual function if there is an overrider auto itPure = std::find_if(matches.begin(), matches.end(), [](const Function* m) { return m->isPure(); }); if (itPure != matches.end() && std::any_of(matches.begin(), matches.end(), [&](const Function* m) { return m->isImplicitlyVirtual() && m != *itPure; })) matches.erase(itPure); // Only one candidate left if (matches.size() == 1) return matches[0]; // Prioritize matches in derived scopes for (const auto& fb : { fallback1Func, fallback2Func }) { const Function* ret = nullptr; for (std::size_t i = 0; i < fb.size(); ++i) { if (std::find(matches.cbegin(), matches.cend(), fb[i]) == matches.cend()) continue; if (this == fb[i]->nestedIn) { if (!ret) ret = fb[i]; else { ret = nullptr; break; } } } if (ret) return ret; } return nullptr; } //--------------------------------------------------------------------------- const Function* SymbolDatabase::findFunction(const Token* const tok) const { // find the scope this function is in const Scope *currScope = tok->scope(); while (currScope && currScope->isExecutable()) { if (const Function* f = currScope->findFunction(tok)) { return f; } if (currScope->functionOf) currScope = currScope->functionOf; else currScope = currScope->nestedIn; } // check for a qualified name and use it when given if (tok->strAt(-1) == "::") { // find start of qualified function name const Token *tok1 = tok; while (Token::Match(tok1->tokAt(-2), ">|%type% ::")) { if (tok1->strAt(-2) == ">") { if (tok1->linkAt(-2)) tok1 = tok1->linkAt(-2)->tokAt(-1); else break; } else tok1 = tok1->tokAt(-2); } // check for global scope if (tok1->strAt(-1) == "::") { currScope = &scopeList.front(); if (const Function* f = currScope->findFunction(tok)) return f; currScope = currScope->findRecordInNestedList(tok1->str()); } // find start of qualification else { while (currScope) { if (currScope->className == tok1->str()) break; const Scope *scope = currScope->findRecordInNestedList(tok1->str()); if (scope) { currScope = scope; break; } currScope = currScope->nestedIn; } } if (currScope) { while (currScope && tok1 && !(Token::Match(tok1, "%type% :: %name% [(),>]") || (Token::Match(tok1, "%type% <") && Token::Match(tok1->linkAt(1), "> :: %name% (")))) { if (tok1->strAt(1) == "::") tok1 = tok1->tokAt(2); else if (tok1->strAt(1) == "<") tok1 = tok1->linkAt(1)->tokAt(2); else tok1 = nullptr; if (tok1) { const Function* func = currScope->findFunction(tok1); if (func) return func; currScope = currScope->findRecordInNestedList(tok1->str()); } } if (tok1) tok1 = tok1->tokAt(2); if (currScope && tok1) { const Function* func = currScope->findFunction(tok1); if (func) return func; } } } // check for member function else if (Token::Match(tok->tokAt(-2), "!!this .")) { const Token* tok1 = tok->previous()->astOperand1(); if (tok1 && tok1->valueType() && tok1->valueType()->typeScope) return tok1->valueType()->typeScope->findFunction(tok, tok1->valueType()->constness == 1, tok1->valueType()->reference); if (tok1 && Token::Match(tok1->previous(), "%name% (") && tok1->previous()->function() && tok1->previous()->function()->retDef) { ValueType vt = ValueType::parseDecl(tok1->previous()->function()->retDef, mSettings); if (vt.typeScope) return vt.typeScope->findFunction(tok, vt.constness == 1); } else if (Token::Match(tok1, "%var% .")) { const Variable *var = getVariableFromVarId(tok1->varId()); if (var && var->typeScope()) return var->typeScope()->findFunction(tok, var->valueType()->constness == 1); if (var && var->smartPointerType() && var->smartPointerType()->classScope && tok1->next()->originalName() == "->") return var->smartPointerType()->classScope->findFunction(tok, var->valueType()->constness == 1); if (var && var->iteratorType() && var->iteratorType()->classScope && tok1->next()->originalName() == "->") return var->iteratorType()->classScope->findFunction(tok, var->valueType()->constness == 1); } else if (Token::simpleMatch(tok->previous()->astOperand1(), "(")) { const Token *castTok = tok->previous()->astOperand1(); if (castTok->isCast()) { ValueType vt = ValueType::parseDecl(castTok->next(),mSettings); if (vt.typeScope) return vt.typeScope->findFunction(tok, vt.constness == 1); } } } // check in enclosing scopes else { while (currScope) { const Function *func = currScope->findFunction(tok); if (func) return func; currScope = currScope->nestedIn; } // check using namespace currScope = tok->scope(); while (currScope) { for (const auto& ul : currScope->usingList) { if (ul.scope) { const Function* func = ul.scope->findFunction(tok); if (func) return func; } } currScope = currScope->nestedIn; } } // Check for constructor if (Token::Match(tok, "%name% (|{")) { ValueType vt = ValueType::parseDecl(tok, mSettings); if (vt.typeScope) return vt.typeScope->findFunction(tok, false); } return nullptr; } //--------------------------------------------------------------------------- const Scope *SymbolDatabase::findScopeByName(const std::string& name) const { auto it = std::find_if(scopeList.cbegin(), scopeList.cend(), [&](const Scope& s) { return s.className == name; }); return it == scopeList.end() ? nullptr : &*it; } //--------------------------------------------------------------------------- template<class S, class T, REQUIRES("S must be a Scope class", std::is_convertible<S*, const Scope*> ), REQUIRES("T must be a Type class", std::is_convertible<T*, const Type*> )> static S* findRecordInNestedListImpl(S& thisScope, const std::string& name, bool isC, std::set<const Scope*>& visited) { for (S* scope: thisScope.nestedList) { if (scope->className == name && scope->type != Scope::eFunction) return scope; if (isC) { S* nestedScope = scope->findRecordInNestedList(name, isC); if (nestedScope) return nestedScope; } } for (const auto& u : thisScope.usingList) { if (!u.scope || u.scope == &thisScope || visited.find(u.scope) != visited.end()) continue; visited.emplace(u.scope); S* nestedScope = findRecordInNestedListImpl<S, T>(const_cast<S&>(*u.scope), name, false, visited); if (nestedScope) return nestedScope; } T * nested_type = thisScope.findType(name); if (nested_type) { if (nested_type->isTypeAlias()) { if (nested_type->typeStart == nested_type->typeEnd) return thisScope.findRecordInNestedList(nested_type->typeStart->str()); // TODO: pass isC? } else return const_cast<S*>(nested_type->classScope); } return nullptr; } const Scope* Scope::findRecordInNestedList(const std::string & name, bool isC) const { std::set<const Scope*> visited; return findRecordInNestedListImpl<const Scope, const Type>(*this, name, isC, visited); } Scope* Scope::findRecordInNestedList(const std::string & name, bool isC) { std::set<const Scope*> visited; return findRecordInNestedListImpl<Scope, Type>(*this, name, isC, visited); } //--------------------------------------------------------------------------- template<class S, class T, REQUIRES("S must be a Scope class", std::is_convertible<S*, const Scope*> ), REQUIRES("T must be a Type class", std::is_convertible<T*, const Type*> )> static T* findTypeImpl(S& thisScope, const std::string & name) { auto it = thisScope.definedTypesMap.find(name); // Type was found if (thisScope.definedTypesMap.end() != it) return it->second; // is type defined in anonymous namespace.. it = thisScope.definedTypesMap.find(emptyString); if (it != thisScope.definedTypesMap.end()) { for (S *scope : thisScope.nestedList) { if (scope->className.empty() && (scope->type == thisScope.eNamespace || scope->isClassOrStructOrUnion())) { T *t = scope->findType(name); if (t) return t; } } } // Type was not found return nullptr; } const Type* Scope::findType(const std::string& name) const { return findTypeImpl<const Scope, const Type>(*this, name); } Type* Scope::findType(const std::string& name) { return findTypeImpl<Scope, Type>(*this, name); } //--------------------------------------------------------------------------- Scope *Scope::findInNestedListRecursive(const std::string & name) { auto it = std::find_if(nestedList.cbegin(), nestedList.cend(), [&](const Scope* s) { return s->className == name; }); if (it != nestedList.end()) return *it; for (Scope* scope: nestedList) { Scope *child = scope->findInNestedListRecursive(name); if (child) return child; } return nullptr; } //--------------------------------------------------------------------------- const Function *Scope::getDestructor() const { auto it = std::find_if(functionList.cbegin(), functionList.cend(), [](const Function& f) { return f.type == Function::eDestructor; }); return it == functionList.end() ? nullptr : &*it; } //--------------------------------------------------------------------------- const Scope *SymbolDatabase::findScope(const Token *tok, const Scope *startScope) const { const Scope *scope = nullptr; // absolute path if (tok->str() == "::") { tok = tok->next(); scope = &scopeList.front(); } // relative path else if (tok->isName()) { scope = startScope; } while (scope && tok && tok->isName()) { if (tok->strAt(1) == "::") { scope = scope->findRecordInNestedList(tok->str()); tok = tok->tokAt(2); } else if (tok->strAt(1) == "<") return nullptr; else return scope->findRecordInNestedList(tok->str()); } // not a valid path return nullptr; } //--------------------------------------------------------------------------- const Type* SymbolDatabase::findType(const Token *startTok, const Scope *startScope, bool lookOutside) const { // skip over struct or union if (Token::Match(startTok, "struct|union")) startTok = startTok->next(); // type same as scope if (startTok->str() == startScope->className && startScope->isClassOrStruct() && startTok->strAt(1) != "::") return startScope->definedType; if (startTok->isC()) { const Scope* scope = startScope; while (scope) { if (startTok->str() == scope->className && scope->isClassOrStruct()) return scope->definedType; const Scope* typeScope = scope->findRecordInNestedList(startTok->str(), /*isC*/ true); if (typeScope) { if (startTok->str() == typeScope->className && typeScope->isClassOrStruct()) { if (const Type* type = typeScope->definedType) return type; } } scope = scope->nestedIn; } return nullptr; } const Scope* start_scope = startScope; // absolute path - directly start in global scope if (startTok->str() == "::") { startTok = startTok->next(); start_scope = &scopeList.front(); } const Token* tok = startTok; const Scope* scope = start_scope; while (scope && tok && tok->isName()) { if (tok->strAt(1) == "::" || (tok->strAt(1) == "<" && Token::simpleMatch(tok->linkAt(1), "> ::"))) { scope = scope->findRecordInNestedList(tok->str()); if (scope) { if (tok->strAt(1) == "::") tok = tok->tokAt(2); else tok = tok->linkAt(1)->tokAt(2); } else { start_scope = start_scope->nestedIn; if (!start_scope) break; scope = start_scope; tok = startTok; } } else { const Scope* scope1{}; const Type* type = scope->findType(tok->str()); if (type) return type; if (lookOutside && (scope1 = scope->findRecordInBase(tok->str()))) { type = scope1->definedType; if (type) return type; } else if (lookOutside && scope->type == Scope::ScopeType::eNamespace) { scope = scope->nestedIn; continue; } else break; } } // check using namespaces while (startScope) { for (std::vector<Scope::UsingInfo>::const_iterator it = startScope->usingList.cbegin(); it != startScope->usingList.cend(); ++it) { tok = startTok; scope = it->scope; start_scope = startScope; while (scope && tok && tok->isName()) { if (tok->strAt(1) == "::" || (tok->strAt(1) == "<" && Token::simpleMatch(tok->linkAt(1), "> ::"))) { scope = scope->findRecordInNestedList(tok->str()); if (scope) { if (tok->strAt(1) == "::") tok = tok->tokAt(2); else tok = tok->linkAt(1)->tokAt(2); } else { start_scope = start_scope->nestedIn; if (!start_scope) break; scope = start_scope; tok = startTok; } } else { const Type * type = scope->findType(tok->str()); if (type) return type; if (const Scope *scope1 = scope->findRecordInBase(tok->str())) { type = scope1->definedType; if (type) return type; } else break; } } } startScope = startScope->nestedIn; } // not a valid path return nullptr; } //--------------------------------------------------------------------------- const Type* SymbolDatabase::findTypeInNested(const Token *startTok, const Scope *startScope) const { // skip over struct or union if (Token::Match(startTok, "struct|union|enum")) startTok = startTok->next(); // type same as scope if (startScope->isClassOrStruct() && startTok->str() == startScope->className && !Token::simpleMatch(startTok->next(), "::")) return startScope->definedType; bool hasPath = false; // absolute path - directly start in global scope if (startTok->str() == "::") { hasPath = true; startTok = startTok->next(); startScope = &scopeList.front(); } const Token* tok = startTok; const Scope* scope = startScope; while (scope && tok && tok->isName()) { if (tok->strAt(1) == "::" || (tok->strAt(1) == "<" && Token::simpleMatch(tok->linkAt(1), "> ::"))) { hasPath = true; scope = scope->findRecordInNestedList(tok->str()); if (scope) { if (tok->strAt(1) == "::") tok = tok->tokAt(2); else tok = tok->linkAt(1)->tokAt(2); } else { startScope = startScope->nestedIn; if (!startScope) break; scope = startScope; tok = startTok; } } else { const Type * type = scope->findType(tok->str()); if (hasPath || type) return type; scope = scope->nestedIn; if (!scope) break; } } // not a valid path return nullptr; } //--------------------------------------------------------------------------- const Scope * SymbolDatabase::findNamespace(const Token * tok, const Scope * scope) const { const Scope * s = findScope(tok, scope); if (s) return s; if (scope->nestedIn) return findNamespace(tok, scope->nestedIn); return nullptr; } //--------------------------------------------------------------------------- Function * SymbolDatabase::findFunctionInScope(const Token *func, const Scope *ns, const std::string & path, nonneg int path_length) { const Function * function = nullptr; const bool destructor = func->strAt(-1) == "~"; auto range = ns->functionMap.equal_range(func->str()); for (std::multimap<std::string, const Function*>::const_iterator it = range.first; it != range.second; ++it) { if (it->second->argsMatch(ns, it->second->argDef, func->next(), path, path_length) && it->second->isDestructor() == destructor) { function = it->second; break; } } if (!function) { const Scope * scope = ns->findRecordInNestedList(func->str()); if (scope && Token::Match(func->tokAt(1), "::|<")) { if (func->strAt(1) == "::") func = func->tokAt(2); else if (func->linkAt(1)) func = func->linkAt(1)->tokAt(2); else return nullptr; if (func->str() == "~") func = func->next(); function = findFunctionInScope(func, scope, path, path_length); } } return const_cast<Function *>(function); } //--------------------------------------------------------------------------- bool SymbolDatabase::isReservedName(const Token* tok) { const std::string& iName = tok->str(); if (tok->isCpp()) { static const auto& cpp_keywords = Keywords::getAll(Standards::cppstd_t::CPPLatest); return cpp_keywords.find(iName) != cpp_keywords.cend(); } static const auto& c_keywords = Keywords::getAll(Standards::cstd_t::CLatest); return c_keywords.find(iName) != c_keywords.cend(); } nonneg int SymbolDatabase::sizeOfType(const Token *type) const { int size = mTokenizer.sizeOfType(type); if (size == 0 && type->type() && type->type()->isEnumType() && type->type()->classScope) { size = mSettings.platform.sizeof_int; const Token * enum_type = type->type()->classScope->enumType; if (enum_type) size = mTokenizer.sizeOfType(enum_type); } return size; } static const Token* parsedecl(const Token* type, ValueType* valuetype, ValueType::Sign defaultSignedness, const Settings& settings, SourceLocation loc = SourceLocation::current()); void SymbolDatabase::setValueType(Token* tok, const Variable& var, const SourceLocation &loc) { ValueType valuetype; if (mSettings.debugnormal || mSettings.debugwarnings) valuetype.setDebugPath(tok, loc); if (var.nameToken()) valuetype.bits = var.nameToken()->bits(); valuetype.pointer = var.dimensions().size(); // HACK: don't set pointer for plain std::array if (var.valueType() && var.valueType()->container && Token::simpleMatch(var.typeStartToken(), "std :: array") && !Token::simpleMatch(var.nameToken()->next(), "[")) valuetype.pointer = 0; valuetype.typeScope = var.typeScope(); if (var.valueType()) { valuetype.container = var.valueType()->container; valuetype.containerTypeToken = var.valueType()->containerTypeToken; } valuetype.smartPointerType = var.smartPointerType(); if (parsedecl(var.typeStartToken(), &valuetype, mDefaultSignedness, mSettings)) { if (tok->str() == "." && tok->astOperand1()) { const ValueType * const vt = tok->astOperand1()->valueType(); if (vt && (vt->constness & 1) != 0) valuetype.constness |= 1; if (vt && (vt->volatileness & 1) != 0) valuetype.volatileness |= 1; } setValueType(tok, valuetype); } } static ValueType::Type getEnumType(const Scope* scope, const Platform& platform); void SymbolDatabase::setValueType(Token* tok, const Enumerator& enumerator, const SourceLocation &loc) { ValueType valuetype; if (mSettings.debugnormal || mSettings.debugwarnings) valuetype.setDebugPath(tok, loc); valuetype.typeScope = enumerator.scope; const Token * type = enumerator.scope->enumType; if (type) { valuetype.type = ValueType::typeFromString(type->str(), type->isLong()); if (valuetype.type == ValueType::Type::UNKNOWN_TYPE && type->isStandardType()) valuetype.fromLibraryType(type->str(), mSettings); if (valuetype.isIntegral()) { if (type->isSigned()) valuetype.sign = ValueType::Sign::SIGNED; else if (type->isUnsigned()) valuetype.sign = ValueType::Sign::UNSIGNED; else if (valuetype.type == ValueType::Type::CHAR) valuetype.sign = mDefaultSignedness; else valuetype.sign = ValueType::Sign::SIGNED; } setValueType(tok, valuetype); } else { valuetype.sign = ValueType::SIGNED; valuetype.type = getEnumType(enumerator.scope, mSettings.platform); setValueType(tok, valuetype); } } static void setAutoTokenProperties(Token * const autoTok) { const ValueType *valuetype = autoTok->valueType(); if (valuetype->isIntegral() || valuetype->isFloat()) autoTok->isStandardType(true); } static bool isContainerYieldElement(Library::Container::Yield yield) { return yield == Library::Container::Yield::ITEM || yield == Library::Container::Yield::AT_INDEX || yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT; } static bool isContainerYieldPointer(Library::Container::Yield yield) { return yield == Library::Container::Yield::BUFFER || yield == Library::Container::Yield::BUFFER_NT; } void SymbolDatabase::setValueType(Token* tok, const ValueType& valuetype, const SourceLocation &loc) { auto* valuetypePtr = new ValueType(valuetype); if (mSettings.debugnormal || mSettings.debugwarnings) valuetypePtr->setDebugPath(tok, loc); tok->setValueType(valuetypePtr); Token *parent = tok->astParent(); if (!parent || parent->valueType()) return; if (!parent->astOperand1()) return; const ValueType *vt1 = parent->astOperand1()->valueType(); const ValueType *vt2 = parent->astOperand2() ? parent->astOperand2()->valueType() : nullptr; if (vt1 && Token::Match(parent, "<<|>>")) { if (!parent->isCpp() || (vt2 && vt2->isIntegral())) { if (vt1->type < ValueType::Type::BOOL || vt1->type >= ValueType::Type::INT) { ValueType vt(*vt1); vt.reference = Reference::None; setValueType(parent, vt); } else { ValueType vt(*vt1); vt.type = ValueType::Type::INT; // Integer promotion vt.sign = ValueType::Sign::SIGNED; vt.reference = Reference::None; setValueType(parent, vt); } } return; } if (vt1 && vt1->container && vt1->containerTypeToken && Token::Match(parent, ". %name% (") && isContainerYieldElement(vt1->container->getYield(parent->strAt(1)))) { ValueType item; if (parsedecl(vt1->containerTypeToken, &item, mDefaultSignedness, mSettings)) { if (item.constness == 0) item.constness = vt1->constness; if (item.volatileness == 0) item.volatileness = vt1->volatileness; if (isContainerYieldPointer(vt1->container->getYield(parent->strAt(1)))) item.pointer += 1; else item.reference = Reference::LValue; setValueType(parent->tokAt(2), item); } } if (vt1 && vt1->smartPointerType && Token::Match(parent, ". %name% (") && parent->originalName() == "->" && !parent->next()->function()) { const Scope *scope = vt1->smartPointerType->classScope; const Function *f = scope ? scope->findFunction(parent->next(), false) : nullptr; if (f) parent->next()->function(f); } if (parent->isAssignmentOp()) { if (vt1) { auto vt = *vt1; vt.reference = Reference::None; setValueType(parent, vt); } else if (parent->isCpp() && ((Token::Match(parent->tokAt(-3), "%var% ; %var% =") && parent->strAt(-3) == parent->strAt(-1)) || Token::Match(parent->tokAt(-1), "%var% ="))) { Token *var1Tok = parent->strAt(-2) == ";" ? parent->tokAt(-3) : parent->tokAt(-1); Token *autoTok = nullptr; if (Token::simpleMatch(var1Tok->tokAt(-1), "auto")) autoTok = var1Tok->previous(); else if (Token::Match(var1Tok->tokAt(-2), "auto *|&|&&")) autoTok = var1Tok->tokAt(-2); else if (Token::simpleMatch(var1Tok->tokAt(-3), "auto * const")) autoTok = var1Tok->tokAt(-3); if (autoTok) { ValueType vt(*vt2); if (vt.constness & (1 << vt.pointer)) vt.constness &= ~(1 << vt.pointer); if (vt.volatileness & (1 << vt.pointer)) vt.volatileness &= ~(1 << vt.pointer); if (autoTok->strAt(1) == "*" && vt.pointer) vt.pointer--; if (Token::Match(autoTok->tokAt(-1), "const|constexpr")) vt.constness |= (1 << vt.pointer); if (Token::simpleMatch(autoTok->tokAt(-1), "volatile")) vt.volatileness |= (1 << vt.pointer); setValueType(autoTok, vt); setAutoTokenProperties(autoTok); if (vt2->pointer > vt.pointer) vt.pointer++; setValueType(var1Tok, vt); if (var1Tok != parent->previous()) setValueType(parent->previous(), vt); auto *var = const_cast<Variable *>(parent->previous()->variable()); if (var) { ValueType vt2_(*vt2); if (vt2_.pointer == 0 && autoTok->strAt(1) == "*") vt2_.pointer = 1; if ((vt.constness & (1 << vt2->pointer)) != 0) vt2_.constness |= (1 << vt2->pointer); if ((vt.volatileness & (1 << vt2->pointer)) != 0) vt2_.volatileness |= (1 << vt2->pointer); if (!Token::Match(autoTok->tokAt(1), "*|&")) { vt2_.constness = vt.constness; vt2_.volatileness = vt.volatileness; } if (Token::simpleMatch(autoTok->tokAt(1), "* const")) vt2_.constness |= (1 << vt2->pointer); if (Token::simpleMatch(autoTok->tokAt(1), "* volatile")) vt2_.volatileness |= (1 << vt2->pointer); var->setValueType(vt2_); if (vt2->typeScope && vt2->typeScope->definedType) { var->type(vt2->typeScope->definedType); if (autoTok->valueType()->pointer == 0) autoTok->type(vt2->typeScope->definedType); } } } } return; } if (parent->str() == "[" && (!parent->isCpp() || parent->astOperand1() == tok) && valuetype.pointer > 0U && !Token::Match(parent->previous(), "[{,]")) { const Token *op1 = parent->astOperand1(); while (op1 && op1->str() == "[") op1 = op1->astOperand1(); ValueType vt(valuetype); // the "[" is a dereference unless this is a variable declaration if (!(op1 && op1->variable() && op1->variable()->nameToken() == op1)) vt.pointer -= 1U; setValueType(parent, vt); return; } if (Token::Match(parent->previous(), "%name% (") && parent->astOperand1() == tok && valuetype.pointer > 0U) { ValueType vt(valuetype); vt.pointer -= 1U; setValueType(parent, vt); return; } // std::move if (vt2 && parent->str() == "(" && Token::simpleMatch(parent->tokAt(-3), "std :: move (")) { ValueType vt = valuetype; vt.reference = Reference::RValue; setValueType(parent, vt); return; } if (parent->str() == "*" && !parent->astOperand2() && valuetype.pointer > 0U) { ValueType vt(valuetype); vt.pointer -= 1U; setValueType(parent, vt); return; } // Dereference iterator if (parent->str() == "*" && !parent->astOperand2() && valuetype.type == ValueType::Type::ITERATOR && valuetype.containerTypeToken) { ValueType vt; if (parsedecl(valuetype.containerTypeToken, &vt, mDefaultSignedness, mSettings)) { if (vt.constness == 0) vt.constness = valuetype.constness; if (vt.volatileness == 0) vt.volatileness = valuetype.volatileness; vt.reference = Reference::LValue; setValueType(parent, vt); return; } } // Dereference smart pointer if (parent->str() == "*" && !parent->astOperand2() && valuetype.type == ValueType::Type::SMART_POINTER && valuetype.smartPointerTypeToken) { ValueType vt; if (parsedecl(valuetype.smartPointerTypeToken, &vt, mDefaultSignedness, mSettings)) { if (vt.constness == 0) vt.constness = valuetype.constness; if (vt.volatileness == 0) vt.volatileness = valuetype.volatileness; setValueType(parent, vt); return; } } if (parent->str() == "*" && Token::simpleMatch(parent->astOperand2(), "[") && valuetype.pointer > 0U) { const Token *op1 = parent->astOperand2()->astOperand1(); while (op1 && op1->str() == "[") op1 = op1->astOperand1(); const ValueType& vt(valuetype); if (op1 && op1->variable() && op1->variable()->nameToken() == op1) { setValueType(parent, vt); return; } } if (parent->str() == "&" && !parent->astOperand2()) { ValueType vt(valuetype); vt.reference = Reference::None; //Given int& x; the type of &x is int* not int&* bool isArrayToPointerDecay = false; for (const Token* child = parent->astOperand1(); child;) { if (Token::Match(child, ".|::")) child = child->astOperand2(); else { isArrayToPointerDecay = child->variable() && child->variable()->isArray(); break; } } if (!isArrayToPointerDecay) vt.pointer += 1U; setValueType(parent, vt); return; } if ((parent->str() == "." || parent->str() == "::") && parent->astOperand2() && parent->astOperand2()->isName()) { const Variable* var = parent->astOperand2()->variable(); if (!var && valuetype.typeScope && vt1) { const std::string &name = parent->astOperand2()->str(); const Scope *typeScope = vt1->typeScope; if (!typeScope) return; auto it = std::find_if(typeScope->varlist.begin(), typeScope->varlist.end(), [&name](const Variable& v) { return v.nameToken()->str() == name; }); if (it != typeScope->varlist.end()) var = &*it; } if (var) { setValueType(parent, *var); return; } if (const Enumerator* enu = parent->astOperand2()->enumerator()) setValueType(parent, *enu); return; } // range for loop, auto if (vt2 && parent->str() == ":" && Token::Match(parent->astParent(), "( const| auto *|&|&&| %var% :") && // TODO: east-const, multiple const, ref to ptr !parent->previous()->valueType() && Token::simpleMatch(parent->astParent()->astOperand1(), "for")) { const bool isconst = Token::simpleMatch(parent->astParent()->next(), "const"); const bool isvolatile = Token::simpleMatch(parent->astParent()->next(), "volatile"); Token * const autoToken = parent->astParent()->tokAt(isconst ? 2 : 1); if (vt2->pointer) { ValueType autovt(*vt2); autovt.pointer--; autovt.constness = 0; autovt.volatileness = 0; setValueType(autoToken, autovt); setAutoTokenProperties(autoToken); ValueType varvt(*vt2); varvt.pointer--; if (Token::simpleMatch(autoToken->next(), "&")) varvt.reference = Reference::LValue; if (isconst) { if (varvt.pointer && varvt.reference != Reference::None) varvt.constness |= (1 << varvt.pointer); else varvt.constness |= 1; } if (isvolatile) { if (varvt.pointer && varvt.reference != Reference::None) varvt.volatileness |= (1 << varvt.pointer); else varvt.volatileness |= 1; } setValueType(parent->previous(), varvt); auto *var = const_cast<Variable *>(parent->previous()->variable()); if (var) { var->setValueType(varvt); if (vt2->typeScope && vt2->typeScope->definedType) { var->type(vt2->typeScope->definedType); autoToken->type(vt2->typeScope->definedType); } } } else if (vt2->container) { // TODO: Determine exact type of RHS const Token *typeStart = parent->astOperand2(); while (typeStart) { if (typeStart->variable()) typeStart = typeStart->variable()->typeStartToken(); else if (typeStart->str() == "(" && typeStart->previous() && typeStart->previous()->function()) typeStart = typeStart->previous()->function()->retDef; else break; } // Try to determine type of "auto" token. // TODO: Get type better bool setType = false; ValueType autovt; const Type *templateArgType = nullptr; // container element type / smart pointer type if (!vt2->container->rangeItemRecordType.empty()) { setType = true; autovt.type = ValueType::Type::RECORD; } else if (vt2->containerTypeToken) { if (mSettings.library.isSmartPointer(vt2->containerTypeToken)) { const Token *smartPointerTypeTok = vt2->containerTypeToken; while (Token::Match(smartPointerTypeTok, "%name%|::")) smartPointerTypeTok = smartPointerTypeTok->next(); if (Token::simpleMatch(smartPointerTypeTok, "<")) { if ((templateArgType = findTypeInNested(smartPointerTypeTok->next(), tok->scope()))) { setType = true; autovt.smartPointerType = templateArgType; autovt.type = ValueType::Type::NONSTD; } } } else if (parsedecl(vt2->containerTypeToken, &autovt, mDefaultSignedness, mSettings)) { setType = true; templateArgType = vt2->containerTypeToken->type(); if (Token::simpleMatch(autoToken->next(), "&")) autovt.reference = Reference::LValue; else if (Token::simpleMatch(autoToken->next(), "&&")) autovt.reference = Reference::RValue; if (autoToken->strAt(-1) == "const") { if (autovt.pointer && autovt.reference != Reference::None) autovt.constness |= 2; else autovt.constness |= 1; } if (autoToken->strAt(-1) == "volatile") { if (autovt.pointer && autovt.reference != Reference::None) autovt.volatileness |= 2; else autovt.volatileness |= 1; } } } if (setType) { // Type of "auto" has been determined.. set type information for "auto" and variable tokens setValueType(autoToken, autovt); setAutoTokenProperties(autoToken); ValueType varvt(autovt); if (autoToken->strAt(1) == "*" && autovt.pointer) autovt.pointer--; if (isconst) varvt.constness |= (1 << autovt.pointer); if (isvolatile) varvt.volatileness |= (1 << autovt.pointer); setValueType(parent->previous(), varvt); auto * var = const_cast<Variable *>(parent->previous()->variable()); if (var) { var->setValueType(varvt); if (templateArgType && templateArgType->classScope && templateArgType->classScope->definedType) { autoToken->type(templateArgType->classScope->definedType); var->type(templateArgType->classScope->definedType); } } } } } if (vt1 && vt1->containerTypeToken && parent->str() == "[") { ValueType vtParent; if (parsedecl(vt1->containerTypeToken, &vtParent, mDefaultSignedness, mSettings)) { setValueType(parent, vtParent); return; } } if (parent->isCpp() && vt2 && Token::simpleMatch(parent->previous(), "decltype (")) { setValueType(parent, *vt2); return; } // c++17 auto type deduction of braced init list if (parent->isCpp() && mSettings.standards.cpp >= Standards::CPP17 && vt2 && Token::Match(parent->tokAt(-2), "auto %var% {")) { Token *autoTok = parent->tokAt(-2); setValueType(autoTok, *vt2); setAutoTokenProperties(autoTok); if (parent->previous()->variable()) const_cast<Variable*>(parent->previous()->variable())->setValueType(*vt2); else debugMessage(parent->previous(), "debug", "Missing variable class for variable with varid"); return; } if (!vt1) return; if (parent->astOperand2() && !vt2) return; const bool ternary = parent->str() == ":" && parent->astParent() && parent->astParent()->str() == "?"; if (ternary) { if (vt2 && vt1->pointer == vt2->pointer && vt1->type == vt2->type && vt1->sign == vt2->sign) setValueType(parent, *vt2); parent = parent->astParent(); } if (ternary || parent->isArithmeticalOp() || parent->tokType() == Token::eIncDecOp) { // CONTAINER + x => CONTAINER if (parent->str() == "+" && vt1->type == ValueType::Type::CONTAINER && vt2 && vt2->isIntegral()) { setValueType(parent, *vt1); return; } // x + CONTAINER => CONTAINER if (parent->str() == "+" && vt1->isIntegral() && vt2 && vt2->type == ValueType::Type::CONTAINER) { setValueType(parent, *vt2); return; } if (parent->isArithmeticalOp()) { if (vt1->pointer != 0U && vt2 && vt2->pointer == 0U) { setValueType(parent, *vt1); return; } if (vt1->pointer == 0U && vt2 && vt2->pointer != 0U) { setValueType(parent, *vt2); return; } } else if (ternary) { if (vt1->pointer != 0U && vt2 && vt2->pointer == 0U) { if (vt2->isPrimitive()) setValueType(parent, *vt1); else setValueType(parent, *vt2); return; } if (vt1->pointer == 0U && vt2 && vt2->pointer != 0U) { if (vt1->isPrimitive()) setValueType(parent, *vt2); else setValueType(parent, *vt1); return; } if (vt1->isTypeEqual(vt2)) { setValueType(parent, *vt1); return; } } if (vt1->pointer != 0U) { if (ternary || parent->tokType() == Token::eIncDecOp) // result is pointer setValueType(parent, *vt1); else // result is pointer diff setValueType(parent, ValueType(ValueType::Sign::SIGNED, ValueType::Type::INT, 0U, 0U, "ptrdiff_t")); return; } if (vt1->type == ValueType::Type::LONGDOUBLE || (vt2 && vt2->type == ValueType::Type::LONGDOUBLE)) { setValueType(parent, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::LONGDOUBLE, 0U)); return; } if (vt1->type == ValueType::Type::DOUBLE || (vt2 && vt2->type == ValueType::Type::DOUBLE)) { setValueType(parent, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::DOUBLE, 0U)); return; } if (vt1->type == ValueType::Type::FLOAT || (vt2 && vt2->type == ValueType::Type::FLOAT)) { setValueType(parent, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::FLOAT, 0U)); return; } // iterator +/- integral = iterator if (vt1->type == ValueType::Type::ITERATOR && vt2 && vt2->isIntegral() && (parent->str() == "+" || parent->str() == "-")) { setValueType(parent, *vt1); return; } if (parent->str() == "+" && vt1->type == ValueType::Type::CONTAINER && vt2 && vt2->type == ValueType::Type::CONTAINER && vt1->container == vt2->container) { setValueType(parent, *vt1); return; } } if (vt1->isIntegral() && vt1->pointer == 0U && (!vt2 || (vt2->isIntegral() && vt2->pointer == 0U)) && (ternary || parent->isArithmeticalOp() || parent->tokType() == Token::eBitOp || parent->tokType() == Token::eIncDecOp || parent->isAssignmentOp())) { ValueType vt; if (!vt2 || vt1->type > vt2->type) { vt.type = vt1->type; vt.sign = vt1->sign; vt.originalTypeName = vt1->originalTypeName; } else if (vt1->type == vt2->type) { vt.type = vt1->type; if (vt1->sign == ValueType::Sign::UNSIGNED || vt2->sign == ValueType::Sign::UNSIGNED) vt.sign = ValueType::Sign::UNSIGNED; else if (vt1->sign == ValueType::Sign::UNKNOWN_SIGN || vt2->sign == ValueType::Sign::UNKNOWN_SIGN) vt.sign = ValueType::Sign::UNKNOWN_SIGN; else vt.sign = ValueType::Sign::SIGNED; vt.originalTypeName = (vt1->originalTypeName.empty() ? vt2 : vt1)->originalTypeName; } else { vt.type = vt2->type; vt.sign = vt2->sign; vt.originalTypeName = vt2->originalTypeName; } if (vt.type < ValueType::Type::INT && !(ternary && vt.type==ValueType::Type::BOOL)) { vt.type = ValueType::Type::INT; vt.sign = ValueType::Sign::SIGNED; vt.originalTypeName.clear(); } setValueType(parent, vt); return; } } static ValueType::Type getEnumType(const Scope* scope, const Platform& platform) // TODO: also determine sign? { ValueType::Type type = ValueType::Type::INT; for (const Token* tok = scope->bodyStart; tok && tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isAssignmentOp()) continue; const Token* vTok = tok->astOperand2(); if (!vTok->hasKnownIntValue()) { if (!vTok->isLiteral()) continue; if (const ValueType* vt = vTok->valueType()) { if ((vt->type > type && (vt->type == ValueType::Type::LONG || vt->type == ValueType::Type::LONGLONG))) type = vt->type; } continue; } const MathLib::bigint value = vTok->getKnownIntValue(); if (!platform.isIntValue(value)) { type = ValueType::Type::LONG; if (!platform.isLongValue(value)) type = ValueType::Type::LONGLONG; } } return type; } static const Token* parsedecl(const Token* type, ValueType* const valuetype, ValueType::Sign defaultSignedness, const Settings& settings, SourceLocation loc) { if (settings.debugnormal || settings.debugwarnings) valuetype->setDebugPath(type, loc); const Token * const previousType = type; const int pointer0 = valuetype->pointer; while (Token::Match(type->previous(), "%name%") && !endsWith(type->strAt(-1), ':')) type = type->previous(); valuetype->sign = ValueType::Sign::UNKNOWN_SIGN; if (!valuetype->typeScope && !valuetype->smartPointerType) valuetype->type = ValueType::Type::UNKNOWN_TYPE; else if (valuetype->smartPointerType) valuetype->type = ValueType::Type::SMART_POINTER; else if (valuetype->typeScope->type == Scope::eEnum) { const Token * enum_type = valuetype->typeScope->enumType; if (enum_type) { if (enum_type->isSigned()) valuetype->sign = ValueType::Sign::SIGNED; else if (enum_type->isUnsigned()) valuetype->sign = ValueType::Sign::UNSIGNED; else valuetype->sign = defaultSignedness; const ValueType::Type t = ValueType::typeFromString(enum_type->str(), enum_type->isLong()); if (t != ValueType::Type::UNKNOWN_TYPE) valuetype->type = t; else if (enum_type->isStandardType()) valuetype->fromLibraryType(enum_type->str(), settings); } else valuetype->type = getEnumType(valuetype->typeScope, settings.platform); } else valuetype->type = ValueType::Type::RECORD; const bool cpp = type->isCpp(); bool par = false; while (Token::Match(type, "%name%|*|&|&&|::|(") && !Token::Match(type, "typename|template") && type->varId() == 0 && !type->variable() && !type->function()) { bool isIterator = false; if (type->str() == "(") { if (!Token::simpleMatch(type, "( *")) break; if (Token::Match(type->link(), ") const| {")) break; if (par) break; par = true; } if (Token::simpleMatch(type, "decltype (") && type->next()->valueType()) { const ValueType *vt2 = type->next()->valueType(); if (valuetype->sign == ValueType::Sign::UNKNOWN_SIGN) valuetype->sign = vt2->sign; if (valuetype->type == ValueType::Type::UNKNOWN_TYPE) valuetype->type = vt2->type; valuetype->constness += vt2->constness; valuetype->pointer += vt2->pointer; valuetype->reference = vt2->reference; type = type->linkAt(1)->next(); continue; } if (type->isSigned()) valuetype->sign = ValueType::Sign::SIGNED; else if (type->isUnsigned()) valuetype->sign = ValueType::Sign::UNSIGNED; if (valuetype->type == ValueType::Type::UNKNOWN_TYPE && type->type() && type->type()->isTypeAlias() && type->type()->typeStart && type->type()->typeStart->str() != type->str() && type->type()->typeStart != previousType) parsedecl(type->type()->typeStart, valuetype, defaultSignedness, settings); else if (Token::Match(type, "const|constexpr")) valuetype->constness |= (1 << (valuetype->pointer - pointer0)); else if (Token::simpleMatch(type, "volatile")) valuetype->volatileness |= (1 << (valuetype->pointer - pointer0)); else if (settings.clang && type->str().size() > 2 && type->str().find("::") < type->str().find('<')) { TokenList typeTokens(&settings); std::string::size_type pos1 = 0; do { const std::string::size_type pos2 = type->str().find("::", pos1); if (pos2 == std::string::npos) { typeTokens.addtoken(type->str().substr(pos1), 0, 0, 0, false); break; } typeTokens.addtoken(type->str().substr(pos1, pos2 - pos1), 0, 0, 0, false); typeTokens.addtoken("::", 0, 0, 0, false); pos1 = pos2 + 2; } while (pos1 < type->str().size()); const Library::Container* container = settings.library.detectContainerOrIterator(typeTokens.front(), &isIterator); if (container) { if (isIterator) valuetype->type = ValueType::Type::ITERATOR; else valuetype->type = ValueType::Type::CONTAINER; valuetype->container = container; } else { const Scope *scope = type->scope(); valuetype->typeScope = scope->check->findScope(typeTokens.front(), scope); if (valuetype->typeScope) valuetype->type = (scope->type == Scope::ScopeType::eClass) ? ValueType::Type::RECORD : ValueType::Type::NONSTD; } } else if (const Library::Container* container = (cpp ? settings.library.detectContainerOrIterator(type, &isIterator) : nullptr)) { if (isIterator) valuetype->type = ValueType::Type::ITERATOR; else valuetype->type = ValueType::Type::CONTAINER; valuetype->container = container; while (Token::Match(type, "%type%|::|<") && type->str() != "const") { if (type->str() == "<" && type->link()) { if (container->type_templateArgNo >= 0) { const Token *templateType = type->next(); for (int j = 0; templateType && j < container->type_templateArgNo; j++) templateType = templateType->nextTemplateArgument(); valuetype->containerTypeToken = templateType; } type = type->link(); } type = type->next(); } if (type && type->str() == "(" && type->previous()->function()) // we are past the end of the type type = type->previous(); continue; } else if (const Library::SmartPointer* smartPointer = (cpp ? settings.library.detectSmartPointer(type) : nullptr)) { const Token* argTok = Token::findsimplematch(type, "<"); if (!argTok) break; valuetype->smartPointer = smartPointer; valuetype->smartPointerTypeToken = argTok->next(); valuetype->smartPointerType = argTok->next()->type(); valuetype->type = ValueType::Type::SMART_POINTER; type = argTok->link(); if (type) type = type->next(); continue; } else if (Token::Match(type, "%name% :: %name%")) { std::string typestr; const Token *end = type; while (Token::Match(end, "%name% :: %name%")) { typestr += end->str() + "::"; end = end->tokAt(2); } typestr += end->str(); if (valuetype->fromLibraryType(typestr, settings)) type = end; } else if (ValueType::Type::UNKNOWN_TYPE != ValueType::typeFromString(type->str(), type->isLong())) { const ValueType::Type t0 = valuetype->type; valuetype->type = ValueType::typeFromString(type->str(), type->isLong()); if (t0 == ValueType::Type::LONG) { if (valuetype->type == ValueType::Type::LONG) valuetype->type = ValueType::Type::LONGLONG; else if (valuetype->type == ValueType::Type::DOUBLE) valuetype->type = ValueType::Type::LONGDOUBLE; } } else if (type->str() == "auto") { const ValueType *vt = type->valueType(); if (!vt) return nullptr; valuetype->type = vt->type; valuetype->pointer = vt->pointer; valuetype->reference = vt->reference; if (vt->sign != ValueType::Sign::UNKNOWN_SIGN) valuetype->sign = vt->sign; valuetype->constness = vt->constness; valuetype->volatileness = vt->volatileness; valuetype->originalTypeName = vt->originalTypeName; const bool hasConst = Token::simpleMatch(type->previous(), "const"); const bool hasVolatile = Token::simpleMatch(type->previous(), "volatile"); while (Token::Match(type, "%name%|*|&|&&|::") && !type->variable()) { if (type->str() == "*") { valuetype->pointer = 1; if (hasConst) valuetype->constness = 1; if (hasVolatile) valuetype->volatileness = 1; } else if (type->str() == "&") { valuetype->reference = Reference::LValue; } else if (type->str() == "&&") { valuetype->reference = Reference::RValue; } if (type->str() == "const") valuetype->constness |= (1 << valuetype->pointer); if (type->str() == "volatile") valuetype->volatileness |= (1 << valuetype->pointer); type = type->next(); } break; } else if (!valuetype->typeScope && (type->str() == "struct" || type->str() == "enum") && valuetype->type != ValueType::Type::SMART_POINTER) valuetype->type = type->str() == "struct" ? ValueType::Type::RECORD : ValueType::Type::NONSTD; else if (!valuetype->typeScope && type->type() && type->type()->classScope && valuetype->type != ValueType::Type::SMART_POINTER) { if (type->type()->classScope->type == Scope::ScopeType::eEnum) { valuetype->sign = ValueType::Sign::SIGNED; valuetype->type = getEnumType(type->type()->classScope, settings.platform); } else { valuetype->type = ValueType::Type::RECORD; } valuetype->typeScope = type->type()->classScope; } else if (type->isName() && valuetype->sign != ValueType::Sign::UNKNOWN_SIGN && valuetype->pointer == 0U) return nullptr; else if (type->str() == "*") valuetype->pointer++; else if (type->str() == "&") valuetype->reference = Reference::LValue; else if (type->str() == "&&") valuetype->reference = Reference::RValue; else if (type->isStandardType()) valuetype->fromLibraryType(type->str(), settings); else if (Token::Match(type->previous(), "!!:: %name% !!::")) valuetype->fromLibraryType(type->str(), settings); if (!type->originalName().empty()) valuetype->originalTypeName = type->originalName(); type = type->next(); if (type && type->link() && type->str() == "<") type = type->link()->next(); } // Set signedness for integral types.. if (valuetype->isIntegral() && valuetype->sign == ValueType::Sign::UNKNOWN_SIGN) { if (valuetype->type == ValueType::Type::CHAR) valuetype->sign = defaultSignedness; else if (valuetype->type >= ValueType::Type::SHORT) valuetype->sign = ValueType::Sign::SIGNED; } return (type && (valuetype->type != ValueType::Type::UNKNOWN_TYPE || valuetype->pointer > 0 || valuetype->reference != Reference::None)) ? type : nullptr; } static const Scope *getClassScope(const Token *tok) { return tok && tok->valueType() && tok->valueType()->typeScope && tok->valueType()->typeScope->isClassOrStruct() ? tok->valueType()->typeScope : nullptr; } static const Function *getOperatorFunction(const Token * const tok) { const std::string functionName("operator" + tok->str()); std::multimap<std::string, const Function *>::const_iterator it; const Scope *classScope = getClassScope(tok->astOperand1()); if (classScope) { it = classScope->functionMap.find(functionName); if (it != classScope->functionMap.end()) return it->second; } classScope = getClassScope(tok->astOperand2()); if (classScope) { it = classScope->functionMap.find(functionName); if (it != classScope->functionMap.end()) return it->second; } return nullptr; } static const Function* getFunction(const Token* tok) { if (!tok) return nullptr; if (tok->function() && tok->function()->retDef) return tok->function(); if (const Variable* lvar = tok->variable()) { // lambda const Function* lambda{}; if (Token::Match(lvar->nameToken()->next(), "; %varid% = [", lvar->declarationId())) lambda = lvar->nameToken()->tokAt(4)->function(); else if (Token::simpleMatch(lvar->nameToken()->next(), "{ [")) lambda = lvar->nameToken()->tokAt(2)->function(); if (lambda && lambda->retDef) return lambda; } return nullptr; } void SymbolDatabase::setValueTypeInTokenList(bool reportDebugWarnings, Token *tokens) { if (!tokens) tokens = mTokenizer.list.front(); for (Token *tok = tokens; tok; tok = tok->next()) tok->setValueType(nullptr); for (Token *tok = tokens; tok; tok = tok->next()) { if (tok->isNumber()) { if (MathLib::isFloat(tok->str())) { ValueType::Type type = ValueType::Type::DOUBLE; const char suffix = tok->str()[tok->str().size() - 1]; if (suffix == 'f' || suffix == 'F') type = ValueType::Type::FLOAT; else if (suffix == 'L' || suffix == 'l') type = ValueType::Type::LONGDOUBLE; setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, type, 0U)); } else if (MathLib::isInt(tok->str())) { const std::string tokStr = MathLib::abs(tok->str()); const bool unsignedSuffix = (tokStr.find_last_of("uU") != std::string::npos); ValueType::Sign sign = unsignedSuffix ? ValueType::Sign::UNSIGNED : ValueType::Sign::SIGNED; ValueType::Type type = ValueType::Type::INT; const MathLib::biguint value = MathLib::toBigUNumber(tokStr); for (std::size_t pos = tokStr.size() - 1U; pos > 0U; --pos) { const char suffix = tokStr[pos]; if (suffix == 'u' || suffix == 'U') sign = ValueType::Sign::UNSIGNED; else if (suffix == 'l' || suffix == 'L') type = (type == ValueType::Type::INT) ? ValueType::Type::LONG : ValueType::Type::LONGLONG; else if (pos > 2U && suffix == '4' && tokStr[pos - 1] == '6' && tokStr[pos - 2] == 'i') { type = ValueType::Type::LONGLONG; pos -= 2; } else break; } if (mSettings.platform.type != Platform::Type::Unspecified) { if (type <= ValueType::Type::INT && mSettings.platform.isIntValue(unsignedSuffix ? (value >> 1) : value)) type = ValueType::Type::INT; else if (type <= ValueType::Type::INT && !MathLib::isDec(tokStr) && mSettings.platform.isIntValue(value >> 2)) { type = ValueType::Type::INT; sign = ValueType::Sign::UNSIGNED; } else if (type <= ValueType::Type::LONG && mSettings.platform.isLongValue(unsignedSuffix ? (value >> 1) : value)) type = ValueType::Type::LONG; else if (type <= ValueType::Type::LONG && !MathLib::isDec(tokStr) && mSettings.platform.isLongValue(value >> 2)) { type = ValueType::Type::LONG; sign = ValueType::Sign::UNSIGNED; } else if (mSettings.platform.isLongLongValue(unsignedSuffix ? (value >> 1) : value)) type = ValueType::Type::LONGLONG; else { type = ValueType::Type::LONGLONG; sign = ValueType::Sign::UNSIGNED; } } setValueType(tok, ValueType(sign, type, 0U)); } } else if (tok->isComparisonOp() || tok->tokType() == Token::eLogicalOp) { if (tok->isCpp() && tok->isComparisonOp() && (getClassScope(tok->astOperand1()) || getClassScope(tok->astOperand2()))) { const Function *function = getOperatorFunction(tok); if (function) { ValueType vt; parsedecl(function->retDef, &vt, mDefaultSignedness, mSettings); setValueType(tok, vt); continue; } } setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::BOOL, 0U)); } else if (tok->isBoolean()) { setValueType(tok, ValueType(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::BOOL, 0U)); } else if (tok->tokType() == Token::eChar || tok->tokType() == Token::eString) { nonneg int const pointer = tok->tokType() == Token::eChar ? 0 : 1; nonneg int const constness = tok->tokType() == Token::eChar ? 0 : 1; nonneg int const volatileness = 0; ValueType valuetype(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::CHAR, pointer, constness, volatileness); if (tok->isCpp() && mSettings.standards.cpp >= Standards::CPP20 && tok->isUtf8()) { valuetype.originalTypeName = "char8_t"; valuetype.fromLibraryType(valuetype.originalTypeName, mSettings); } else if (tok->isUtf16()) { valuetype.originalTypeName = "char16_t"; valuetype.fromLibraryType(valuetype.originalTypeName, mSettings); } else if (tok->isUtf32()) { valuetype.originalTypeName = "char32_t"; valuetype.fromLibraryType(valuetype.originalTypeName, mSettings); } else if (tok->isLong()) { valuetype.originalTypeName = "wchar_t"; valuetype.type = ValueType::Type::WCHAR_T; } else if ((tok->tokType() == Token::eChar) && ((!tok->isCpp() && tok->isCChar()) || (tok->isCMultiChar()))) { valuetype.type = ValueType::Type::INT; valuetype.sign = ValueType::Sign::SIGNED; } setValueType(tok, valuetype); } else if (tok->link() && Token::Match(tok, "(|{")) { const Token* start = tok->astOperand1() ? tok->astOperand1()->findExpressionStartEndTokens().first : nullptr; // cast if (tok->isCast() && !tok->astOperand2() && Token::Match(tok, "( %name%")) { ValueType valuetype; if (Token::simpleMatch(parsedecl(tok->next(), &valuetype, mDefaultSignedness, mSettings), ")")) setValueType(tok, valuetype); } // C++ cast else if (tok->astOperand2() && Token::Match(tok->astOperand1(), "static_cast|const_cast|dynamic_cast|reinterpret_cast < %name%") && tok->astOperand1()->linkAt(1)) { ValueType valuetype; if (Token::simpleMatch(parsedecl(tok->astOperand1()->tokAt(2), &valuetype, mDefaultSignedness, mSettings), ">")) setValueType(tok, valuetype); } // Construct smart pointer else if (start && start->isCpp() && mSettings.library.isSmartPointer(start)) { ValueType valuetype; if (parsedecl(start, &valuetype, mDefaultSignedness, mSettings)) { setValueType(tok, valuetype); setValueType(tok->astOperand1(), valuetype); } } // function or lambda else if (const Function* f = getFunction(tok->previous())) { ValueType valuetype; if (parsedecl(f->retDef, &valuetype, mDefaultSignedness, mSettings)) setValueType(tok, valuetype); } else if (Token::simpleMatch(tok->previous(), "sizeof (")) { ValueType valuetype(ValueType::Sign::UNSIGNED, ValueType::Type::LONG, 0U); if (mSettings.platform.type == Platform::Type::Win64) valuetype.type = ValueType::Type::LONGLONG; valuetype.originalTypeName = "size_t"; setValueType(tok, valuetype); if (Token::Match(tok, "( %type% %type%| *| *| )")) { ValueType vt; if (parsedecl(tok->next(), &vt, mDefaultSignedness, mSettings)) { setValueType(tok->next(), vt); } } } // function style cast else if (tok->previous() && tok->previous()->isStandardType()) { ValueType valuetype; if (tok->astOperand1() && valuetype.fromLibraryType(tok->astOperand1()->expressionString(), mSettings)) { setValueType(tok, valuetype); continue; } valuetype.type = ValueType::typeFromString(tok->strAt(-1), tok->previous()->isLong()); if (tok->previous()->isUnsigned()) valuetype.sign = ValueType::Sign::UNSIGNED; else if (tok->previous()->isSigned()) valuetype.sign = ValueType::Sign::SIGNED; else if (valuetype.isIntegral() && valuetype.type != ValueType::UNKNOWN_INT) valuetype.sign = mDefaultSignedness; setValueType(tok, valuetype); } // constructor call else if (tok->previous() && tok->previous()->function() && tok->previous()->function()->isConstructor()) { ValueType valuetype; valuetype.type = ValueType::RECORD; valuetype.typeScope = tok->previous()->function()->tokenDef->scope(); setValueType(tok, valuetype); } else if (Token::simpleMatch(tok->previous(), "= {") && tok->tokAt(-2) && tok->tokAt(-2)->valueType()) { ValueType vt = *tok->tokAt(-2)->valueType(); setValueType(tok, vt); } // library type/function else if (tok->previous()) { // Aggregate constructor if (Token::Match(tok->previous(), "%name%")) { ValueType valuetype; if (parsedecl(tok->previous(), &valuetype, mDefaultSignedness, mSettings)) { if (valuetype.typeScope) { setValueType(tok, valuetype); continue; } } } if (tok->isCpp() && tok->astParent() && Token::Match(tok->astOperand1(), "%name%|::")) { const Token *typeStartToken = tok->astOperand1(); while (typeStartToken && typeStartToken->str() == "::") typeStartToken = typeStartToken->astOperand1(); if (mSettings.library.detectContainerOrIterator(typeStartToken) || mSettings.library.detectSmartPointer(typeStartToken)) { ValueType vt; if (parsedecl(typeStartToken, &vt, mDefaultSignedness, mSettings)) { setValueType(tok, vt); continue; } } const std::string e = tok->astOperand1()->expressionString(); if ((e == "std::make_shared" || e == "std::make_unique") && Token::Match(tok->astOperand1(), ":: %name% < %name%")) { ValueType vt; parsedecl(tok->astOperand1()->tokAt(3), &vt, mDefaultSignedness, mSettings); if (vt.typeScope) { vt.smartPointerType = vt.typeScope->definedType; vt.typeScope = nullptr; } if (e == "std::make_shared" && mSettings.library.smartPointers().count("std::shared_ptr") > 0) vt.smartPointer = &mSettings.library.smartPointers().at("std::shared_ptr"); if (e == "std::make_unique" && mSettings.library.smartPointers().count("std::unique_ptr") > 0) vt.smartPointer = &mSettings.library.smartPointers().at("std::unique_ptr"); vt.type = ValueType::Type::SMART_POINTER; vt.smartPointerTypeToken = tok->astOperand1()->tokAt(3); setValueType(tok, vt); continue; } ValueType podtype; if (podtype.fromLibraryType(e, mSettings)) { setValueType(tok, podtype); continue; } } const std::string& typestr(mSettings.library.returnValueType(tok->previous())); if (!typestr.empty()) { ValueType valuetype; TokenList tokenList(&mSettings); std::istringstream istr(typestr+";"); tokenList.createTokens(istr, tok->isCpp() ? Standards::Language::CPP : Standards::Language::C); // TODO: check result? tokenList.simplifyStdType(); if (parsedecl(tokenList.front(), &valuetype, mDefaultSignedness, mSettings)) { valuetype.originalTypeName = typestr; setValueType(tok, valuetype); } } //Is iterator fetching function invoked on container? const bool isReturnIter = typestr == "iterator"; if (typestr.empty() || isReturnIter) { if (Token::simpleMatch(tok->astOperand1(), ".") && tok->astOperand1()->astOperand1() && tok->astOperand1()->astOperand2() && tok->astOperand1()->astOperand1()->valueType() && tok->astOperand1()->astOperand1()->valueType()->container) { const Library::Container *cont = tok->astOperand1()->astOperand1()->valueType()->container; const auto it = cont->functions.find(tok->astOperand1()->astOperand2()->str()); if (it != cont->functions.end()) { if (it->second.yield == Library::Container::Yield::START_ITERATOR || it->second.yield == Library::Container::Yield::END_ITERATOR || it->second.yield == Library::Container::Yield::ITERATOR) { ValueType vt; vt.type = ValueType::Type::ITERATOR; vt.container = cont; vt.containerTypeToken = tok->astOperand1()->astOperand1()->valueType()->containerTypeToken; setValueType(tok, vt); continue; } } //Is iterator fetching function called? } else if (Token::simpleMatch(tok->astOperand1(), "::") && tok->astOperand2() && tok->astOperand2()->isVariable()) { const auto* const paramVariable = tok->astOperand2()->variable(); if (!paramVariable || !paramVariable->valueType() || !paramVariable->valueType()->container) { continue; } const auto yield = astFunctionYield(tok->previous(), mSettings); if (yield == Library::Container::Yield::START_ITERATOR || yield == Library::Container::Yield::END_ITERATOR || yield == Library::Container::Yield::ITERATOR) { ValueType vt; vt.type = ValueType::Type::ITERATOR; vt.container = paramVariable->valueType()->container; vt.containerTypeToken = paramVariable->valueType()->containerTypeToken; setValueType(tok, vt); } } if (isReturnIter) { const std::vector<const Token*> args = getArguments(tok); if (!args.empty()) { const Library::ArgumentChecks::IteratorInfo* info = mSettings.library.getArgIteratorInfo(tok->previous(), 1); if (info && info->it) { const Token* contTok = args[0]; if (Token::simpleMatch(args[0]->astOperand1(), ".") && args[0]->astOperand1()->astOperand1()) // .begin() contTok = args[0]->astOperand1()->astOperand1(); else if (Token::simpleMatch(args[0], "(") && args[0]->astOperand2()) // std::begin() contTok = args[0]->astOperand2(); while (Token::simpleMatch(contTok, "[")) // move to container token contTok = contTok->astOperand1(); if (Token::simpleMatch(contTok, ".")) contTok = contTok->astOperand2(); if (contTok && contTok->variable() && contTok->variable()->valueType() && contTok->variable()->valueType()->container) { ValueType vt; vt.type = ValueType::Type::ITERATOR; vt.container = contTok->variable()->valueType()->container; vt.containerTypeToken = contTok->variable()->valueType()->containerTypeToken; setValueType(tok, vt); } else if (Token::simpleMatch(contTok, "(") && contTok->astOperand1() && contTok->astOperand1()->function()) { const Function* func = contTok->astOperand1()->function(); if (const ValueType* funcVt = func->tokenDef->next()->valueType()) { ValueType vt; vt.type = ValueType::Type::ITERATOR; vt.container = funcVt->container; vt.containerTypeToken = funcVt->containerTypeToken; setValueType(tok, vt); } } } } } continue; } TokenList tokenList(&mSettings); std::istringstream istr(typestr+";"); if (tokenList.createTokens(istr, tok->isCpp() ? Standards::Language::CPP : Standards::Language::C)) { ValueType vt; tokenList.simplifyPlatformTypes(); tokenList.simplifyStdType(); if (parsedecl(tokenList.front(), &vt, mDefaultSignedness, mSettings)) { vt.originalTypeName = typestr; setValueType(tok, vt); } } } } else if (tok->str() == "return") { const Scope *functionScope = tok->scope(); while (functionScope && functionScope->isExecutable() && functionScope->type != Scope::eLambda && functionScope->type != Scope::eFunction) functionScope = functionScope->nestedIn; if (functionScope && functionScope->type == Scope::eFunction && functionScope->function && functionScope->function->retDef) { ValueType vt = ValueType::parseDecl(functionScope->function->retDef, mSettings); setValueType(tok, vt); if (Token::simpleMatch(tok, "return {")) setValueType(tok->next(), vt); } } else if (tok->variable()) { setValueType(tok, *tok->variable()); if (!tok->variable()->valueType() && tok->valueType()) const_cast<Variable*>(tok->variable())->setValueType(*tok->valueType()); } else if (tok->enumerator()) { setValueType(tok, *tok->enumerator()); } else if (tok->isKeyword() && tok->str() == "new") { const Token *typeTok = tok->next(); if (Token::Match(typeTok, "( std| ::| nothrow )")) typeTok = typeTok->link()->next(); bool isIterator = false; if (const Library::Container* c = mSettings.library.detectContainerOrIterator(typeTok, &isIterator)) { ValueType vt; vt.pointer = 1; vt.container = c; vt.type = isIterator ? ValueType::Type::ITERATOR : ValueType::Type::CONTAINER; setValueType(tok, vt); continue; } std::string typestr; while (Token::Match(typeTok, "%name% :: %name%")) { typestr += typeTok->str() + "::"; typeTok = typeTok->tokAt(2); } if (!Token::Match(typeTok, "%type% ;|[|(")) continue; typestr += typeTok->str(); ValueType vt; vt.pointer = 1; if (typeTok->type() && typeTok->type()->classScope) { vt.type = ValueType::Type::RECORD; vt.typeScope = typeTok->type()->classScope; } else { vt.type = ValueType::typeFromString(typestr, typeTok->isLong()); if (vt.type == ValueType::Type::UNKNOWN_TYPE) vt.fromLibraryType(typestr, mSettings); if (vt.type == ValueType::Type::UNKNOWN_TYPE) continue; if (typeTok->isUnsigned()) vt.sign = ValueType::Sign::UNSIGNED; else if (typeTok->isSigned()) vt.sign = ValueType::Sign::SIGNED; if (vt.sign == ValueType::Sign::UNKNOWN_SIGN && vt.isIntegral()) vt.sign = (vt.type == ValueType::Type::CHAR) ? mDefaultSignedness : ValueType::Sign::SIGNED; } setValueType(tok, vt); if (Token::simpleMatch(tok->astOperand1(), "(")) { vt.pointer--; setValueType(tok->astOperand1(), vt); } } else if (tok->isKeyword() && tok->str() == "return" && tok->scope()) { const Scope* fscope = tok->scope(); while (fscope && !fscope->function) fscope = fscope->nestedIn; if (fscope && fscope->function && fscope->function->retDef) { ValueType vt; parsedecl(fscope->function->retDef, &vt, mDefaultSignedness, mSettings); setValueType(tok, vt); } } else if (tok->isKeyword() && tok->str() == "this" && tok->scope()->isExecutable()) { const Scope* fscope = tok->scope(); while (fscope && !fscope->function) fscope = fscope->nestedIn; const Scope* defScope = fscope && fscope->function->tokenDef ? fscope->function->tokenDef->scope() : nullptr; if (defScope && defScope->isClassOrStruct()) { ValueType vt(ValueType::Sign::UNKNOWN_SIGN, ValueType::Type::RECORD, 1); vt.typeScope = defScope; if (fscope->function->isConst()) vt.constness = 1; if (fscope->function->isVolatile()) vt.volatileness = 1; setValueType(tok, vt); } } } if (reportDebugWarnings && mSettings.debugwarnings) { for (Token *tok = tokens; tok; tok = tok->next()) { if (tok->str() == "auto" && !tok->valueType()) { if (Token::Match(tok->next(), "%name% ; %name% = [") && isLambdaCaptureList(tok->tokAt(5))) continue; if (Token::Match(tok->next(), "%name% {|= [") && isLambdaCaptureList(tok->tokAt(3))) continue; debugMessage(tok, "autoNoType", "auto token with no type."); } } } // Update functions with new type information. createSymbolDatabaseSetFunctionPointers(false); // Update auto variables with new type information. createSymbolDatabaseSetVariablePointers(); } ValueType ValueType::parseDecl(const Token *type, const Settings &settings) { ValueType vt; parsedecl(type, &vt, settings.platform.defaultSign == 'u' ? Sign::UNSIGNED : Sign::SIGNED, settings); return vt; } ValueType::Type ValueType::typeFromString(const std::string &typestr, bool longType) { if (typestr == "void") return ValueType::Type::VOID; if (typestr == "bool" || typestr == "_Bool") return ValueType::Type::BOOL; if (typestr== "char") return ValueType::Type::CHAR; if (typestr == "short") return ValueType::Type::SHORT; if (typestr == "wchar_t") return ValueType::Type::WCHAR_T; if (typestr == "int") return ValueType::Type::INT; if (typestr == "long") return longType ? ValueType::Type::LONGLONG : ValueType::Type::LONG; if (typestr == "float") return ValueType::Type::FLOAT; if (typestr == "double") return longType ? ValueType::Type::LONGDOUBLE : ValueType::Type::DOUBLE; return ValueType::Type::UNKNOWN_TYPE; } bool ValueType::fromLibraryType(const std::string &typestr, const Settings &settings) { const Library::PodType* podtype = settings.library.podtype(typestr); if (podtype && (podtype->sign == 's' || podtype->sign == 'u')) { if (podtype->size == 1) type = ValueType::Type::CHAR; else if (podtype->size == settings.platform.sizeof_int) type = ValueType::Type::INT; else if (podtype->size == settings.platform.sizeof_short) type = ValueType::Type::SHORT; else if (podtype->size == settings.platform.sizeof_long) type = ValueType::Type::LONG; else if (podtype->size == settings.platform.sizeof_long_long) type = ValueType::Type::LONGLONG; else if (podtype->stdtype == Library::PodType::Type::BOOL) type = ValueType::Type::BOOL; else if (podtype->stdtype == Library::PodType::Type::CHAR) type = ValueType::Type::CHAR; else if (podtype->stdtype == Library::PodType::Type::SHORT) type = ValueType::Type::SHORT; else if (podtype->stdtype == Library::PodType::Type::INT) type = ValueType::Type::INT; else if (podtype->stdtype == Library::PodType::Type::LONG) type = ValueType::Type::LONG; else if (podtype->stdtype == Library::PodType::Type::LONGLONG) type = ValueType::Type::LONGLONG; else type = ValueType::Type::UNKNOWN_INT; sign = (podtype->sign == 'u') ? ValueType::UNSIGNED : ValueType::SIGNED; return true; } if (podtype && podtype->stdtype == Library::PodType::Type::NO) { type = ValueType::Type::POD; sign = ValueType::UNKNOWN_SIGN; return true; } const Library::PlatformType *platformType = settings.library.platform_type(typestr, settings.platform.toString()); if (platformType) { if (platformType->mType == "char") type = ValueType::Type::CHAR; else if (platformType->mType == "short") type = ValueType::Type::SHORT; else if (platformType->mType == "wchar_t") type = ValueType::Type::WCHAR_T; else if (platformType->mType == "int") type = platformType->mLong ? ValueType::Type::LONG : ValueType::Type::INT; else if (platformType->mType == "long") type = platformType->mLong ? ValueType::Type::LONGLONG : ValueType::Type::LONG; if (platformType->mSigned) sign = ValueType::SIGNED; else if (platformType->mUnsigned) sign = ValueType::UNSIGNED; if (platformType->mPointer) pointer = 1; if (platformType->mPtrPtr) pointer = 2; if (platformType->mConstPtr) constness = 1; return true; } if (!podtype && (typestr == "size_t" || typestr == "std::size_t")) { originalTypeName = "size_t"; sign = ValueType::UNSIGNED; if (settings.platform.sizeof_size_t == settings.platform.sizeof_long) type = ValueType::Type::LONG; else if (settings.platform.sizeof_size_t == settings.platform.sizeof_long_long) type = ValueType::Type::LONGLONG; else if (settings.platform.sizeof_size_t == settings.platform.sizeof_int) type = ValueType::Type::INT; else type = ValueType::Type::UNKNOWN_INT; return true; } return false; } std::string ValueType::dump() const { std::string ret; switch (type) { case UNKNOWN_TYPE: return ""; case NONSTD: ret += "valueType-type=\"nonstd\""; break; case POD: ret += "valueType-type=\"pod\""; break; case RECORD: ret += "valueType-type=\"record\""; break; case SMART_POINTER: ret += "valueType-type=\"smart-pointer\""; break; case CONTAINER: { ret += "valueType-type=\"container\""; ret += " valueType-containerId=\""; ret += id_string(container); ret += "\""; break; } case ITERATOR: ret += "valueType-type=\"iterator\""; break; case VOID: ret += "valueType-type=\"void\""; break; case BOOL: ret += "valueType-type=\"bool\""; break; case CHAR: ret += "valueType-type=\"char\""; break; case SHORT: ret += "valueType-type=\"short\""; break; case WCHAR_T: ret += "valueType-type=\"wchar_t\""; break; case INT: ret += "valueType-type=\"int\""; break; case LONG: ret += "valueType-type=\"long\""; break; case LONGLONG: ret += "valueType-type=\"long long\""; break; case UNKNOWN_INT: ret += "valueType-type=\"unknown int\""; break; case FLOAT: ret += "valueType-type=\"float\""; break; case DOUBLE: ret += "valueType-type=\"double\""; break; case LONGDOUBLE: ret += "valueType-type=\"long double\""; break; } switch (sign) { case Sign::UNKNOWN_SIGN: break; case Sign::SIGNED: ret += " valueType-sign=\"signed\""; break; case Sign::UNSIGNED: ret += " valueType-sign=\"unsigned\""; break; } if (bits > 0) { ret += " valueType-bits=\""; ret += std::to_string(bits); ret += '\"'; } if (pointer > 0) { ret += " valueType-pointer=\""; ret += std::to_string(pointer); ret += '\"'; } if (constness > 0) { ret += " valueType-constness=\""; ret += std::to_string(constness); ret += '\"'; } if (volatileness > 0) { ret += " valueType-volatileness=\""; ret += std::to_string(volatileness); ret += '\"'; } if (reference == Reference::None) ret += " valueType-reference=\"None\""; else if (reference == Reference::LValue) ret += " valueType-reference=\"LValue\""; else if (reference == Reference::RValue) ret += " valueType-reference=\"RValue\""; if (typeScope) { ret += " valueType-typeScope=\""; ret += id_string(typeScope); ret += '\"'; } if (!originalTypeName.empty()) { ret += " valueType-originalTypeName=\""; ret += ErrorLogger::toxml(originalTypeName); ret += '\"'; } return ret; } bool ValueType::isConst(nonneg int indirect) const { if (indirect > pointer) return false; return constness & (1 << (pointer - indirect)); } bool ValueType::isVolatile(nonneg int indirect) const { if (indirect > pointer) return false; return volatileness & (1 << (pointer - indirect)); } MathLib::bigint ValueType::typeSize(const Platform &platform, bool p) const { if (p && pointer) return platform.sizeof_pointer; if (typeScope && typeScope->definedType && typeScope->definedType->sizeOf) return typeScope->definedType->sizeOf; switch (type) { case ValueType::Type::BOOL: return platform.sizeof_bool; case ValueType::Type::CHAR: return 1; case ValueType::Type::SHORT: return platform.sizeof_short; case ValueType::Type::WCHAR_T: return platform.sizeof_wchar_t; case ValueType::Type::INT: return platform.sizeof_int; case ValueType::Type::LONG: return platform.sizeof_long; case ValueType::Type::LONGLONG: return platform.sizeof_long_long; case ValueType::Type::FLOAT: return platform.sizeof_float; case ValueType::Type::DOUBLE: return platform.sizeof_double; case ValueType::Type::LONGDOUBLE: return platform.sizeof_long_double; default: break; } // Unknown invalid size return 0; } bool ValueType::isTypeEqual(const ValueType* that) const { if (!that) return false; auto tie = [](const ValueType* vt) { return std::tie(vt->type, vt->container, vt->pointer, vt->typeScope, vt->smartPointer); }; return tie(this) == tie(that); } std::string ValueType::str() const { std::string ret; if (constness & 1) ret = " const"; if (volatileness & 1) ret = " volatile"; if (type == VOID) ret += " void"; else if (isIntegral()) { if (sign == SIGNED) ret += " signed"; else if (sign == UNSIGNED) ret += " unsigned"; if (type == BOOL) ret += " bool"; else if (type == CHAR) ret += " char"; else if (type == SHORT) ret += " short"; else if (type == WCHAR_T) ret += " wchar_t"; else if (type == INT) ret += " int"; else if (type == LONG) ret += " long"; else if (type == LONGLONG) ret += " long long"; else if (type == UNKNOWN_INT) ret += " unknown_int"; } else if (type == FLOAT) ret += " float"; else if (type == DOUBLE) ret += " double"; else if (type == LONGDOUBLE) ret += " long double"; else if ((type == ValueType::Type::NONSTD || type == ValueType::Type::RECORD) && typeScope) { std::string className(typeScope->className); const Scope *scope = typeScope->definedType ? typeScope->definedType->enclosingScope : typeScope->nestedIn; while (scope && scope->type != Scope::eGlobal) { if (scope->type == Scope::eClass || scope->type == Scope::eStruct || scope->type == Scope::eNamespace) className = scope->className + "::" + className; scope = (scope->definedType && scope->definedType->enclosingScope) ? scope->definedType->enclosingScope : scope->nestedIn; } ret += ' ' + className; } else if (type == ValueType::Type::CONTAINER && container) { ret += " container(" + container->startPattern + ')'; } else if (type == ValueType::Type::ITERATOR && container) { ret += " iterator(" + container->startPattern + ')'; } else if (type == ValueType::Type::SMART_POINTER && smartPointer) { ret += " smart-pointer(" + smartPointer->name + ")"; } for (unsigned int p = 0; p < pointer; p++) { ret += " *"; if (constness & (2 << p)) ret += " const"; if (volatileness & (2 << p)) ret += " volatile"; } if (reference == Reference::LValue) ret += " &"; else if (reference == Reference::RValue) ret += " &&"; if (ret.empty()) return ret; return ret.substr(1); } void ValueType::setDebugPath(const Token* tok, SourceLocation ctx, const SourceLocation &local) { std::string file = ctx.file_name(); if (file.empty()) return; std::string s = Path::stripDirectoryPart(file) + ":" + std::to_string(ctx.line()) + ": " + ctx.function_name() + " => " + local.function_name(); debugPath.emplace_back(tok, std::move(s)); } ValueType::MatchResult ValueType::matchParameter(const ValueType *call, const ValueType *func) { if (!call || !func) return ValueType::MatchResult::UNKNOWN; if (call->pointer != func->pointer) { if (call->pointer > 1 && func->pointer == 1 && func->type == ValueType::Type::VOID) return ValueType::MatchResult::FALLBACK1; if (call->pointer == 1 && func->pointer == 0 && func->isIntegral() && func->sign != ValueType::Sign::SIGNED) return ValueType::MatchResult::FALLBACK1; if (call->pointer == 1 && call->type == ValueType::Type::CHAR && func->pointer == 0 && func->container && func->container->stdStringLike) return ValueType::MatchResult::FALLBACK2; return ValueType::MatchResult::NOMATCH; // TODO } if (call->pointer > 0) { if ((call->constness | func->constness) != func->constness) return ValueType::MatchResult::NOMATCH; if ((call->volatileness | func->volatileness) != func->volatileness) return ValueType::MatchResult::NOMATCH; if (call->constness == 0 && func->constness != 0 && func->reference != Reference::None) return ValueType::MatchResult::NOMATCH; if (call->volatileness == 0 && func->volatileness != 0 && func->reference != Reference::None) return ValueType::MatchResult::NOMATCH; } if (call->type != func->type || (call->isEnum() && !func->isEnum())) { if (call->type == ValueType::Type::VOID || func->type == ValueType::Type::VOID) return ValueType::MatchResult::FALLBACK1; if (call->pointer > 0) return func->type == ValueType::UNKNOWN_TYPE ? ValueType::MatchResult::UNKNOWN : ValueType::MatchResult::NOMATCH; if (call->isIntegral() && func->isIntegral()) return call->type < func->type ? ValueType::MatchResult::FALLBACK1 : ValueType::MatchResult::FALLBACK2; if (call->isFloat() && func->isFloat()) return ValueType::MatchResult::FALLBACK1; if (call->isIntegral() && func->isFloat()) return ValueType::MatchResult::FALLBACK2; if (call->isFloat() && func->isIntegral()) return ValueType::MatchResult::FALLBACK2; return ValueType::MatchResult::UNKNOWN; // TODO } if (call->typeScope != nullptr || func->typeScope != nullptr) { if (call->typeScope != func->typeScope && !(call->typeScope && func->typeScope && call->typeScope->definedType && call->typeScope->definedType->isDerivedFrom(func->typeScope->className))) return ValueType::MatchResult::NOMATCH; } if (call->container != nullptr || func->container != nullptr) { if (call->container != func->container) return ValueType::MatchResult::NOMATCH; } if (func->typeScope != nullptr && func->container != nullptr) { if (func->type < ValueType::Type::VOID || func->type == ValueType::Type::UNKNOWN_INT) return ValueType::MatchResult::UNKNOWN; } if (call->isIntegral() && func->isIntegral() && call->sign != ValueType::Sign::UNKNOWN_SIGN && func->sign != ValueType::Sign::UNKNOWN_SIGN && call->sign != func->sign) return ValueType::MatchResult::FALLBACK1; if (func->reference != Reference::None && (func->constness > call->constness || func->volatileness > call->volatileness)) return ValueType::MatchResult::FALLBACK1; return ValueType::MatchResult::SAME; } ValueType::MatchResult ValueType::matchParameter(const ValueType *call, const Variable *callVar, const Variable *funcVar) { ValueType vt; const ValueType* pvt = funcVar->valueType(); if (pvt && funcVar->isArray() && !(funcVar->isStlType() && Token::simpleMatch(funcVar->typeStartToken(), "std :: array"))) { // std::array doesn't decay to a pointer vt = *pvt; if (vt.pointer == 0) // don't bump array of pointers vt.pointer = funcVar->dimensions().size(); pvt = &vt; } ValueType cvt; if (call && callVar && callVar->isArray() && !(callVar->isStlType() && Token::simpleMatch(callVar->typeStartToken(), "std :: array"))) { cvt = *call; if (cvt.pointer == 0) // don't bump array of pointers cvt.pointer = callVar->dimensions().size(); call = &cvt; } const ValueType::MatchResult res = ValueType::matchParameter(call, pvt); if (callVar && ((res == ValueType::MatchResult::SAME && call->container) || res == ValueType::MatchResult::UNKNOWN)) { const std::string type1 = getTypeString(callVar->typeStartToken()); const std::string type2 = getTypeString(funcVar->typeStartToken()); const bool templateVar = funcVar->scope() && funcVar->scope()->function && funcVar->scope()->function->templateDef; if (type1 == type2) return ValueType::MatchResult::SAME; if (!templateVar && type1.find("auto") == std::string::npos && type2.find("auto") == std::string::npos) return ValueType::MatchResult::NOMATCH; } return res; }
331,769
C++
.cpp
7,445
32.226998
197
0.513244
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
26,190
checkcondition.cpp
danmar_cppcheck/lib/checkcondition.cpp
/* * Cppcheck - A tool for static C/C++ code analysis * Copyright (C) 2007-2024 Cppcheck team. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //--------------------------------------------------------------------------- // Check for condition mismatches //--------------------------------------------------------------------------- #include "checkcondition.h" #include "astutils.h" #include "library.h" #include "platform.h" #include "settings.h" #include "symboldatabase.h" #include "token.h" #include "tokenize.h" #include "utils.h" #include "vfvalue.h" #include "checkother.h" // comparisonNonZeroExpressionLessThanZero and testIfNonZeroExpressionIsPositive #include <algorithm> #include <cstdint> #include <limits> #include <list> #include <set> #include <sstream> #include <utility> #include <vector> // CWE ids used static const CWE uncheckedErrorConditionCWE(391U); static const CWE CWE398(398U); // Indicator of Poor Code Quality static const CWE CWE570(570U); // Expression is Always False static const CWE CWE571(571U); // Expression is Always True //--------------------------------------------------------------------------- // Register this check class (by creating a static instance of it) namespace { CheckCondition instance; } bool CheckCondition::diag(const Token* tok, bool insert) { if (!tok) return false; const Token* parent = tok->astParent(); bool hasParent = false; while (Token::Match(parent, "!|&&|%oror%")) { if (mCondDiags.count(parent) != 0) { hasParent = true; break; } parent = parent->astParent(); } if (mCondDiags.count(tok) == 0 && !hasParent) { if (insert) mCondDiags.insert(tok); return false; } return true; } bool CheckCondition::isAliased(const std::set<int> &vars) const { for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (Token::Match(tok, "= & %var% ;") && vars.find(tok->tokAt(2)->varId()) != vars.end()) return true; } return false; } void CheckCondition::assignIf() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("assignIfError")) return; logChecker("CheckCondition::assignIf"); // style for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() != "=") continue; if (Token::Match(tok->tokAt(-2), "[;{}] %var% =")) { const Variable *var = tok->previous()->variable(); if (var == nullptr) continue; char bitop = '\0'; MathLib::bigint num = 0; if (Token::Match(tok->next(), "%num% [&|]")) { bitop = tok->strAt(2).at(0); num = MathLib::toBigNumber(tok->strAt(1)); } else { const Token *endToken = Token::findsimplematch(tok, ";"); // Casting address if (endToken && Token::Match(endToken->tokAt(-4), "* ) & %any% ;")) endToken = nullptr; if (endToken && Token::Match(endToken->tokAt(-2), "[&|] %num% ;")) { bitop = endToken->strAt(-2).at(0); num = MathLib::toBigNumber(endToken->strAt(-1)); } } if (bitop == '\0') continue; if (num < 0 && bitop == '|') continue; assignIfParseScope(tok, tok->tokAt(4), var->declarationId(), var->isLocal(), bitop, num); } } } static bool isParameterChanged(const Token *partok) { bool addressOf = Token::Match(partok, "[(,] &"); int argumentNumber = 0; const Token *ftok; for (ftok = partok; ftok && ftok->str() != "("; ftok = ftok->previous()) { if (ftok->str() == ")") ftok = ftok->link(); else if (argumentNumber == 0U && ftok->str() == "&") addressOf = true; else if (ftok->str() == ",") argumentNumber++; } ftok = ftok ? ftok->previous() : nullptr; if (!(ftok && ftok->function())) return true; const Variable *par = ftok->function()->getArgumentVar(argumentNumber); if (!par) return true; if (par->isConst()) return false; if (addressOf || par->isReference() || par->isPointer()) return true; return false; } /** parse scopes recursively */ bool CheckCondition::assignIfParseScope(const Token * const assignTok, const Token * const startTok, const nonneg int varid, const bool islocal, const char bitop, const MathLib::bigint num) { bool ret = false; for (const Token *tok2 = startTok; tok2; tok2 = tok2->next()) { if ((bitop == '&') && Token::Match(tok2->tokAt(2), "%varid% %cop% %num% ;", varid) && tok2->strAt(3) == std::string(1U, bitop)) { const MathLib::bigint num2 = MathLib::toBigNumber(tok2->strAt(4)); if (0 == (num & num2)) mismatchingBitAndError(assignTok, num, tok2, num2); } if (Token::Match(tok2, "%varid% =", varid)) { return true; } if (bitop == '&' && Token::Match(tok2, "%varid% &= %num% ;", varid)) { const MathLib::bigint num2 = MathLib::toBigNumber(tok2->strAt(2)); if (0 == (num & num2)) mismatchingBitAndError(assignTok, num, tok2, num2); } if (Token::Match(tok2, "++|-- %varid%", varid) || Token::Match(tok2, "%varid% ++|--", varid)) return true; if (Token::Match(tok2, "[(,] &| %varid% [,)]", varid) && isParameterChanged(tok2)) return true; if (tok2->str() == "}") return false; if (Token::Match(tok2, "break|continue|return")) ret = true; if (ret && tok2->str() == ";") return false; if (!islocal && Token::Match(tok2, "%name% (") && !Token::simpleMatch(tok2->linkAt(1), ") {")) return true; if (Token::Match(tok2, "if|while (")) { if (!islocal && tok2->str() == "while") continue; if (tok2->str() == "while") { // is variable changed in loop? const Token *bodyStart = tok2->linkAt(1)->next(); const Token *bodyEnd = bodyStart ? bodyStart->link() : nullptr; if (!bodyEnd || bodyEnd->str() != "}" || isVariableChanged(bodyStart, bodyEnd, varid, !islocal, *mSettings)) continue; } // parse condition const Token * const end = tok2->linkAt(1); for (; tok2 != end; tok2 = tok2->next()) { if (Token::Match(tok2, "[(,] &| %varid% [,)]", varid)) { return true; } if (Token::Match(tok2,"&&|%oror%|( %varid% ==|!= %num% &&|%oror%|)", varid)) { const Token *vartok = tok2->next(); const MathLib::bigint num2 = MathLib::toBigNumber(vartok->strAt(2)); if ((num & num2) != ((bitop=='&') ? num2 : num)) { const std::string& op(vartok->strAt(1)); const bool alwaysTrue = op == "!="; const std::string condition(vartok->str() + op + vartok->strAt(2)); assignIfError(assignTok, tok2, condition, alwaysTrue); } } if (Token::Match(tok2, "%varid% %op%", varid) && tok2->next()->isAssignmentOp()) { return true; } } const bool ret1 = assignIfParseScope(assignTok, end->tokAt(2), varid, islocal, bitop, num); bool ret2 = false; if (Token::simpleMatch(end->linkAt(1), "} else {")) ret2 = assignIfParseScope(assignTok, end->linkAt(1)->tokAt(3), varid, islocal, bitop, num); if (ret1 || ret2) return true; } } return false; } void CheckCondition::assignIfError(const Token *tok1, const Token *tok2, const std::string &condition, bool result) { if (tok2 && diag(tok2->tokAt(2))) return; std::list<const Token *> locations = { tok1, tok2 }; reportError(locations, Severity::style, "assignIfError", "Mismatching assignment and comparison, comparison '" + condition + "' is always " + std::string(bool_to_string(result)) + ".", CWE398, Certainty::normal); } void CheckCondition::mismatchingBitAndError(const Token *tok1, const MathLib::bigint num1, const Token *tok2, const MathLib::bigint num2) { std::list<const Token *> locations = { tok1, tok2 }; std::ostringstream msg; msg << "Mismatching bitmasks. Result is always 0 (" << "X = Y & 0x" << std::hex << num1 << "; Z = X & 0x" << std::hex << num2 << "; => Z=0)."; reportError(locations, Severity::style, "mismatchingBitAnd", msg.str(), CWE398, Certainty::normal); } static void getnumchildren(const Token *tok, std::list<MathLib::bigint> &numchildren) { if (tok->astOperand1() && tok->astOperand1()->isNumber()) numchildren.push_back(MathLib::toBigNumber(tok->astOperand1()->str())); else if (tok->astOperand1() && tok->str() == tok->astOperand1()->str()) getnumchildren(tok->astOperand1(), numchildren); if (tok->astOperand2() && tok->astOperand2()->isNumber()) numchildren.push_back(MathLib::toBigNumber(tok->astOperand2()->str())); else if (tok->astOperand2() && tok->str() == tok->astOperand2()->str()) getnumchildren(tok->astOperand2(), numchildren); } /* Return whether tok is in the body for a function returning a boolean. */ static bool inBooleanFunction(const Token *tok) { const Scope *scope = tok ? tok->scope() : nullptr; while (scope && scope->isLocal()) scope = scope->nestedIn; if (scope && scope->type == Scope::eFunction) { const Function *func = scope->function; if (func) { const Token *ret = func->retDef; while (Token::Match(ret, "static|const")) ret = ret->next(); return Token::Match(ret, "bool|_Bool"); } } return false; } static bool isOperandExpanded(const Token *tok) { if (tok->isExpandedMacro() || tok->isEnumerator()) return true; if (tok->astOperand1() && isOperandExpanded(tok->astOperand1())) return true; if (tok->astOperand2() && isOperandExpanded(tok->astOperand2())) return true; return false; } void CheckCondition::checkBadBitmaskCheck() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("badBitmaskCheck")) return; logChecker("CheckCondition::checkBadBitmaskCheck"); // style for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (tok->str() == "|" && tok->astOperand1() && tok->astOperand2() && tok->astParent()) { const Token* parent = tok->astParent(); const bool isBoolean = Token::Match(parent, "&&|%oror%") || (parent->str() == "?" && parent->astOperand1() == tok) || (parent->str() == "=" && parent->astOperand2() == tok && parent->astOperand1() && parent->astOperand1()->variable() && Token::Match(parent->astOperand1()->variable()->typeStartToken(), "bool|_Bool")) || (parent->str() == "(" && Token::Match(parent->astOperand1(), "if|while")) || (parent->str() == "return" && parent->astOperand1() == tok && inBooleanFunction(tok)); const bool isTrue = (tok->astOperand1()->hasKnownIntValue() && tok->astOperand1()->values().front().intvalue != 0) || (tok->astOperand2()->hasKnownIntValue() && tok->astOperand2()->values().front().intvalue != 0); if (isBoolean && isTrue) badBitmaskCheckError(tok); // If there are #ifdef in the expression don't warn about redundant | to avoid FP const auto& startStop = tok->findExpressionStartEndTokens(); if (mTokenizer->hasIfdef(startStop.first, startStop.second)) continue; const bool isZero1 = (tok->astOperand1()->hasKnownIntValue() && tok->astOperand1()->values().front().intvalue == 0); const bool isZero2 = (tok->astOperand2()->hasKnownIntValue() && tok->astOperand2()->values().front().intvalue == 0); if (!isZero1 && !isZero2) continue; if (!tok->isExpandedMacro() && !(isZero1 && isOperandExpanded(tok->astOperand1())) && !(isZero2 && isOperandExpanded(tok->astOperand2()))) badBitmaskCheckError(tok, /*isNoOp*/ true); } } } void CheckCondition::badBitmaskCheckError(const Token *tok, bool isNoOp) { if (isNoOp) reportError(tok, Severity::style, "badBitmaskCheck", "Operator '|' with one operand equal to zero is redundant.", CWE571, Certainty::normal); else reportError(tok, Severity::warning, "badBitmaskCheck", "Result of operator '|' is always true if one operand is non-zero. Did you intend to use '&'?", CWE571, Certainty::normal); } void CheckCondition::comparison() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("comparisonError")) return; logChecker("CheckCondition::comparison"); // style for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (!tok->isComparisonOp()) continue; const Token *expr1 = tok->astOperand1(); const Token *expr2 = tok->astOperand2(); if (!expr1 || !expr2) continue; if (expr1->isNumber()) std::swap(expr1,expr2); if (!expr2->isNumber()) continue; if (!compareTokenFlags(expr1, expr2, /*macro*/ true)) continue; const MathLib::bigint num2 = MathLib::toBigNumber(expr2->str()); if (num2 < 0) continue; if (!Token::Match(expr1,"[&|]")) continue; std::list<MathLib::bigint> numbers; getnumchildren(expr1, numbers); for (const MathLib::bigint num1 : numbers) { if (num1 < 0) continue; if (Token::Match(tok, "==|!=")) { if ((expr1->str() == "&" && (num1 & num2) != num2) || (expr1->str() == "|" && (num1 | num2) != num2)) { const std::string& op(tok->str()); comparisonError(expr1, expr1->str(), num1, op, num2, op != "=="); } } else if (expr1->str() == "&") { const bool or_equal = Token::Match(tok, ">=|<="); const std::string& op(tok->str()); if ((Token::Match(tok, ">=|<")) && (num1 < num2)) { comparisonError(expr1, expr1->str(), num1, op, num2, !or_equal); } else if ((Token::Match(tok, "<=|>")) && (num1 <= num2)) { comparisonError(expr1, expr1->str(), num1, op, num2, or_equal); } } else if (expr1->str() == "|") { if ((expr1->astOperand1()->valueType()) && (expr1->astOperand1()->valueType()->sign == ValueType::Sign::UNSIGNED)) { const bool or_equal = Token::Match(tok, ">=|<="); const std::string& op(tok->str()); if ((Token::Match(tok, ">=|<")) && (num1 >= num2)) { //"(a | 0x07) >= 7U" is always true for unsigned a //"(a | 0x07) < 7U" is always false for unsigned a comparisonError(expr1, expr1->str(), num1, op, num2, or_equal); } else if ((Token::Match(tok, "<=|>")) && (num1 > num2)) { //"(a | 0x08) <= 7U" is always false for unsigned a //"(a | 0x07) > 6U" is always true for unsigned a comparisonError(expr1, expr1->str(), num1, op, num2, !or_equal); } } } } } } void CheckCondition::comparisonError(const Token *tok, const std::string &bitop, MathLib::bigint value1, const std::string &op, MathLib::bigint value2, bool result) { std::ostringstream expression; expression << std::hex << "(X " << bitop << " 0x" << value1 << ") " << op << " 0x" << value2; const std::string errmsg("Expression '" + expression.str() + "' is always " + bool_to_string(result) + ".\n" "The expression '" + expression.str() + "' is always " + bool_to_string(result) + ". Check carefully constants and operators used, these errors might be hard to " "spot sometimes. In case of complex expression it might help to split it to " "separate expressions."); reportError(tok, Severity::style, "comparisonError", errmsg, CWE398, Certainty::normal); } bool CheckCondition::isOverlappingCond(const Token * const cond1, const Token * const cond2, bool pure) const { if (!cond1 || !cond2) return false; // same expressions if (isSameExpression(true, cond1, cond2, *mSettings, pure, false)) return true; // bitwise overlap for example 'x&7' and 'x==1' if (cond1->str() == "&" && cond1->astOperand1() && cond2->astOperand2()) { const Token *expr1 = cond1->astOperand1(); const Token *num1 = cond1->astOperand2(); if (!num1) // unary operator& return false; if (!num1->isNumber()) std::swap(expr1,num1); if (!num1->isNumber() || MathLib::isNegative(num1->str())) return false; if (!Token::Match(cond2, "&|==") || !cond2->astOperand1() || !cond2->astOperand2()) return false; const Token *expr2 = cond2->astOperand1(); const Token *num2 = cond2->astOperand2(); if (!num2->isNumber()) std::swap(expr2,num2); if (!num2->isNumber() || MathLib::isNegative(num2->str())) return false; if (!isSameExpression(true, expr1, expr2, *mSettings, pure, false)) return false; const MathLib::bigint value1 = MathLib::toBigNumber(num1->str()); const MathLib::bigint value2 = MathLib::toBigNumber(num2->str()); if (cond2->str() == "&") return ((value1 & value2) == value2); return ((value1 & value2) > 0); } return false; } void CheckCondition::duplicateCondition() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("duplicateCondition")) return; logChecker("CheckCondition::duplicateCondition"); // style const SymbolDatabase *const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eIf) continue; const Token* tok2 = scope.classDef->next(); if (!tok2) continue; const Token* cond1 = tok2->astOperand2(); if (!cond1) continue; if (cond1->hasKnownIntValue()) continue; tok2 = tok2->link(); if (!Token::simpleMatch(tok2, ") {")) continue; tok2 = tok2->linkAt(1); if (!Token::simpleMatch(tok2, "} if (")) continue; const Token *cond2 = tok2->tokAt(2)->astOperand2(); if (!cond2) continue; ErrorPath errorPath; if (!findExpressionChanged(cond1, scope.classDef->next(), cond2, *mSettings) && isSameExpression(true, cond1, cond2, *mSettings, true, true, &errorPath)) duplicateConditionError(cond1, cond2, std::move(errorPath)); } } void CheckCondition::duplicateConditionError(const Token *tok1, const Token *tok2, ErrorPath errorPath) { if (diag(tok1) & diag(tok2)) return; errorPath.emplace_back(tok1, "First condition"); errorPath.emplace_back(tok2, "Second condition"); std::string msg = "The if condition is the same as the previous if condition"; reportError(errorPath, Severity::style, "duplicateCondition", msg, CWE398, Certainty::normal); } void CheckCondition::multiCondition() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("multiCondition")) return; logChecker("CheckCondition::multiCondition"); // style const SymbolDatabase* const symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { if (scope.type != Scope::eIf) continue; const Token * const cond1 = scope.classDef->next()->astOperand2(); if (!cond1) continue; const Token * tok2 = scope.classDef->next(); // Check each 'else if' for (;;) { tok2 = tok2->link(); if (!Token::simpleMatch(tok2, ") {")) break; tok2 = tok2->linkAt(1); if (!Token::simpleMatch(tok2, "} else { if (")) break; tok2 = tok2->tokAt(4); if (tok2->astOperand2()) { ErrorPath errorPath; if (isOverlappingCond(cond1, tok2->astOperand2(), true) && !findExpressionChanged(cond1, cond1, tok2->astOperand2(), *mSettings)) overlappingElseIfConditionError(tok2->astOperand2(), cond1->linenr()); else if (isOppositeCond( true, cond1, tok2->astOperand2(), *mSettings, true, true, &errorPath) && !findExpressionChanged(cond1, cond1, tok2->astOperand2(), *mSettings)) oppositeElseIfConditionError(cond1, tok2->astOperand2(), std::move(errorPath)); } } } } void CheckCondition::overlappingElseIfConditionError(const Token *tok, nonneg int line1) { if (diag(tok)) return; std::ostringstream errmsg; errmsg << "Expression is always false because 'else if' condition matches previous condition at line " << line1 << "."; reportError(tok, Severity::style, "multiCondition", errmsg.str(), CWE398, Certainty::normal); } void CheckCondition::oppositeElseIfConditionError(const Token *ifCond, const Token *elseIfCond, ErrorPath errorPath) { if (diag(ifCond) & diag(elseIfCond)) return; std::ostringstream errmsg; errmsg << "Expression is always true because 'else if' condition is opposite to previous condition at line " << ifCond->linenr() << "."; errorPath.emplace_back(ifCond, "first condition"); errorPath.emplace_back(elseIfCond, "else if condition is opposite to first condition"); reportError(errorPath, Severity::style, "multiCondition", errmsg.str(), CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // - Opposite inner conditions => always false // - (TODO) Same/Overlapping inner condition => always true // - same condition after early exit => always false //--------------------------------------------------------------------------- static bool isNonConstFunctionCall(const Token *ftok, const Library &library) { if (library.isFunctionConst(ftok)) return false; const Token *obj = ftok->next()->astOperand1(); while (obj && obj->str() == ".") obj = obj->astOperand1(); if (!obj) return true; if (obj->variable() && obj->variable()->isConst()) return false; if (ftok->function() && ftok->function()->isConst()) return false; return true; } void CheckCondition::multiCondition2() { if (!mSettings->severity.isEnabled(Severity::warning) && !mSettings->isPremiumEnabled("identicalConditionAfterEarlyExit") && !mSettings->isPremiumEnabled("identicalInnerCondition")) return; logChecker("CheckCondition::multiCondition2"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope &scope : symbolDatabase->scopeList) { const Token *condTok = nullptr; if (scope.type == Scope::eIf || scope.type == Scope::eWhile) condTok = scope.classDef->next()->astOperand2(); else if (scope.type == Scope::eFor) { condTok = scope.classDef->next()->astOperand2(); if (!condTok || condTok->str() != ";") continue; condTok = condTok->astOperand2(); if (!condTok || condTok->str() != ";") continue; condTok = condTok->astOperand1(); } if (!condTok) continue; const Token * const cond1 = condTok; if (!Token::simpleMatch(scope.classDef->linkAt(1), ") {")) continue; bool functionCall = false; bool nonConstFunctionCall = false; bool nonlocal = false; // nonlocal variable used in condition std::set<int> vars; // variables used in condition visitAstNodes(condTok, [&](const Token *cond) { if (Token::Match(cond, "%name% (")) { functionCall = true; nonConstFunctionCall = isNonConstFunctionCall(cond, mSettings->library); if (nonConstFunctionCall) return ChildrenToVisit::done; } if (cond->varId()) { vars.insert(cond->varId()); const Variable *var = cond->variable(); if (!nonlocal && var) { if (!(var->isLocal() || var->isArgument())) nonlocal = true; else if ((var->isPointer() || var->isReference()) && !Token::Match(cond->astParent(), "%oror%|&&|!")) // TODO: if var is pointer check what it points at nonlocal = true; } } else if (!nonlocal && cond->isName()) { // varid is 0. this is possibly a nonlocal variable.. nonlocal = Token::Match(cond->astParent(), "%cop%|(|[") || Token::Match(cond, "%name% .") || (cond->isCpp() && cond->str() == "this"); } else { return ChildrenToVisit::op1_and_op2; } return ChildrenToVisit::none; }); if (nonConstFunctionCall) continue; std::vector<const Variable*> varsInCond; visitAstNodes(condTok, [&varsInCond](const Token *cond) { if (cond->variable()) { const Variable *var = cond->variable(); if (std::find(varsInCond.cbegin(), varsInCond.cend(), var) == varsInCond.cend()) varsInCond.push_back(var); } return ChildrenToVisit::op1_and_op2; }); // parse until second condition is reached.. enum MULTICONDITIONTYPE : std::uint8_t { INNER, AFTER }; const Token *tok; // Parse inner condition first and then early return condition std::vector<MULTICONDITIONTYPE> types = {MULTICONDITIONTYPE::INNER}; if (Token::Match(scope.bodyStart, "{ return|throw|continue|break")) types.push_back(MULTICONDITIONTYPE::AFTER); for (const MULTICONDITIONTYPE type:types) { if (type == MULTICONDITIONTYPE::AFTER) { tok = scope.bodyEnd->next(); } else { tok = scope.bodyStart; } const Token * const endToken = tok->scope()->bodyEnd; for (; tok && tok != endToken; tok = tok->next()) { if (isExpressionChangedAt(cond1, tok, 0, false, *mSettings)) break; if (Token::Match(tok, "if|return")) { const Token * condStartToken = tok->str() == "if" ? tok->next() : tok; const Token * condEndToken = tok->str() == "if" ? condStartToken->link() : Token::findsimplematch(condStartToken, ";"); // Does condition modify tracked variables? if (findExpressionChanged(cond1, condStartToken, condEndToken, *mSettings)) break; // Condition.. const Token *cond2 = tok->str() == "if" ? condStartToken->astOperand2() : condStartToken->astOperand1(); const bool isReturnVar = (tok->str() == "return" && (!Token::Match(cond2, "%cop%") || (cond2 && cond2->isUnaryOp("!")))); ErrorPath errorPath; if (type == MULTICONDITIONTYPE::INNER) { visitAstNodes(cond1, [&](const Token* firstCondition) { if (!firstCondition) return ChildrenToVisit::none; if (firstCondition->str() == "&&") { if (!isOppositeCond(false, firstCondition, cond2, *mSettings, true, true)) return ChildrenToVisit::op1_and_op2; } if (!firstCondition->hasKnownIntValue()) { if (!isReturnVar && isOppositeCond(false, firstCondition, cond2, *mSettings, true, true, &errorPath)) { if (!isAliased(vars)) oppositeInnerConditionError(firstCondition, cond2, errorPath); } else if (!isReturnVar && isSameExpression(true, firstCondition, cond2, *mSettings, true, true, &errorPath)) { identicalInnerConditionError(firstCondition, cond2, errorPath); } } return ChildrenToVisit::none; }); } else { visitAstNodes(cond2, [&](const Token *secondCondition) { if (secondCondition->str() == "||" || secondCondition->str() == "&&") return ChildrenToVisit::op1_and_op2; if ((!cond1->hasKnownIntValue() || !secondCondition->hasKnownIntValue()) && isSameExpression(true, cond1, secondCondition, *mSettings, true, true, &errorPath)) { if (!isAliased(vars) && !mTokenizer->hasIfdef(cond1, secondCondition)) { identicalConditionAfterEarlyExitError(cond1, secondCondition, errorPath); return ChildrenToVisit::done; } } return ChildrenToVisit::none; }); } } if (Token::Match(tok, "%name% (") && isVariablesChanged(tok, tok->linkAt(1), 0, varsInCond, *mSettings)) { break; } if (Token::Match(tok, "%type% (") && nonlocal && isNonConstFunctionCall(tok, mSettings->library)) // non const function call -> bailout if there are nonlocal variables break; if (Token::Match(tok, "case|break|continue|return|throw") && tok->scope() == endToken->scope()) break; if (Token::Match(tok, "[;{}] %name% :")) break; // bailout if loop is seen. // TODO: handle loops better. if (Token::Match(tok, "for|while|do")) { const Token *tok1 = tok->next(); const Token *tok2; if (Token::simpleMatch(tok, "do {")) { if (!Token::simpleMatch(tok->linkAt(1), "} while (")) break; tok2 = tok->linkAt(1)->linkAt(2); } else if (Token::Match(tok, "if|while (")) { tok2 = tok->linkAt(1); if (Token::simpleMatch(tok2, ") {")) tok2 = tok2->linkAt(1); if (!tok2) break; } else { // Incomplete code break; } const bool changed = std::any_of(vars.cbegin(), vars.cend(), [&](int varid) { return isVariableChanged(tok1, tok2, varid, nonlocal, *mSettings); }); if (changed) break; } if ((tok->varId() && vars.find(tok->varId()) != vars.end()) || (!tok->varId() && nonlocal) || (functionCall && tok->variable() && !tok->variable()->isLocal())) { if (Token::Match(tok, "%name% %assign%|++|--")) break; if (Token::Match(tok->astParent(), "*|.|[")) { const Token *parent = tok; while (Token::Match(parent->astParent(), ".|[") || (parent->astParent() && parent->astParent()->isUnaryOp("*"))) parent = parent->astParent(); if (Token::Match(parent->astParent(), "%assign%|++|--")) break; } if (tok->isCpp() && Token::Match(tok, "%name% <<") && (!tok->valueType() || !tok->valueType()->isIntegral())) break; if (isLikelyStreamRead(tok->next()) || isLikelyStreamRead(tok->previous())) break; if (Token::Match(tok, "%name% [")) { const Token *tok2 = tok->linkAt(1); while (Token::simpleMatch(tok2, "] [")) tok2 = tok2->linkAt(1); if (Token::Match(tok2, "] %assign%|++|--")) break; } if (Token::Match(tok->previous(), "++|--|& %name%")) break; if (tok->variable() && !tok->variable()->isConst() && Token::Match(tok, "%name% . %name% (")) { const Function* function = tok->tokAt(2)->function(); if (!function || !function->isConst()) break; } if (Token::Match(tok->previous(), "[(,] *|& %name% [,)]") && isParameterChanged(tok)) break; } } } } } static std::string innerSmtString(const Token * tok) { if (!tok) return "if"; const Token * top = tok->astTop(); if (top->str() == "(" && top->astOperand1()) return top->astOperand1()->str(); return top->str(); } void CheckCondition::oppositeInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath) { if (diag(tok1) & diag(tok2)) return; const std::string s1(tok1 ? tok1->expressionString() : "x"); const std::string s2(tok2 ? tok2->expressionString() : "!x"); const std::string innerSmt = innerSmtString(tok2); errorPath.emplace_back(tok1, "outer condition: " + s1); errorPath.emplace_back(tok2, "opposite inner condition: " + s2); const std::string msg("Opposite inner '" + innerSmt + "' condition leads to a dead code block.\n" "Opposite inner '" + innerSmt + "' condition leads to a dead code block (outer condition is '" + s1 + "' and inner condition is '" + s2 + "')."); reportError(errorPath, Severity::warning, "oppositeInnerCondition", msg, CWE398, Certainty::normal); } void CheckCondition::identicalInnerConditionError(const Token *tok1, const Token* tok2, ErrorPath errorPath) { if (diag(tok1) & diag(tok2)) return; const std::string s1(tok1 ? tok1->expressionString() : "x"); const std::string s2(tok2 ? tok2->expressionString() : "x"); const std::string innerSmt = innerSmtString(tok2); errorPath.emplace_back(tok1, "outer condition: " + s1); errorPath.emplace_back(tok2, "identical inner condition: " + s2); const std::string msg("Identical inner '" + innerSmt + "' condition is always true.\n" "Identical inner '" + innerSmt + "' condition is always true (outer condition is '" + s1 + "' and inner condition is '" + s2 + "')."); reportError(errorPath, Severity::warning, "identicalInnerCondition", msg, CWE398, Certainty::normal); } void CheckCondition::identicalConditionAfterEarlyExitError(const Token *cond1, const Token* cond2, ErrorPath errorPath) { if (diag(cond1) & diag(cond2)) return; const bool isReturnValue = cond2 && Token::simpleMatch(cond2->astParent(), "return"); const std::string cond(cond1 ? cond1->expressionString() : "x"); const std::string value = (cond2 && cond2->valueType() && cond2->valueType()->type == ValueType::Type::BOOL) ? "false" : "0"; errorPath.emplace_back(cond1, "If condition '" + cond + "' is true, the function will return/exit"); errorPath.emplace_back(cond2, (isReturnValue ? "Returning identical expression '" : "Testing identical condition '") + cond + "'"); reportError(errorPath, Severity::warning, "identicalConditionAfterEarlyExit", isReturnValue ? ("Identical condition and return expression '" + cond + "', return value is always " + value) : ("Identical condition '" + cond + "', second condition is always false"), CWE398, Certainty::normal); } //--------------------------------------------------------------------------- // if ((x != 1) || (x != 3)) // expression always true // if ((x == 1) && (x == 3)) // expression always false // if ((x < 1) && (x > 3)) // expression always false // if ((x > 3) || (x < 10)) // expression always true // if ((x > 5) && (x != 1)) // second comparison always true // // Check for suspect logic for an expression consisting of 2 comparison // expressions with a shared variable and constants and a logical operator // between them. // // Suggest a different logical operator when the logical operator between // the comparisons is probably wrong. // // Inform that second comparison is always true when first comparison is true. //--------------------------------------------------------------------------- static std::string invertOperatorForOperandSwap(std::string s) { if (s[0] == '<') s[0] = '>'; else if (s[0] == '>') s[0] = '<'; return s; } template<typename T> static int sign(const T v) { return static_cast<int>(v > 0) - static_cast<int>(v < 0); } // returns 1 (-1) if the first (second) condition is sufficient, 0 if indeterminate template<typename T> static int sufficientCondition(std::string op1, const bool not1, const T value1, std::string op2, const bool not2, const T value2, const bool isAnd) { auto transformOp = [](std::string& op, const bool invert) { if (invert) { if (op == "==") op = "!="; else if (op == "!=") op = "=="; else if (op == "<") op = ">="; else if (op == ">") op = "<="; else if (op == "<=") op = ">"; else if (op == ">=") op = "<"; } }; transformOp(op1, not1); transformOp(op2, not2); int res = 0; bool equal = false; if (op1 == op2) { equal = true; if (op1 == ">" || op1 == ">=") res = sign(value1 - value2); else if (op1 == "<" || op1 == "<=") res = -sign(value1 - value2); } else { // not equal if (op1 == "!=") res = 1; else if (op2 == "!=") res = -1; else if (op1 == "==") res = -1; else if (op2 == "==") res = 1; else if (op1 == ">" && op2 == ">=") res = sign(value1 - (value2 - 1)); else if (op1 == ">=" && op2 == ">") res = sign((value1 - 1) - value2); else if (op1 == "<" && op2 == "<=") res = -sign(value1 - (value2 + 1)); else if (op1 == "<=" && op2 == "<") res = -sign((value1 + 1) - value2); } return res * (isAnd == equal ? 1 : -1); } template<typename T> static bool checkIntRelation(const std::string &op, const T value1, const T value2) { return (op == "==" && value1 == value2) || (op == "!=" && value1 != value2) || (op == ">" && value1 > value2) || (op == ">=" && value1 >= value2) || (op == "<" && value1 < value2) || (op == "<=" && value1 <= value2); } static bool checkFloatRelation(const std::string &op, const double value1, const double value2) { return (op == ">" && value1 > value2) || (op == ">=" && value1 >= value2) || (op == "<" && value1 < value2) || (op == "<=" && value1 <= value2); } template<class T> static T getvalue3(const T value1, const T value2) { const T min = std::min(value1, value2); if (min== std::numeric_limits<T>::max()) return min; return min + 1; // see #5895 } template<> double getvalue3(const double value1, const double value2) { return (value1 + value2) / 2.0; } template<class T> static inline T getvalue(const int test, const T value1, const T value2) { // test: // 1 => return value that is less than both value1 and value2 // 2 => return value1 // 3 => return value that is between value1 and value2 // 4 => return value2 // 5 => return value that is larger than both value1 and value2 switch (test) { case 1: return std::numeric_limits<T>::lowest(); case 2: return value1; case 3: return getvalue3<T>(value1, value2); case 4: return value2; case 5: return std::numeric_limits<T>::max(); } return 0; } static bool parseComparison(const Token *comp, bool &not1, std::string &op, std::string &value, const Token *&expr, bool &inconclusive) { not1 = false; while (comp && comp->str() == "!") { not1 = !(not1); comp = comp->astOperand1(); } if (!comp) return false; const Token* op1 = comp->astOperand1(); const Token* op2 = comp->astOperand2(); if (!comp->isComparisonOp() || !op1 || !op2) { op = "!="; value = "0"; expr = comp; } else if (op1->isLiteral()) { if (op1->isExpandedMacro()) return false; op = invertOperatorForOperandSwap(comp->str()); if (op1->enumerator() && op1->enumerator()->value_known) value = std::to_string(op1->enumerator()->value); else value = op1->str(); expr = op2; } else if (comp->astOperand2()->isLiteral()) { if (op2->isExpandedMacro()) return false; op = comp->str(); if (op2->enumerator() && op2->enumerator()->value_known) value = std::to_string(op2->enumerator()->value); else value = op2->str(); expr = op1; } else { op = "!="; value = "0"; expr = comp; } inconclusive = inconclusive || ((value)[0] == '\'' && !(op == "!=" || op == "==")); // Only float and int values are currently handled return MathLib::isInt(value) || MathLib::isFloat(value) || (value[0] == '\''); } static std::string conditionString(bool not1, const Token *expr1, const std::string &op, const std::string &value1) { if (expr1->astParent()->isComparisonOp()) return std::string(not1 ? "!(" : "") + expr1->expressionString() + " " + op + " " + value1 + (not1 ? ")" : ""); return std::string(not1 ? "!" : "") + expr1->expressionString(); } static std::string conditionString(const Token * tok) { if (!tok) return ""; if (tok->isComparisonOp()) { bool inconclusive = false; bool not_; std::string op, value; const Token *expr; if (parseComparison(tok, not_, op, value, expr, inconclusive) && expr->isName()) { return conditionString(not_, expr, op, value); } } if (Token::Match(tok, "%cop%|&&|%oror%")) { if (tok->astOperand2()) return conditionString(tok->astOperand1()) + " " + tok->str() + " " + conditionString(tok->astOperand2()); return tok->str() + "(" + conditionString(tok->astOperand1()) + ")"; } return tok->expressionString(); } static bool isIfConstexpr(const Token* tok) { const Token* const top = tok->astTop(); return Token::simpleMatch(top->astOperand1(), "if") && top->astOperand1()->isConstexpr(); } void CheckCondition::checkIncorrectLogicOperator() { const bool printStyle = mSettings->severity.isEnabled(Severity::style); const bool printWarning = mSettings->severity.isEnabled(Severity::warning); if (!printWarning && !printStyle && !mSettings->isPremiumEnabled("incorrectLogicOperator")) return; const bool printInconclusive = mSettings->certainty.isEnabled(Certainty::inconclusive); logChecker("CheckCondition::checkIncorrectLogicOperator"); // style,warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!Token::Match(tok, "%oror%|&&") || !tok->astOperand1() || !tok->astOperand2()) continue; // 'A && (!A || B)' is equivalent to 'A && B' // 'A || (!A && B)' is equivalent to 'A || B' // 'A && (A || B)' is equivalent to 'A' // 'A || (A && B)' is equivalent to 'A' if (printStyle && ((tok->str() == "||" && tok->astOperand2()->str() == "&&") || (tok->str() == "&&" && tok->astOperand2()->str() == "||"))) { const Token* tok2 = tok->astOperand2()->astOperand1(); if (isOppositeCond(true, tok->astOperand1(), tok2, *mSettings, true, false)) { std::string expr1(tok->astOperand1()->expressionString()); std::string expr2(tok->astOperand2()->astOperand1()->expressionString()); std::string expr3(tok->astOperand2()->astOperand2()->expressionString()); // make copy for later because the original string might get overwritten const std::string expr1VerboseMsg = expr1; const std::string expr2VerboseMsg = expr2; const std::string expr3VerboseMsg = expr3; if (expr1.length() + expr2.length() + expr3.length() > 50U) { if (expr1[0] == '!' && expr2[0] != '!') { expr1 = "!A"; expr2 = "A"; } else { expr1 = "A"; expr2 = "!A"; } expr3 = "B"; } const std::string cond1 = expr1 + " " + tok->str() + " (" + expr2 + " " + tok->astOperand2()->str() + " " + expr3 + ")"; const std::string cond2 = expr1 + " " + tok->str() + " " + expr3; const std::string cond1VerboseMsg = expr1VerboseMsg + " " + tok->str() + " " + expr2VerboseMsg + " " + tok->astOperand2()->str() + " " + expr3VerboseMsg; const std::string cond2VerboseMsg = expr1VerboseMsg + " " + tok->str() + " " + expr3VerboseMsg; // for the --verbose message, transform the actual condition and print it const std::string msg = tok2->expressionString() + ". '" + cond1 + "' is equivalent to '" + cond2 + "'\n" "The condition '" + cond1VerboseMsg + "' is equivalent to '" + cond2VerboseMsg + "'."; redundantConditionError(tok, msg, false); continue; } if (isSameExpression(false, tok->astOperand1(), tok2, *mSettings, true, true)) { std::string expr1(tok->astOperand1()->expressionString()); std::string expr2(tok->astOperand2()->astOperand1()->expressionString()); std::string expr3(tok->astOperand2()->astOperand2()->expressionString()); // make copy for later because the original string might get overwritten const std::string expr1VerboseMsg = expr1; const std::string expr2VerboseMsg = expr2; const std::string expr3VerboseMsg = expr3; if (expr1.length() + expr2.length() + expr3.length() > 50U) { expr1 = "A"; expr2 = "A"; expr3 = "B"; } const std::string cond1 = expr1 + " " + tok->str() + " (" + expr2 + " " + tok->astOperand2()->str() + " " + expr3 + ")"; const std::string cond2 = std::move(expr1); const std::string cond1VerboseMsg = expr1VerboseMsg + " " + tok->str() + " " + expr2VerboseMsg + " " + tok->astOperand2()->str() + " " + expr3VerboseMsg; const std::string& cond2VerboseMsg = expr1VerboseMsg; // for the --verbose message, transform the actual condition and print it const std::string msg = tok2->expressionString() + ". '" + cond1 + "' is equivalent to '" + cond2 + "'\n" "The condition '" + cond1VerboseMsg + "' is equivalent to '" + cond2VerboseMsg + "'."; redundantConditionError(tok, msg, false); continue; } } // Comparison #1 (LHS) const Token *comp1 = tok->astOperand1(); if (comp1->str() == tok->str()) comp1 = comp1->astOperand2(); // Comparison #2 (RHS) const Token *comp2 = tok->astOperand2(); bool inconclusive = false; bool parseable = true; // Parse LHS bool not1; std::string op1, value1; const Token *expr1 = nullptr; parseable &= (parseComparison(comp1, not1, op1, value1, expr1, inconclusive)); // Parse RHS bool not2; std::string op2, value2; const Token *expr2 = nullptr; parseable &= (parseComparison(comp2, not2, op2, value2, expr2, inconclusive)); if (inconclusive && !printInconclusive) continue; const bool isUnknown = (expr1 && expr1->valueType() && expr1->valueType()->type == ValueType::UNKNOWN_TYPE) || (expr2 && expr2->valueType() && expr2->valueType()->type == ValueType::UNKNOWN_TYPE); if (isUnknown) continue; const bool isfloat = astIsFloat(expr1, true) || MathLib::isFloat(value1) || astIsFloat(expr2, true) || MathLib::isFloat(value2); ErrorPath errorPath; // Opposite comparisons around || or && => always true or always false const bool isLogicalOr(tok->str() == "||"); if (!isfloat && isOppositeCond(isLogicalOr, tok->astOperand1(), tok->astOperand2(), *mSettings, true, true, &errorPath)) { if (!isIfConstexpr(tok)) { const bool alwaysTrue(isLogicalOr); incorrectLogicOperatorError(tok, conditionString(tok), alwaysTrue, inconclusive, errorPath); } continue; } if (!parseable) continue; if (isSameExpression(true, comp1, comp2, *mSettings, true, true)) continue; // same expressions => only report that there are same expressions if (!isSameExpression(true, expr1, expr2, *mSettings, true, true)) continue; // don't check floating point equality comparisons. that is bad // and deserves different warnings. if (isfloat && (op1 == "==" || op1 == "!=" || op2 == "==" || op2 == "!=")) continue; const double d1 = (isfloat) ? MathLib::toDoubleNumber(value1) : 0; const double d2 = (isfloat) ? MathLib::toDoubleNumber(value2) : 0; const MathLib::bigint i1 = (isfloat) ? 0 : MathLib::toBigNumber(value1); const MathLib::bigint i2 = (isfloat) ? 0 : MathLib::toBigNumber(value2); const bool useUnsignedInt = (std::numeric_limits<MathLib::bigint>::max()==i1) || (std::numeric_limits<MathLib::bigint>::max()==i2); const MathLib::biguint u1 = (useUnsignedInt) ? MathLib::toBigNumber(value1) : 0; const MathLib::biguint u2 = (useUnsignedInt) ? MathLib::toBigNumber(value2) : 0; // evaluate if expression is always true/false bool alwaysTrue = true, alwaysFalse = true; bool firstTrue = true, secondTrue = true; const bool isAnd = tok->str() == "&&"; for (int test = 1; test <= 5; ++test) { // test: // 1 => testvalue is less than both value1 and value2 // 2 => testvalue is value1 // 3 => testvalue is between value1 and value2 // 4 => testvalue value2 // 5 => testvalue is larger than both value1 and value2 bool result1, result2; if (isfloat) { const auto testvalue = getvalue<double>(test, d1, d2); result1 = checkFloatRelation(op1, testvalue, d1); result2 = checkFloatRelation(op2, testvalue, d2); } else if (useUnsignedInt) { const auto testvalue = getvalue<MathLib::biguint>(test, u1, u2); result1 = checkIntRelation(op1, testvalue, u1); result2 = checkIntRelation(op2, testvalue, u2); } else { const auto testvalue = getvalue<MathLib::bigint>(test, i1, i2); result1 = checkIntRelation(op1, testvalue, i1); result2 = checkIntRelation(op2, testvalue, i2); } if (not1) result1 = !result1; if (not2) result2 = !result2; if (isAnd) { alwaysTrue &= (result1 && result2); alwaysFalse &= !(result1 && result2); } else { alwaysTrue &= (result1 || result2); alwaysFalse &= !(result1 || result2); } firstTrue &= !(!result1 && result2); secondTrue &= !(result1 && !result2); } const std::string cond1str = conditionString(not1, expr1, op1, value1); const std::string cond2str = conditionString(not2, expr2, op2, value2); if (printWarning && (alwaysTrue || alwaysFalse)) { const std::string text = cond1str + " " + tok->str() + " " + cond2str; incorrectLogicOperatorError(tok, text, alwaysTrue, inconclusive, std::move(errorPath)); } else if (printStyle && (firstTrue || secondTrue)) { // cppcheck-suppress accessMoved - TODO: FP - see #12174 const int which = isfloat ? sufficientCondition(std::move(op1), not1, d1, std::move(op2), not2, d2, isAnd) : sufficientCondition(std::move(op1), not1, i1, std::move(op2), not2, i2, isAnd); std::string text; if (which != 0) { text = "The condition '" + (which == 1 ? cond2str : cond1str) + "' is redundant since '" + (which == 1 ? cond1str : cond2str) + "' is sufficient."; } else text = "If '" + (secondTrue ? cond1str : cond2str) + "', the comparison '" + (secondTrue ? cond2str : cond1str) + "' is always true."; redundantConditionError(tok, text, inconclusive); } } } } void CheckCondition::incorrectLogicOperatorError(const Token *tok, const std::string &condition, bool always, bool inconclusive, ErrorPath errors) { if (diag(tok)) return; errors.emplace_back(tok, ""); if (always) reportError(errors, Severity::warning, "incorrectLogicOperator", "Logical disjunction always evaluates to true: " + condition + ".\n" "Logical disjunction always evaluates to true: " + condition + ". " "Are these conditions necessary? Did you intend to use && instead? Are the numbers correct? Are you comparing the correct variables?", CWE571, inconclusive ? Certainty::inconclusive : Certainty::normal); else reportError(errors, Severity::warning, "incorrectLogicOperator", "Logical conjunction always evaluates to false: " + condition + ".\n" "Logical conjunction always evaluates to false: " + condition + ". " "Are these conditions necessary? Did you intend to use || instead? Are the numbers correct? Are you comparing the correct variables?", CWE570, inconclusive ? Certainty::inconclusive : Certainty::normal); } void CheckCondition::redundantConditionError(const Token *tok, const std::string &text, bool inconclusive) { if (diag(tok)) return; reportError(tok, Severity::style, "redundantCondition", "Redundant condition: " + text, CWE398, inconclusive ? Certainty::inconclusive : Certainty::normal); } //----------------------------------------------------------------------------- // Detect "(var % val1) > val2" where val2 is >= val1. //----------------------------------------------------------------------------- void CheckCondition::checkModuloAlwaysTrueFalse() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckCondition::checkModuloAlwaysTrueFalse"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp()) continue; const Token *num, *modulo; if (Token::simpleMatch(tok->astOperand1(), "%") && Token::Match(tok->astOperand2(), "%num%")) { modulo = tok->astOperand1(); num = tok->astOperand2(); } else if (Token::Match(tok->astOperand1(), "%num%") && Token::simpleMatch(tok->astOperand2(), "%")) { num = tok->astOperand1(); modulo = tok->astOperand2(); } else { continue; } if (Token::Match(modulo->astOperand2(), "%num%") && MathLib::isLessEqual(modulo->astOperand2()->str(), num->str())) moduloAlwaysTrueFalseError(tok, modulo->astOperand2()->str()); } } } void CheckCondition::moduloAlwaysTrueFalseError(const Token* tok, const std::string& maxVal) { if (diag(tok)) return; reportError(tok, Severity::warning, "moduloAlwaysTrueFalse", "Comparison of modulo result is predetermined, because it is always less than " + maxVal + ".", CWE398, Certainty::normal); } static int countPar(const Token *tok1, const Token *tok2) { int par = 0; for (const Token *tok = tok1; tok && tok != tok2; tok = tok->next()) { if (tok->str() == "(") ++par; else if (tok->str() == ")") --par; else if (tok->str() == ";") return -1; } return par; } //--------------------------------------------------------------------------- // Clarify condition '(x = a < 0)' into '((x = a) < 0)' or '(x = (a < 0))' // Clarify condition '(a & b == c)' into '((a & b) == c)' or '(a & (b == c))' //--------------------------------------------------------------------------- void CheckCondition::clarifyCondition() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("clarifyCondition")) return; logChecker("CheckCondition::clarifyCondition"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { if (Token::Match(tok, "( %name% [=&|^]")) { for (const Token *tok2 = tok->tokAt(3); tok2; tok2 = tok2->next()) { if (tok2->str() == "(" || tok2->str() == "[") tok2 = tok2->link(); else if (tok2->isComparisonOp()) { // This might be a template if (!tok2->isC() && tok2->link()) break; if (Token::simpleMatch(tok2->astParent(), "?")) break; clarifyConditionError(tok, tok->strAt(2) == "=", false); break; } else if (!tok2->isName() && !tok2->isNumber() && tok2->str() != ".") break; } } else if (tok->tokType() == Token::eBitOp && !tok->isUnaryOp("&")) { if (tok->astOperand2() && tok->astOperand2()->variable() && tok->astOperand2()->variable()->nameToken() == tok->astOperand2()) continue; // using boolean result in bitwise operation ! x [&|^] const ValueType* vt1 = tok->astOperand1() ? tok->astOperand1()->valueType() : nullptr; const ValueType* vt2 = tok->astOperand2() ? tok->astOperand2()->valueType() : nullptr; if (vt1 && vt1->type == ValueType::BOOL && !Token::Match(tok->astOperand1(), "%name%|(|[|::|.") && countPar(tok->astOperand1(), tok) == 0) clarifyConditionError(tok, false, true); else if (vt2 && vt2->type == ValueType::BOOL && !Token::Match(tok->astOperand2(), "%name%|(|[|::|.") && countPar(tok, tok->astOperand2()) == 0) clarifyConditionError(tok, false, true); } } } } void CheckCondition::clarifyConditionError(const Token *tok, bool assign, bool boolop) { std::string errmsg; if (assign) errmsg = "Suspicious condition (assignment + comparison); Clarify expression with parentheses."; else if (boolop) errmsg = "Boolean result is used in bitwise operation. Clarify expression with parentheses.\n" "Suspicious expression. Boolean result is used in bitwise operation. The operator '!' " "and the comparison operators have higher precedence than bitwise operators. " "It is recommended that the expression is clarified with parentheses."; else errmsg = "Suspicious condition (bitwise operator + comparison); Clarify expression with parentheses.\n" "Suspicious condition. Comparison operators have higher precedence than bitwise operators. " "Please clarify the condition with parentheses."; reportError(tok, Severity::style, "clarifyCondition", errmsg, CWE398, Certainty::normal); } void CheckCondition::alwaysTrueFalse() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("alwaysTrue") && !mSettings->isPremiumEnabled("alwaysFalse") && !mSettings->isPremiumEnabled("knownConditionTrueFalse")) return; logChecker("CheckCondition::alwaysTrueFalse"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart->next(); tok != scope->bodyEnd; tok = tok->next()) { // don't write false positives when templates are used or inside of asserts or non-evaluated contexts if (tok->link() && (Token::simpleMatch(tok, "<") || Token::Match(tok->previous(), "static_assert|assert|ASSERT|sizeof|decltype ("))) { tok = tok->link(); continue; } if (!tok->hasKnownIntValue()) continue; if (Token::Match(tok->previous(), "%name% (") && tok->previous()->function()) { const Function* f = tok->previous()->function(); if (f->functionScope && Token::Match(f->functionScope->bodyStart, "{ return true|false ;")) continue; } const Token* condition = nullptr; { // is this a condition.. const Token *parent = tok->astParent(); while (Token::Match(parent, "%oror%|&&")) parent = parent->astParent(); if (!parent) continue; if (parent->str() == "?" && precedes(tok, parent)) condition = parent; else if (Token::Match(parent->previous(), "if|while (")) condition = parent->previous(); else if (Token::simpleMatch(parent, "return")) condition = parent; else if (parent->str() == ";" && parent->astParent() && parent->astParent()->astParent() && Token::simpleMatch(parent->astParent()->astParent()->previous(), "for (")) condition = parent->astParent()->astParent()->previous(); else if (Token::Match(tok, "%comp%")) condition = tok; else continue; } // Skip already diagnosed values if (diag(tok, false)) continue; if (condition->isConstexpr()) continue; if (!isUsedAsBool(tok, *mSettings)) continue; if (Token::simpleMatch(condition, "return") && Token::Match(tok, "%assign%")) continue; if (Token::simpleMatch(tok->astParent(), "return") && Token::Match(tok, ".|%var%")) continue; if (Token::Match(tok, "%num%|%bool%|%char%")) continue; if (Token::Match(tok, "! %num%|%bool%|%char%")) continue; if (Token::Match(tok, "%oror%|&&")) { bool bail = false; for (const Token* op : { tok->astOperand1(), tok->astOperand2() }) { if (op->hasKnownIntValue() && (!op->isLiteral() || op->isBoolean())) { bail = true; break; } } if (bail) continue; } if (Token::simpleMatch(tok, ":")) continue; if (Token::Match(tok->astOperand1(), "%name% (") && Token::simpleMatch(tok->astParent(), "return")) continue; if (tok->isComparisonOp() && isWithoutSideEffects(tok->astOperand1()) && isSameExpression(true, tok->astOperand1(), tok->astOperand2(), *mSettings, true, true)) continue; if (isConstVarExpression(tok, [](const Token* tok) { return Token::Match(tok, "[|(|&|+|-|*|/|%|^|>>|<<") && !Token::simpleMatch(tok, "( )"); })) continue; // there are specific warnings about nonzero expressions (pointer/unsigned) // do not write alwaysTrueFalse for these comparisons. { const ValueFlow::Value *zeroValue = nullptr; const Token *nonZeroExpr = nullptr; if (CheckOther::comparisonNonZeroExpressionLessThanZero(tok, zeroValue, nonZeroExpr, /*suppress*/ true) || CheckOther::testIfNonZeroExpressionIsPositive(tok, zeroValue, nonZeroExpr)) continue; } // Don't warn when there are expanded macros.. bool isExpandedMacro = false; visitAstNodes(tok, [&](const Token * tok2) { if (!tok2) return ChildrenToVisit::none; if (tok2->isExpandedMacro()) { isExpandedMacro = true; return ChildrenToVisit::done; } return ChildrenToVisit::op1_and_op2; }); if (isExpandedMacro) continue; for (const Token *parent = tok; parent; parent = parent->astParent()) { if (parent->isExpandedMacro()) { isExpandedMacro = true; break; } } if (isExpandedMacro) continue; // don't warn when condition checks sizeof result bool hasSizeof = false; visitAstNodes(tok, [&](const Token * tok2) { if (!tok2) return ChildrenToVisit::none; if (tok2->isNumber()) return ChildrenToVisit::none; if (Token::simpleMatch(tok2->previous(), "sizeof (")) { hasSizeof = true; return ChildrenToVisit::none; } if (tok2->isComparisonOp() || tok2->isArithmeticalOp()) { return ChildrenToVisit::op1_and_op2; } return ChildrenToVisit::none; }); if (hasSizeof) continue; alwaysTrueFalseError(tok, condition, &tok->values().front()); } } } void CheckCondition::alwaysTrueFalseError(const Token* tok, const Token* condition, const ValueFlow::Value* value) { const bool alwaysTrue = value && (value->intvalue != 0 || value->isImpossible()); const std::string expr = tok ? tok->expressionString() : std::string("x"); const std::string conditionStr = (Token::simpleMatch(condition, "return") ? "Return value" : "Condition"); const std::string errmsg = conditionStr + " '" + expr + "' is always " + bool_to_string(alwaysTrue); const ErrorPath errorPath = getErrorPath(tok, value, errmsg); reportError(errorPath, Severity::style, "knownConditionTrueFalse", errmsg, (alwaysTrue ? CWE571 : CWE570), Certainty::normal); } void CheckCondition::checkInvalidTestForOverflow() { // Interesting blogs: // https://www.airs.com/blog/archives/120 // https://kristerw.blogspot.com/2016/02/how-undefined-signed-overflow-enables.html // https://research.checkpoint.com/2020/optout-compiler-undefined-behavior-optimizations/ // x + c < x -> false // x + c <= x -> false // x + c > x -> true // x + c >= x -> true // x + y < x -> y < 0 if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckCondition::checkInvalidTestForOverflow"); // warning for (const Token *tok = mTokenizer->tokens(); tok; tok = tok->next()) { if (!Token::Match(tok, "<|<=|>=|>") || !tok->isBinaryOp()) continue; const Token *lhsTokens[2] = {tok->astOperand1(), tok->astOperand2()}; for (const Token *lhs: lhsTokens) { std::string cmp = tok->str(); if (lhs == tok->astOperand2()) cmp[0] = (cmp[0] == '<') ? '>' : '<'; if (!Token::Match(lhs, "[+-]") || !lhs->isBinaryOp()) continue; const bool isSignedInteger = lhs->valueType() && lhs->valueType()->isIntegral() && lhs->valueType()->sign == ValueType::Sign::SIGNED; const bool isPointer = lhs->valueType() && lhs->valueType()->pointer > 0; if (!isSignedInteger && !isPointer) continue; const Token *exprTokens[2] = {lhs->astOperand1(), lhs->astOperand2()}; for (const Token *expr: exprTokens) { if (lhs->str() == "-" && expr == lhs->astOperand2()) continue; // TODO? if (expr->hasKnownIntValue()) continue; if (!isSameExpression(true, expr, lhs->astSibling(), *mSettings, true, false)) continue; const Token * const other = expr->astSibling(); // x [+-] c cmp x if ((other->isNumber() && other->getKnownIntValue() > 0) || (!other->isNumber() && other->valueType() && other->valueType()->isIntegral() && other->valueType()->sign == ValueType::Sign::UNSIGNED)) { bool result; if (lhs->str() == "+") result = (cmp == ">" || cmp == ">="); else result = (cmp == "<" || cmp == "<="); invalidTestForOverflow(tok, lhs->valueType(), bool_to_string(result)); continue; } // x + y cmp x if (lhs->str() == "+" && other->varId() > 0) { const std::string result = other->str() + cmp + "0"; invalidTestForOverflow(tok, lhs->valueType(), result); continue; } // x - y cmp x if (lhs->str() == "-" && other->varId() > 0) { std::string cmp2 = cmp; cmp2[0] = (cmp[0] == '<') ? '>' : '<'; const std::string result = other->str() + cmp2 + "0"; invalidTestForOverflow(tok, lhs->valueType(), result); continue; } } } } } void CheckCondition::invalidTestForOverflow(const Token* tok, const ValueType *valueType, const std::string &replace) { const std::string expr = (tok ? tok->expressionString() : std::string("x + c < x")); const std::string overflow = (valueType && valueType->pointer) ? "pointer overflow" : "signed integer overflow"; std::string errmsg = "Invalid test for overflow '" + expr + "'; " + overflow + " is undefined behavior."; if (replace == "false" || replace == "true") errmsg += " Some mainstream compilers remove such overflow tests when optimising the code and assume it's always " + replace + "."; else errmsg += " Some mainstream compilers removes handling of overflows when optimising the code and change the code to '" + replace + "'."; reportError(tok, Severity::warning, "invalidTestForOverflow", errmsg, uncheckedErrorConditionCWE, Certainty::normal); } void CheckCondition::checkPointerAdditionResultNotNull() { if (!mSettings->severity.isEnabled(Severity::warning)) return; logChecker("CheckCondition::checkPointerAdditionResultNotNull"); // warning const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp() || !tok->astOperand1() || !tok->astOperand2()) continue; // Macros might have pointless safety checks if (tok->isExpandedMacro()) continue; const Token *calcToken, *exprToken; if (tok->astOperand1()->str() == "+") { calcToken = tok->astOperand1(); exprToken = tok->astOperand2(); } else if (tok->astOperand2()->str() == "+") { calcToken = tok->astOperand2(); exprToken = tok->astOperand1(); } else continue; // pointer comparison against NULL (ptr+12==0) if (calcToken->hasKnownIntValue()) continue; if (!calcToken->valueType() || calcToken->valueType()->pointer==0) continue; if (!exprToken->hasKnownIntValue() || !exprToken->getValue(0)) continue; pointerAdditionResultNotNullError(tok, calcToken); } } } void CheckCondition::pointerAdditionResultNotNullError(const Token *tok, const Token *calc) { const std::string s = calc ? calc->expressionString() : "ptr+1"; reportError(tok, Severity::warning, "pointerAdditionResultNotNull", "Comparison is wrong. Result of '" + s + "' can't be 0 unless there is pointer overflow, and pointer overflow is undefined behaviour."); } void CheckCondition::checkDuplicateConditionalAssign() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("duplicateConditionalAssign")) return; logChecker("CheckCondition::checkDuplicateConditionalAssign"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope *scope : symbolDatabase->functionScopes) { for (const Token *tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (!Token::simpleMatch(tok, "if (")) continue; if (!Token::simpleMatch(tok->linkAt(1), ") {")) continue; const Token *blockTok = tok->linkAt(1)->next(); const Token *condTok = tok->next()->astOperand2(); const bool isBoolVar = Token::Match(condTok, "!| %var%"); if (!isBoolVar && !Token::Match(condTok, "==|!=")) continue; if ((isBoolVar || condTok->str() == "!=") && Token::simpleMatch(blockTok->link(), "} else {")) continue; if (!blockTok->next()) continue; const Token *assignTok = blockTok->next()->astTop(); if (!Token::simpleMatch(assignTok, "=")) continue; if (nextAfterAstRightmostLeaf(assignTok) != blockTok->link()->previous()) continue; bool isRedundant = false; if (isBoolVar) { const bool isNegation = condTok->str() == "!"; const Token* const varTok = isNegation ? condTok->next() : condTok; const ValueType* vt = varTok->variable() ? varTok->variable()->valueType() : nullptr; if (!(vt && vt->type == ValueType::Type::BOOL && !vt->pointer)) continue; if (!(assignTok->astOperand1() && assignTok->astOperand1()->varId() == varTok->varId())) continue; if (!(assignTok->astOperand2() && assignTok->astOperand2()->hasKnownIntValue())) continue; const MathLib::bigint val = assignTok->astOperand2()->getKnownIntValue(); if (val < 0 || val > 1) continue; isRedundant = (isNegation && val == 0) || (!isNegation && val == 1); } else { // comparison if (!isSameExpression( true, condTok->astOperand1(), assignTok->astOperand1(), *mSettings, true, true)) continue; if (!isSameExpression( true, condTok->astOperand2(), assignTok->astOperand2(), *mSettings, true, true)) continue; } duplicateConditionalAssignError(condTok, assignTok, isRedundant); } } } void CheckCondition::duplicateConditionalAssignError(const Token *condTok, const Token* assignTok, bool isRedundant) { ErrorPath errors; std::string msg = "Duplicate expression for the condition and assignment."; if (condTok && assignTok) { if (condTok->str() == "==") { msg = "Assignment '" + assignTok->expressionString() + "' is redundant with condition '" + condTok->expressionString() + "'."; errors.emplace_back(condTok, "Condition '" + condTok->expressionString() + "'"); errors.emplace_back(assignTok, "Assignment '" + assignTok->expressionString() + "' is redundant"); } else { msg = "The statement 'if (" + condTok->expressionString() + ") " + assignTok->expressionString(); msg += isRedundant ? "' is redundant." : "' is logically equivalent to '" + assignTok->expressionString() + "'."; errors.emplace_back(assignTok, "Assignment '" + assignTok->expressionString() + "'"); errors.emplace_back(condTok, "Condition '" + condTok->expressionString() + "' is redundant"); } } reportError( errors, Severity::style, "duplicateConditionalAssign", msg, CWE398, Certainty::normal); } void CheckCondition::checkAssignmentInCondition() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("assignmentInCondition")) return; logChecker("CheckCondition::checkAssignmentInCondition"); // style const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (tok->str() != "=") continue; if (!tok->astParent()) continue; // Is this assignment of container/iterator? if (!tok->valueType()) continue; if (tok->valueType()->pointer > 0) continue; if (tok->valueType()->type != ValueType::Type::CONTAINER && tok->valueType()->type != ValueType::Type::ITERATOR) continue; // warn if this is a conditional expression.. if (Token::Match(tok->astParent()->previous(), "if|while (")) assignmentInCondition(tok); else if (Token::Match(tok->astParent(), "%oror%|&&")) assignmentInCondition(tok); else if (Token::simpleMatch(tok->astParent(), "?") && tok == tok->astParent()->astOperand1()) assignmentInCondition(tok); } } } void CheckCondition::assignmentInCondition(const Token *eq) { std::string expr = eq ? eq->expressionString() : "x=y"; reportError( eq, Severity::style, "assignmentInCondition", "Suspicious assignment in condition. Condition '" + expr + "' is always true.", CWE571, Certainty::normal); } void CheckCondition::checkCompareValueOutOfTypeRange() { if (!mSettings->severity.isEnabled(Severity::style) && !mSettings->isPremiumEnabled("compareValueOutOfTypeRangeError")) return; if (mSettings->platform.type == Platform::Type::Native || mSettings->platform.type == Platform::Type::Unspecified) return; logChecker("CheckCondition::checkCompareValueOutOfTypeRange"); // style,platform const SymbolDatabase *symbolDatabase = mTokenizer->getSymbolDatabase(); for (const Scope * scope : symbolDatabase->functionScopes) { for (const Token* tok = scope->bodyStart; tok != scope->bodyEnd; tok = tok->next()) { if (!tok->isComparisonOp() || !tok->isBinaryOp()) continue; for (int i = 0; i < 2; ++i) { const Token * const valueTok = (i == 0) ? tok->astOperand1() : tok->astOperand2(); const Token * const typeTok = valueTok->astSibling(); if (!valueTok->hasKnownIntValue() || !typeTok->valueType() || typeTok->valueType()->pointer) continue; if (valueTok->getKnownIntValue() < 0 && valueTok->valueType() && valueTok->valueType()->sign != ValueType::Sign::SIGNED) continue; if (valueTok->valueType() && valueTok->valueType()->isTypeEqual(typeTok->valueType())) continue; int bits = 0; switch (typeTok->valueType()->type) { case ValueType::Type::BOOL: bits = 1; break; case ValueType::Type::CHAR: bits = mSettings->platform.char_bit; break; case ValueType::Type::SHORT: bits = mSettings->platform.short_bit; break; case ValueType::Type::INT: bits = mSettings->platform.int_bit; break; case ValueType::Type::LONG: bits = mSettings->platform.long_bit; break; case ValueType::Type::LONGLONG: bits = mSettings->platform.long_long_bit; break; default: break; } if (bits == 0 || bits >= 64) continue; const auto typeMinValue = (typeTok->valueType()->sign == ValueType::Sign::UNSIGNED) ? 0 : (-(1LL << (bits-1))); const auto unsignedTypeMaxValue = (1LL << bits) - 1LL; long long typeMaxValue; if (typeTok->valueType()->sign != ValueType::Sign::SIGNED) typeMaxValue = unsignedTypeMaxValue; else if (bits >= mSettings->platform.int_bit && (!valueTok->valueType() || valueTok->valueType()->sign != ValueType::Sign::SIGNED)) typeMaxValue = unsignedTypeMaxValue; else typeMaxValue = unsignedTypeMaxValue / 2; bool result{}; const auto kiv = valueTok->getKnownIntValue(); if (tok->str() == "==") result = false; else if (tok->str() == "!=") result = true; else if (tok->str()[0] == '>' && i == 0) // num > var result = (kiv > 0); else if (tok->str()[0] == '>' && i == 1) // var > num result = (kiv < 0); else if (tok->str()[0] == '<' && i == 0) // num < var result = (kiv < 0); else if (tok->str()[0] == '<' && i == 1) // var < num result = (kiv > 0); bool error = false; if (kiv < typeMinValue || kiv > typeMaxValue) { error = true; } else { switch (i) { case 0: // num cmp var if (kiv == typeMinValue) { if (tok->str() == "<=") { result = true; error = true; } else if (tok->str() == ">") error = true; } else if (kiv == typeMaxValue && (tok->str() == ">=" || tok->str() == "<")) { error = true; } break; case 1: // var cmp num if (kiv == typeMinValue) { if (tok->str() == ">=") { result = true; error = true; } else if (tok->str() == "<") error = true; } else if (kiv == typeMaxValue && (tok->str() == "<=" || tok->str() == ">")) { error = true; } break; } } if (error) compareValueOutOfTypeRangeError(valueTok, typeTok->valueType()->str(), kiv, result); } } } } void CheckCondition::compareValueOutOfTypeRangeError(const Token *comparison, const std::string &type, long long value, bool result) { reportError( comparison, Severity::style, "compareValueOutOfTypeRangeError", "Comparing expression of type '" + type + "' against value " + std::to_string(value) + ". Condition is always " + bool_to_string(result) + ".", CWE398, Certainty::normal); }
90,132
C++
.cpp
1,815
37.035262
237
0.527355
danmar/cppcheck
5,720
1,444
118
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false