Fixed current and potential bugs caught by Coverity

Change-Id: I9f9d09dc797ffea062eeb49c881be1d5acb63d7b
This commit is contained in:
Tyler Veness
2015-11-15 14:49:50 -08:00
committed by Peter Johnson
parent b0fec4089b
commit 055ee09825
34 changed files with 105 additions and 65 deletions

View File

@@ -230,7 +230,7 @@ extern "C"
int HALGetJoystickDescriptor(uint8_t joystickNum, HALJoystickDescriptor *desc);
int HALGetJoystickIsXbox(uint8_t joystickNum);
int HALGetJoystickType(uint8_t joystickNum);
const char* HALGetJoystickName(uint8_t joystickNum);
char* HALGetJoystickName(uint8_t joystickNum);
int HALGetJoystickAxisType(uint8_t joystickNum, uint8_t axis);
int HALSetJoystickOutputs(uint8_t joystickNum, uint32_t outputs, uint16_t leftRumble, uint16_t rightRumble);
int HALGetMatchTime(float *matchTime);

View File

@@ -273,7 +273,9 @@ uint32_t getAnalogOversampleBits(void* analog_port_pointer, int32_t *status) {
int16_t getAnalogValue(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
int16_t value;
checkAnalogInputChannel(port->port.pin);
if (!checkAnalogInputChannel(port->port.pin)) {
return 0;
}
tAI::tReadSelect readSelect;
readSelect.Channel = port->port.pin;
@@ -304,7 +306,9 @@ int16_t getAnalogValue(void* analog_port_pointer, int32_t *status) {
int32_t getAnalogAverageValue(void* analog_port_pointer, int32_t *status) {
AnalogPort* port = (AnalogPort*) analog_port_pointer;
int32_t value;
checkAnalogInputChannel(port->port.pin);
if (!checkAnalogInputChannel(port->port.pin)) {
return 0;
}
tAI::tReadSelect readSelect;
readSelect.Channel = port->port.pin;

View File

@@ -126,11 +126,11 @@ void initializeDigital(int32_t *status) {
// Ensure that PWM output values are set to OFF
for (uint32_t pwm_index = 0; pwm_index < kPwmPins; pwm_index++) {
// Initialize port structure
DigitalPort* digital_port = new DigitalPort();
digital_port->port.pin = pwm_index;
DigitalPort digital_port;
digital_port.port.pin = pwm_index;
setPWM(digital_port, kPwmDisabled, status);
setPWMPeriodScale(digital_port, 3, status); // Set all to 4x by default.
setPWM(&digital_port, kPwmDisabled, status);
setPWMPeriodScale(&digital_port, 3, status); // Set all to 4x by default.
}
digitalSystemsInitialized = true;

View File

@@ -209,7 +209,7 @@ CTR_Code PCM::FireOneShotSolenoid(UINT8 idx)
CTR_Code PCM::SetOneShotDurationMs(UINT8 idx,uint32_t durMs)
{
/* sanity check caller's param */
if(idx > 8)
if(idx > 7)
return CTR_InvalidParamValue;
/* get latest tx frame */
CtreCanNode::txTask<PcmControlSetOneShotDur_t> toFill = GetTx<PcmControlSetOneShotDur_t>(CONTROL_3 | GetDeviceNumber());

View File

@@ -1,6 +1,7 @@
//This file must compile on ALL PLATFORMS. Be very careful what you put in here.
#include "HAL/HAL.hpp"
#include "FRC_NetworkCommunication/FRCComm.h"
#include <cstring>
int HALGetControlWord(HALControlWord *data)
{
@@ -62,17 +63,20 @@ int HALGetJoystickType(uint8_t joystickNum)
}
}
const char* HALGetJoystickName(uint8_t joystickNum)
char* HALGetJoystickName(uint8_t joystickNum)
{
HALJoystickDescriptor joystickDesc;
if(HALGetJoystickDescriptor(joystickNum, &joystickDesc)<0)
{
const char* retval = "";
return retval;
char* name = (char*)std::malloc(1);
name[0] = '\0';
return name;
} else
{
const char* retval(joystickDesc.name);
return retval;
size_t len = std::strlen(joystickDesc.name);
char* name = (char*)std::malloc(len+1);
std::strcpy(name, joystickDesc.name);
return name;
}
}

View File

@@ -53,7 +53,6 @@ class AnalogAccelerometer : public SensorBase,
std::shared_ptr<AnalogInput> m_analogInput;
float m_voltsPerG = 1.0;
float m_zeroGVoltage = 2.5;
bool m_allocatedChannel;
std::shared_ptr<ITable> m_table;
};

View File

@@ -11,6 +11,7 @@
#include "SensorBase.h"
#include "LiveWindow/LiveWindowSendable.h"
#include <memory>
#include <cstdint>
/**
* MXP analog output class.

View File

@@ -87,5 +87,4 @@ class AnalogPotentiometer : public Potentiometer, public LiveWindowSendable {
std::shared_ptr<AnalogInput> m_analog_input;
double m_fullRange, m_offset;
std::shared_ptr<ITable> m_table;
bool m_init_analog_input;
};

View File

@@ -177,7 +177,7 @@ class CANJaguar : public MotorSafety,
float m_value = 0.0f;
// Parameters/configuration
ControlMode m_controlMode;
ControlMode m_controlMode = kPercentVbus;
uint8_t m_speedReference = LM_REF_NONE;
uint8_t m_positionReference = LM_REF_NONE;
double m_p = 0.0;
@@ -227,7 +227,7 @@ class CANJaguar : public MotorSafety,
mutable std::atomic<bool> m_receivedStatusMessage1{false};
mutable std::atomic<bool> m_receivedStatusMessage2{false};
bool m_controlEnabled;
bool m_controlEnabled = false;
void verify();

View File

@@ -10,6 +10,7 @@
#include "LiveWindow/LiveWindowSendable.h"
#include <memory>
#include <cstdint>
/**
* Class to read a digital input.

View File

@@ -45,7 +45,7 @@ class InterruptableSensorBase : public SensorBase {
protected:
void *m_interrupt = nullptr;
uint32_t m_interruptIndex;
uint32_t m_interruptIndex = std::numeric_limits<uint32_t>::max();
void AllocateInterrupts(bool watcher);
static std::unique_ptr<Resource> m_interrupts;

View File

@@ -49,9 +49,9 @@ class SPI : public SensorBase {
protected:
uint8_t m_port;
bool m_msbFirst;
bool m_sampleOnTrailing;
bool m_clk_idle_high;
bool m_msbFirst = false; // default little-endian
bool m_sampleOnTrailing = false; // default data updated on falling edge
bool m_clk_idle_high = false; // default clock active high
private:
void Init();

View File

@@ -101,8 +101,7 @@ class Ultrasonic : public SensorBase,
std::shared_ptr<DigitalOutput> m_pingChannel;
std::shared_ptr<DigitalInput> m_echoChannel;
bool m_allocatedChannels;
bool m_enabled;
bool m_enabled = false;
Counter m_counter;
Ultrasonic *m_nextSensor;
DistanceUnit m_units;

View File

@@ -88,7 +88,10 @@ AnalogGyro::AnalogGyro(std::shared_ptr<AnalogInput> channel)
* significant
* drift in the gyro and it needs to be recalibrated after it has been running.
*/
void AnalogGyro::Reset() { m_analog->ResetAccumulator(); }
void AnalogGyro::Reset() {
if (StatusIsFatal()) return;
m_analog->ResetAccumulator();
}
/**
* {@inheritDoc}
@@ -127,6 +130,8 @@ void AnalogGyro::Calibrate() {
* of the returned rate from the gyro.
*/
float AnalogGyro::GetAngle() const {
if (StatusIsFatal()) return 0.f;
int64_t rawValue;
uint32_t count;
m_analog->GetAccumulatorOutput(rawValue, count);
@@ -148,6 +153,8 @@ float AnalogGyro::GetAngle() const {
* @return the current rate in degrees per second
*/
double AnalogGyro::GetRate() const {
if (StatusIsFatal()) return 0.0;
return (m_analog->GetAverageValue() - ((double)m_center + m_offset)) * 1e-9 *
m_analog->GetLSBWeight() /
((1 << m_analog->GetOversampleBits()) * m_voltsPerDegreePerSecond);
@@ -176,6 +183,8 @@ void AnalogGyro::SetSensitivity(float voltsPerDegreePerSecond) {
* @param volts The size of the deadband in volts
*/
void AnalogGyro::SetDeadband(float volts) {
if (StatusIsFatal()) return;
int32_t deadband = volts * 1e9 / m_analog->GetLSBWeight() *
(1 << m_analog->GetOversampleBits());
m_analog->SetAccumulatorDeadband(deadband);

View File

@@ -10,6 +10,7 @@
#include "Timer.h"
#include "WPIErrors.h"
#include "LiveWindow/LiveWindow.h"
#include "HAL/Port.h"
#include <sstream>
@@ -43,10 +44,11 @@ AnalogInput::AnalogInput(uint32_t channel) {
m_channel = channel;
void *port = getPort(channel);
void* port = getPort(channel);
int32_t status = 0;
m_port = initializeAnalogInputPort(port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
freePort(port);
LiveWindow::GetInstance()->AddSensor("AnalogInput", channel, this);
HALReport(HALUsageReporting::kResourceType_AnalogChannel, channel);

View File

@@ -9,7 +9,9 @@
#include "Resource.h"
#include "WPIErrors.h"
#include "LiveWindow/LiveWindow.h"
#include "HAL/Port.h"
#include <limits>
#include <sstream>
static std::unique_ptr<Resource> outputs;
@@ -27,21 +29,26 @@ AnalogOutput::AnalogOutput(uint32_t channel) {
if (!checkAnalogOutputChannel(channel)) {
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf.str());
m_channel = std::numeric_limits<uint32_t>::max();
m_port = nullptr;
return;
}
if (outputs->Allocate(channel, buf.str()) ==
std::numeric_limits<uint32_t>::max()) {
CloneError(*outputs);
m_channel = std::numeric_limits<uint32_t>::max();
m_port = nullptr;
return;
}
m_channel = channel;
void *port = getPort(m_channel);
void* port = getPort(m_channel);
int32_t status = 0;
m_port = initializeAnalogOutputPort(port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
freePort(port);
LiveWindow::GetInstance()->AddActuator("AnalogOutput", m_channel, this);
HALReport(HALUsageReporting::kResourceType_AnalogOutput, m_channel);

View File

@@ -11,6 +11,8 @@
//#include "NetworkCommunication/UsageReporting.h"
#include "Resource.h"
#include "WPIErrors.h"
#include "HAL/Port.h"
#include <memory>
/**
@@ -20,11 +22,12 @@
* on-board 4-7 are on the MXP port.
*/
AnalogTrigger::AnalogTrigger(int32_t channel) {
void *port = getPort(channel);
void* port = getPort(channel);
int32_t status = 0;
uint32_t index = 0;
m_trigger = initializeAnalogTrigger(port, &index, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
freePort(port);
m_index = index;
HALReport(HALUsageReporting::kResourceType_AnalogTrigger, channel);

View File

@@ -149,7 +149,10 @@ unsigned int CameraServer::GetQuality() {
void CameraServer::Serve() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) wpi_setErrnoError();
if (sock == -1) {
wpi_setErrnoError();
return;
}
int reuseAddr = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuseAddr,

View File

@@ -11,6 +11,7 @@
#include "WPIErrors.h"
#include "LiveWindow/LiveWindow.h"
#include <limits>
#include <sstream>
/**
@@ -25,6 +26,7 @@ DigitalInput::DigitalInput(uint32_t channel) {
if (!CheckDigitalChannel(channel)) {
buf << "Digital Channel " << channel;
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf.str());
m_channel = std::numeric_limits<uint32_t>::max();
return;
}
m_channel = channel;

View File

@@ -9,6 +9,7 @@
#include "Resource.h"
#include "WPIErrors.h"
#include <limits>
#include <sstream>
/**
@@ -21,13 +22,14 @@
DigitalOutput::DigitalOutput(uint32_t channel) {
std::stringstream buf;
m_pwmGenerator = (void *)std::numeric_limits<uint32_t>::max();
if (!CheckDigitalChannel(channel)) {
buf << "Digital Channel " << channel;
wpi_setWPIErrorWithContext(ChannelIndexOutOfRange, buf.str());
m_channel = std::numeric_limits<uint32_t>::max();
return;
}
m_channel = channel;
m_pwmGenerator = (void *)std::numeric_limits<uint32_t>::max();
int32_t status = 0;
allocateDIO(m_digital_ports[channel], false, &status);

View File

@@ -107,7 +107,6 @@ void PIDController::Calculate() {
pidInput = m_pidInput;
pidOutput = m_pidOutput;
enabled = m_enabled;
pidInput = m_pidInput;
}
if (pidInput == nullptr) return;

View File

@@ -56,8 +56,10 @@ RobotBase::RobotBase() : m_ds(DriverStation::GetInstance()) {
FILE *file = nullptr;
file = fopen("/tmp/frc_versions/FRC_Lib_Version.ini", "w");
fputs("2016 C++ Beta2.0", file);
if (file != nullptr) fclose(file);
if (file != nullptr) {
fputs("2016 C++ Beta2.0", file);
fclose(file);
}
}
/**

View File

@@ -10,6 +10,7 @@
#include "NetworkCommunication/LoadOut.h"
#include "WPIErrors.h"
#include "HAL/HAL.hpp"
#include "HAL/Port.h"
const uint32_t SensorBase::kDigitalChannels;
const uint32_t SensorBase::kAnalogInputs;
@@ -36,6 +37,7 @@ SensorBase::SensorBase() {
int32_t status = 0;
m_digital_ports[i] = initializeDigitalPort(port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
freePort(port);
}
for (uint32_t i = 0; i < kRelayChannels; i++) {
@@ -43,6 +45,7 @@ SensorBase::SensorBase() {
int32_t status = 0;
m_relay_ports[i] = initializeDigitalPort(port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
freePort(port);
}
for (uint32_t i = 0; i < kPwmChannels; i++) {
@@ -50,6 +53,7 @@ SensorBase::SensorBase() {
int32_t status = 0;
m_pwm_ports[i] = initializeDigitalPort(port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
freePort(port);
}
}
}

View File

@@ -21,6 +21,7 @@ SolenoidBase::SolenoidBase(uint8_t moduleNumber)
SolenoidBase::m_ports[moduleNumber][i] =
initializeSolenoidPort(port, &status);
wpi_setErrorWithContext(status, getHALErrorMessage(status));
freePort(port);
}
}

View File

@@ -126,6 +126,8 @@ Ultrasonic::Ultrasonic(DigitalOutput *pingChannel, DigitalInput *echoChannel,
m_counter(m_echoChannel) {
if (pingChannel == nullptr || echoChannel == nullptr) {
wpi_setWPIError(NullParameter);
m_nextSensor = nullptr;
m_units = units;
return;
}
m_units = units;

View File

@@ -117,8 +117,10 @@ HSLImage *AxisCamera::GetImage() {
int AxisCamera::CopyJPEG(char **destImage, unsigned int &destImageSize,
unsigned int &destImageBufferSize) {
std::lock_guard<priority_mutex> lock(m_imageDataMutex);
if (destImage == nullptr)
if (destImage == nullptr) {
wpi_setWPIErrorWithContext(NullParameter, "destImage must not be nullptr");
return 0;
}
if (m_imageData.size() == 0) return 0; // if no source image
@@ -440,6 +442,7 @@ void AxisCamera::ReadImagesFromCamera() {
wpi_setWPIErrorWithContext(IncompatibleMode,
"No content-length token found in packet");
close(m_cameraSocket);
if (imgBuffer) delete[] imgBuffer;
return;
}
contentLength = contentLength + 16; // skip past "content length"
@@ -564,8 +567,10 @@ int AxisCamera::CreateCameraSocket(std::string const &requestString,
}
if (getaddrinfo(m_cameraHost.c_str(), "80", nullptr, &address) == -1) {
if (setError)
if (setError) {
wpi_setErrnoErrorWithContext("Failed to create the camera socket");
close(camSocket);
}
return -1;
}
@@ -573,10 +578,13 @@ int AxisCamera::CreateCameraSocket(std::string const &requestString,
if (connect(camSocket, address->ai_addr, address->ai_addrlen) == -1) {
if (setError)
wpi_setErrnoErrorWithContext("Failed to connect to the camera");
freeaddrinfo(address);
close(camSocket);
return -1;
}
freeaddrinfo(address);
int sent = send(camSocket, requestString.c_str(), requestString.size(), 0);
if (sent == -1) {
if (setError)

View File

@@ -69,6 +69,7 @@ void dprintf(const char *tempString, ...) /* Variable argument list */
for (index = 0; index < tempStringLen; index++) {
if (tempString[index] == ' ') {
printf("ERROR in dprintf: malformed calling sequence (%s)\n", tempString);
va_end(args);
return;
}
if (tempString[index] == '\\' || tempString[index] == '/')
@@ -292,6 +293,7 @@ int processFile(char *inputFile, char *outputString, int lineNumber) {
FILE *infile;
const int stringSize = 80; // max size of one line in file
char inputStr[stringSize];
inputStr[0] = '\0';
int lineCount = 0;
if (lineNumber < 0) return (-1);
@@ -323,14 +325,10 @@ int processFile(char *inputFile, char *outputString, int lineNumber) {
if (lineNumber == 0) return (lineCount);
// check for input out of range
if (lineNumber > lineCount) return (-1);
// return the line selected
if (lineCount) {
stripString(inputStr);
strcpy(outputString, inputStr);
return (lineCount);
} else {
return (-1);
}
// return the line selected; lineCount guaranteed to be greater than zero
stripString(inputStr);
strcpy(outputString, inputStr);
return (lineCount);
}
/** Ignore empty string

View File

@@ -70,6 +70,7 @@ int frcDispose(const char* functionName, ...) /* Variable argument list */
}
disposalPtr = va_arg(disposalPtrList, void*);
}
va_end(disposalPtrList);
return returnValue;
}

View File

@@ -22,7 +22,7 @@ class CommandGroupEntry {
CommandGroupEntry(Command *command, Sequence state, double timeout = -1.0);
bool IsTimedOut() const;
double m_timeout;
double m_timeout = -1.0;
Command *m_command = nullptr;
Sequence m_state = kSequence_InSequence;
};

View File

@@ -11,7 +11,7 @@
struct LiveWindowComponent {
std::string subsystem;
std::string name;
bool isSensor;
bool isSensor = false;
LiveWindowComponent() = default;
LiveWindowComponent(std::string subsystem, std::string name, bool isSensor) {

View File

@@ -93,7 +93,6 @@ class PIDController : public LiveWindowSendable,
float m_minimumInput = 0; // minimum input - limit setpoint to this
bool m_continuous = false; // do the endpoints wrap around? eg. Absolute encoder
bool m_enabled = false; // is the pid controller enabled
bool m_destruct; // should the calculate thread stop running
float m_prevInput = 0; // the prior sensor input (used to compute velocity)
double m_totalError = 0; // the sum of the errors for use in the integral calc
enum {
@@ -105,7 +104,7 @@ class PIDController : public LiveWindowSendable,
// the percetage or absolute error that is considered on target.
float m_tolerance = 0.05;
float m_setpoint = 0;
float m_error;
float m_error = 0;
float m_result = 0;
float m_period;

View File

@@ -56,5 +56,5 @@ class SensorBase : public ErrorBase {
private:
static SensorBase* m_singletonList;
SensorBase* m_nextSingleton;
SensorBase* m_nextSingleton = nullptr;
};

View File

@@ -136,11 +136,7 @@ void LiveWindow::AddSensor(std::string type, int channel,
LiveWindowSendable *component) {
std::ostringstream oss;
oss << type << "[" << channel << "]";
std::string types(oss.str());
auto cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()] = '\0';
AddSensor("Ungrouped", cc, component);
AddSensor("Ungrouped", oss.str(), component);
std::shared_ptr<LiveWindowSendable> component_stl(
component, NullDeleter<LiveWindowSendable>());
if (std::find(m_sensors.begin(), m_sensors.end(), component_stl) ==
@@ -155,12 +151,8 @@ void LiveWindow::AddActuator(std::string type, int channel,
LiveWindowSendable *component) {
std::ostringstream oss;
oss << type << "[" << channel << "]";
std::string types(oss.str());
auto cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()] = '\0';
AddActuator("Ungrouped", cc, std::shared_ptr<LiveWindowSendable>(
component, [](LiveWindowSendable *) {}));
AddActuator("Ungrouped", oss.str(), std::shared_ptr<LiveWindowSendable>(
component, [](LiveWindowSendable *) {}));
}
/**
@@ -170,12 +162,8 @@ void LiveWindow::AddActuator(std::string type, int module, int channel,
LiveWindowSendable *component) {
std::ostringstream oss;
oss << type << "[" << module << "," << channel << "]";
std::string types(oss.str());
auto cc = new char[types.size() + 1];
types.copy(cc, types.size());
cc[types.size()] = '\0';
AddActuator("Ungrouped", cc, std::shared_ptr<LiveWindowSendable>(
component, [](LiveWindowSendable *) {}));
AddActuator("Ungrouped", oss.str(), std::shared_ptr<LiveWindowSendable>(
component, [](LiveWindowSendable *) {}));
}
/**

View File

@@ -390,7 +390,10 @@ JNIEXPORT jstring JNICALL Java_edu_wpi_first_wpilibj_communication_FRCNetworkCom
(JNIEnv * env, jclass, jbyte port)
{
NETCOMM_LOG(logDEBUG) << "Calling HALGetJoystickName";
return env->NewStringUTF(HALGetJoystickName(port));
char* joystickName = HALGetJoystickName(port);
jstring str = env->NewStringUTF(joystickName);
std::free(joystickName);
return str;
}
/*