instruction
stringclasses 1
value | input
stringlengths 90
139k
| output
stringlengths 16
138k
| __index_level_0__
int64 165k
175k
|
---|---|---|---|
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
Commit Message: [MJ2] Avoid index out of bounds access to pi->include[]
Signed-off-by: Young_X <[email protected]>
CWE ID: CWE-20 | static opj_bool pi_next_rpcl(opj_pi_iterator_t * pi)
{
opj_pi_comp_t *comp = NULL;
opj_pi_resolution_t *res = NULL;
long index = 0;
if (!pi->first) {
goto LABEL_SKIP;
} else {
int compno, resno;
pi->first = 0;
pi->dx = 0;
pi->dy = 0;
for (compno = 0; compno < pi->numcomps; compno++) {
comp = &pi->comps[compno];
for (resno = 0; resno < comp->numresolutions; resno++) {
int dx, dy;
res = &comp->resolutions[resno];
dx = comp->dx * (1 << (res->pdx + comp->numresolutions - 1 - resno));
dy = comp->dy * (1 << (res->pdy + comp->numresolutions - 1 - resno));
pi->dx = !pi->dx ? dx : int_min(pi->dx, dx);
pi->dy = !pi->dy ? dy : int_min(pi->dy, dy);
}
}
}
if (!pi->tp_on) {
pi->poc.ty0 = pi->ty0;
pi->poc.tx0 = pi->tx0;
pi->poc.ty1 = pi->ty1;
pi->poc.tx1 = pi->tx1;
}
for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
pi->y += pi->dy - (pi->y % pi->dy)) {
for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
pi->x += pi->dx - (pi->x % pi->dx)) {
for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
int levelno;
int trx0, try0;
int trx1, try1;
int rpx, rpy;
int prci, prcj;
comp = &pi->comps[pi->compno];
if (pi->resno >= comp->numresolutions) {
continue;
}
res = &comp->resolutions[pi->resno];
levelno = comp->numresolutions - 1 - pi->resno;
trx0 = int_ceildiv(pi->tx0, comp->dx << levelno);
try0 = int_ceildiv(pi->ty0, comp->dy << levelno);
trx1 = int_ceildiv(pi->tx1, comp->dx << levelno);
try1 = int_ceildiv(pi->ty1, comp->dy << levelno);
rpx = res->pdx + levelno;
rpy = res->pdy + levelno;
/* To avoid divisions by zero / undefined behaviour on shift */
if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
continue;
}
if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
((try0 << levelno) % (1 << rpy))))) {
continue;
}
if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
((trx0 << levelno) % (1 << rpx))))) {
continue;
}
if ((res->pw == 0) || (res->ph == 0)) {
continue;
}
if ((trx0 == trx1) || (try0 == try1)) {
continue;
}
prci = int_floordivpow2(int_ceildiv(pi->x, comp->dx << levelno), res->pdx)
- int_floordivpow2(trx0, res->pdx);
prcj = int_floordivpow2(int_ceildiv(pi->y, comp->dy << levelno), res->pdy)
- int_floordivpow2(try0, res->pdy);
pi->precno = prci + prcj * res->pw;
for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
pi->step_c + pi->precno * pi->step_p;
/* Avoids index out of bounds access with include*/
if (index >= pi->include_size) {
opj_pi_emit_error(pi, "Invalid access to pi->include");
return OPJ_FALSE;
}
if (!pi->include[index]) {
pi->include[index] = 1;
return OPJ_TRUE;
}
LABEL_SKIP:
;
}
}
}
}
}
return OPJ_FALSE;
}
| 169,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg)
{
struct bcm_tarang_data *pTarang = filp->private_data;
void __user *argp = (void __user *)arg;
struct bcm_mini_adapter *Adapter = pTarang->Adapter;
INT Status = STATUS_FAILURE;
int timeout = 0;
struct bcm_ioctl_buffer IoBuffer;
int bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX", cmd, arg);
if (_IOC_TYPE(cmd) != BCM_IOCTL)
return -EFAULT;
if (_IOC_DIR(cmd) & _IOC_READ)
Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd));
else if (_IOC_DIR(cmd) & _IOC_WRITE)
Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd));
else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE))
Status = STATUS_SUCCESS;
if (Status)
return -EFAULT;
if (Adapter->device_removed)
return -EFAULT;
if (FALSE == Adapter->fw_download_done) {
switch (cmd) {
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ:
case IOCTL_BCM_GPIO_SET_REQUEST:
case IOCTL_BCM_GPIO_STATUS_REQUEST:
return -EACCES;
default:
break;
}
}
Status = vendorextnIoctl(Adapter, cmd, arg);
if (Status != CONTINUE_COMMON_PATH)
return Status;
switch (cmd) {
/* Rdms for Swin Idle... */
case IOCTL_BCM_REGISTER_READ_PRIVATE: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff;
UINT Bufflen;
u16 temp_value;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
Bufflen = IoBuffer.OutputLength;
temp_value = 4 - (Bufflen % 4);
Bufflen += temp_value % 4;
temp_buff = kmalloc(Bufflen, GFP_KERNEL);
if (!temp_buff)
return -ENOMEM;
bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register,
(PUINT)temp_buff, Bufflen);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE_PRIVATE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_REGISTER_READ:
case IOCTL_BCM_EEPROM_REGISTER_READ: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff = NULL;
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Rdms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sRdmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Done On invalid Address : %x Access Denied.\n",
(int)sRdmBuffer.Register);
kfree(temp_buff);
return -EINVAL;
}
uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK;
bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE:
case IOCTL_BCM_EEPROM_REGISTER_WRITE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Wrms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sWrmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)sWrmBuffer.Register);
return -EINVAL;
}
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sWrmBuffer.Length);
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_GPIO_SET_REQUEST: {
UCHAR ucResetValue[4];
UINT value = 0;
UINT uiBit = 0;
UINT uiOperation = 0;
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
return -EACCES;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
uiOperation = gpio_info.uiGpioValue;
value = (1<<uiBit);
if (IsReqGpioIsLedInNVM(Adapter, value) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Sorry, Requested GPIO<0x%X> is not correspond to LED !!!", value);
Status = -EINVAL;
break;
}
/* Set - setting 1 */
if (uiOperation) {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to set the %dth GPIO\n", uiBit);
break;
}
} else {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to clear the %dth GPIO\n", uiBit);
break;
}
}
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"GPIO_MODE_REGISTER read failed");
break;
} else {
Status = STATUS_SUCCESS;
}
/* Set the gpio mode register to output */
*(UINT *)ucResetValue |= (1<<uiBit);
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER,
(PUINT)ucResetValue, sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO to output Mode\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to put GPIO in Output Mode\n");
break;
}
}
break;
case BCM_LED_THREAD_STATE_CHANGE_REQ: {
struct bcm_user_thread_req threadReq = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "User made LED thread InActive");
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
Status = -EACCES;
break;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(threadReq))
return -EINVAL;
if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
/* if LED thread is running(Actively or Inactively) set it state to make inactive */
if (Adapter->LEDInfo.led_thread_running) {
if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Activating thread req");
Adapter->DriverState = LED_THREAD_ACTIVE;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DeActivating Thread req.....");
Adapter->DriverState = LED_THREAD_INACTIVE;
}
/* signal thread. */
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
break;
case IOCTL_BCM_GPIO_STATUS_REQUEST: {
ULONG uiBit = 0;
UCHAR ucRead[4];
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EACCES;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
/* Set the gpio output register */
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER,
(PUINT)ucRead, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Failed\n");
return Status;
} else {
Status = STATUS_SUCCESS;
}
}
break;
case IOCTL_BCM_GPIO_MULTI_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX];
struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info;
memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info));
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_info))
return -EINVAL;
if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
/* Set the gpio output register */
if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) &
(pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) {
/* Set 1's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
pgpio_multi_info[WIMAX_IDX].uiGPIOValue;
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG,
(PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_SET_REG Failed.");
return Status;
}
/* Clear to 0's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
(~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue)));
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.");
return Status;
}
}
if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) {
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM to GPIO_PIN_STATE_REGISTER Failed.");
return Status;
} else {
Status = STATUS_SUCCESS;
}
pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue &
pgpio_multi_info[WIMAX_IDX].uiGPIOMask);
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_BCM_GPIO_MODE_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX];
struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_mode))
return -EINVAL;
if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Read of GPIO_MODE_REGISTER failed");
return Status;
} else {
Status = STATUS_SUCCESS;
}
/* Validating the request */
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) {
/* write all OUT's (1's) */
*(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* write all IN's (0's) */
*(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* Currently implemented return the modes of all GPIO's
* else needs to bit AND with mask
*/
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"WRM to GPIO_MODE_REGISTER Done");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"WRM to GPIO_MODE_REGISTER Failed");
Status = -EFAULT;
break;
}
} else {
/* if uiGPIOMask is 0 then return mode register configuration */
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ: {
PVOID pvBuffer = NULL;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(struct bcm_link_request))
return -EINVAL;
if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
down(&Adapter->LowPowerModeSync);
Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue,
!Adapter->bPreparingForLowPowerMode,
(1 * HZ));
if (Status == -ERESTARTSYS)
goto cntrlEnd;
if (Adapter->bPreparingForLowPowerMode) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Preparing Idle Mode is still True - Hence Rejecting control message\n");
Status = STATUS_FAILURE;
goto cntrlEnd;
}
Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer);
cntrlEnd:
up(&Adapter->LowPowerModeSync);
kfree(pvBuffer);
break;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_START: {
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (down_trylock(&Adapter->fw_download_sema))
return -EBUSY;
Adapter->bBinDownloaded = FALSE;
Adapter->fw_download_process_pid = current->pid;
Adapter->bCfgDownloaded = FALSE;
Adapter->fw_download_done = FALSE;
netif_carrier_off(Adapter->dev);
netif_stop_queue(Adapter->dev);
Status = reset_card_proc(Adapter);
if (Status) {
pr_err(PFX "%s: reset_card_proc Failed!\n", Adapter->dev->name);
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
mdelay(10);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD: {
struct bcm_firmware_info *psFwInfo = NULL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (!down_trylock(&Adapter->fw_download_sema)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Invalid way to download buffer. Use Start and then call this!!!\n");
up(&Adapter->fw_download_sema);
Status = -EINVAL;
return Status;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
up(&Adapter->fw_download_sema);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length for FW DLD is : %lx\n", IoBuffer.InputLength);
if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL);
if (!psFwInfo) {
up(&Adapter->fw_download_sema);
return -ENOMEM;
}
if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) {
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
return -EFAULT;
}
if (!psFwInfo->pvMappedFirmwareAddress ||
(psFwInfo->u32FirmwareLength == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Something else is wrong %lu\n",
psFwInfo->u32FirmwareLength);
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
Status = -EINVAL;
return Status;
}
Status = bcm_ioctl_fw_download(Adapter, psFwInfo);
if (Status != STATUS_SUCCESS) {
if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Configuration File Upload Failed\n");
else
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Firmware File Upload Failed\n");
/* up(&Adapter->fw_download_sema); */
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = DRIVER_INIT;
Adapter->LEDInfo.bLedInitDone = FALSE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
if (Status != STATUS_SUCCESS)
up(&Adapter->fw_download_sema);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "IOCTL: Firmware File Uploaded\n");
kfree(psFwInfo);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: {
if (!down_trylock(&Adapter->fw_download_sema)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"FW download blocked as EEPROM Read/Write is in progress\n");
up(&Adapter->fw_download_sema);
return -EACCES;
}
Adapter->bBinDownloaded = TRUE;
Adapter->bCfgDownloaded = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->downloadDDR = 0;
/* setting the Mips to Run */
Status = run_card_proc(Adapter);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Firm Download Failed\n");
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG,
DBG_LVL_ALL, "Firm Download Over...\n");
}
mdelay(10);
/* Wait for MailBox Interrupt */
if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter))
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Unable to send interrupt...\n");
timeout = 5*HZ;
Adapter->waiting_to_fw_download_done = FALSE;
wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue,
Adapter->waiting_to_fw_download_done, timeout);
Adapter->fw_download_process_pid = INVALID_PID;
Adapter->fw_download_done = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->PrevNumRecvDescs = 0;
atomic_set(&Adapter->cntrlpktCnt, 0);
Adapter->LinkUpStatus = 0;
Adapter->LinkStatus = 0;
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = FW_DOWNLOAD_DONE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
if (!timeout)
Status = -ENODEV;
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BE_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_RTPS_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_CHIP_RESET: {
INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock);
if (NVMAccess) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, " IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
down(&Adapter->RxAppControlQueuelock);
Status = reset_card_proc(Adapter);
flushAllAppQ();
up(&Adapter->RxAppControlQueuelock);
up(&Adapter->NVMRdmWrmLock);
ResetCounters(Adapter);
break;
}
case IOCTL_QOS_THRESHOLD: {
USHORT uiLoopIndex;
Status = 0;
for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) {
if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold,
(unsigned long __user *)arg)) {
Status = -EFAULT;
break;
}
}
break;
}
case IOCTL_DUMP_PACKET_INFO:
DumpPackInfo(Adapter);
DumpPhsRules(&Adapter->stBCMPhsContext);
Status = STATUS_SUCCESS;
break;
case IOCTL_GET_PACK_INFO:
if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_SWITCH_TRANSFER_MODE: {
UINT uiData = 0;
if (copy_from_user(&uiData, argp, sizeof(UINT)))
return -EFAULT;
if (uiData) {
/* Allow All Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\n");
Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE;
} else {
/* Allow IP only Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\n");
Adapter->TransferMode = IP_PACKET_ONLY_MODE;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_DRIVER_VERSION: {
ulong len;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1);
if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_CURRENT_STATUS: {
struct bcm_link_state link_state;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user failed..\n");
return -EFAULT;
}
if (IoBuffer.OutputLength != sizeof(link_state)) {
Status = -EINVAL;
break;
}
memset(&link_state, 0, sizeof(link_state));
link_state.bIdleMode = Adapter->IdleMode;
link_state.bShutdownMode = Adapter->bShutStatus;
link_state.ucLinkStatus = Adapter->LinkStatus;
if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy_to_user Failed..\n");
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_SET_MAC_TRACING: {
UINT tracing_flag;
/* copy ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if (tracing_flag)
Adapter->pTarangs->MacTracingEnabled = TRUE;
else
Adapter->pTarangs->MacTracingEnabled = FALSE;
break;
}
case IOCTL_BCM_GET_DSX_INDICATION: {
ULONG ulSFId = 0;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Mismatch req: %lx needed is =0x%zx!!!",
IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt));
return -EINVAL;
}
if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Get DSX Data SF ID is =%lx\n", ulSFId);
get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer);
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_GET_HOST_MIBS: {
PVOID temp_buff;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length Check failed %lu %zd\n",
IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs));
return -EINVAL;
}
/* FIXME: HOST_STATS are too big for kmalloc (122048)! */
temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
Status = ProcessGetHostMibs(Adapter, temp_buff);
GetDroppedAppCntrlPktMibs(temp_buff, pTarang);
if (Status != STATUS_FAILURE)
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) {
kfree(temp_buff);
return -EFAULT;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE:
if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) {
Adapter->usIdleModePattern = ABORT_IDLE_MODE;
Adapter->bWakeUpDevice = TRUE;
wake_up(&Adapter->process_rx_cntrlpkt);
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_BULK_WRM: {
struct bcm_bulk_wrm_buffer *pBulkBuffer;
UINT uiTempVar = 0;
PCHAR pvBuffer = NULL;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle/Shutdown Mode, Blocking Wrms\n");
Status = -EACCES;
break;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(ULONG) * 2)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer;
if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 ||
((ULONG)pBulkBuffer->Register & 0x3)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)pBulkBuffer->Register);
kfree(pvBuffer);
Status = -EINVAL;
break;
}
uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
kfree(pvBuffer);
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
Status = -EFAULT;
break;
}
if (pBulkBuffer->SwapEndian == FALSE)
Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
else
Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
if (Status != STATUS_SUCCESS)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Failed\n");
kfree(pvBuffer);
break;
}
case IOCTL_BCM_GET_NVM_SIZE:
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT)))
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_CAL_INIT: {
UINT uiSectorSize = 0 ;
if (Adapter->eNVMType == NVM_FLASH) {
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize,
sizeof(UINT)))
return -EFAULT;
} else {
if (IsFlash2x(Adapter)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT)))
return -EFAULT;
} else {
if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is in Idle/Shutdown Mode\n");
return -EACCES;
}
Adapter->uiSectorSize = uiSectorSize;
BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize);
}
}
Status = STATUS_SUCCESS;
} else {
Status = STATUS_FAILURE;
}
}
break;
case IOCTL_BCM_SET_DEBUG:
#ifdef DEBUG
{
struct bcm_user_debug_state sUserDebugState;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "In SET_DEBUG ioctl\n");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state)))
return -EFAULT;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x ",
sUserDebugState.OnOff, sUserDebugState.Type);
/* sUserDebugState.Subtype <<= 1; */
sUserDebugState.Subtype = 1 << sUserDebugState.Subtype;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "actual Subtype=0x%x\n", sUserDebugState.Subtype);
/* Update new 'DebugState' in the Adapter */
Adapter->stDebugState.type |= sUserDebugState.Type;
/* Subtype: A bitmap of 32 bits for Subtype per Type.
* Valid indexes in 'subtype' array: 1,2,4,8
* corresponding to valid Type values. Hence we can use the 'Type' field
* as the index value, ignoring the array entries 0,3,5,6,7 !
*/
if (sUserDebugState.OnOff)
Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype;
else
Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype;
BCM_SHOW_DEBUG_BITMAP(Adapter);
}
#endif
break;
case IOCTL_BCM_NVM_READ:
case IOCTL_BCM_NVM_WRITE: {
struct bcm_nvm_readwrite stNVMReadWrite;
PUCHAR pReadData = NULL;
ULONG ulDSDMagicNumInUsrBuff = 0;
struct timeval tv0, tv1;
memset(&tv0, 0, sizeof(struct timeval));
memset(&tv1, 0, sizeof(struct timeval));
if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "The Flash Control Section is Corrupted. Hence Rejection on NVM Read/Write\n");
return -EFAULT;
}
if (IsFlash2x(Adapter)) {
if ((Adapter->eActiveDSD != DSD0) &&
(Adapter->eActiveDSD != DSD1) &&
(Adapter->eActiveDSD != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "No DSD is active..hence NVM Command is blocked");
return STATUS_FAILURE;
}
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&stNVMReadWrite,
(IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer,
sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
/*
* Deny the access if the offset crosses the cal area limit.
*/
if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize)
return STATUS_FAILURE;
if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) {
/* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Can't allow access beyond NVM Size: 0x%x 0x%x\n", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); */
return STATUS_FAILURE;
}
pReadData = memdup_user(stNVMReadWrite.pBuffer,
stNVMReadWrite.uiNumBytes);
if (IS_ERR(pReadData))
return PTR_ERR(pReadData);
do_gettimeofday(&tv0);
if (IOCTL_BCM_NVM_READ == cmd) {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes);
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) {
kfree(pReadData);
return -EFAULT;
}
} else {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Adapter->bHeaderChangeAllowed = TRUE;
if (IsFlash2x(Adapter)) {
/*
* New Requirement:-
* DSD section updation will be allowed in two case:-
* 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull
* 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is
* corrupted then user space program first modify the DSD header with valid DSD sig so
* that this as well as further write may be worthwhile.
*
* This restriction has been put assuming that if DSD sig is corrupted, DSD
* data won't be considered valid.
*/
Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD);
if (Status != STATUS_SUCCESS) {
if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) ||
(stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE));
if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
}
}
Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify);
if (IsFlash2x(Adapter))
BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD);
Adapter->bHeaderChangeAllowed = FALSE;
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
}
do_gettimeofday(&tv1);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " timetaken by Write/read :%ld msec\n", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)/1000);
kfree(pReadData);
return STATUS_SUCCESS;
}
case IOCTL_BCM_FLASH2X_SECTION_READ: {
struct bcm_flash2x_readwrite sFlash2xRead = {0};
PUCHAR pReadBuff = NULL ;
UINT NOB = 0;
UINT BuffSize = 0;
UINT ReadBytes = 0;
UINT ReadOffset = 0;
void __user *OutPutBuff;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_READ Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xRead.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%x", sFlash2xRead.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xRead.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xRead.bVerify);
/* This was internal to driver for raw read. now it has ben exposed to user space app. */
if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE)
return STATUS_FAILURE;
NOB = sFlash2xRead.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB;
ReadOffset = sFlash2xRead.offset ;
OutPutBuff = IoBuffer.OutputBuffer;
pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
return -ENOMEM;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EACCES;
}
while (NOB) {
if (NOB > Adapter->uiSectorSize)
ReadBytes = Adapter->uiSectorSize;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes ;
}
}
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
}
break;
case IOCTL_BCM_FLASH2X_SECTION_WRITE: {
struct bcm_flash2x_readwrite sFlash2xWrite = {0};
PUCHAR pWriteBuff;
void __user *InputAddr;
UINT NOB = 0;
UINT BuffSize = 0;
UINT WriteOffset = 0;
UINT WriteBytes = 0;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
/* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_WRITE Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xWrite.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%d", sFlash2xWrite.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xWrite.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xWrite.bVerify);
if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Only VSA write is allowed");
return -EINVAL;
}
if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE)
return STATUS_FAILURE;
InputAddr = sFlash2xWrite.pDataBuff;
WriteOffset = sFlash2xWrite.offset;
NOB = sFlash2xWrite.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB ;
pWriteBuff = kmalloc(BuffSize, GFP_KERNEL);
if (pWriteBuff == NULL)
return -ENOMEM;
/* extracting the remainder of the given offset. */
WriteBytes = Adapter->uiSectorSize;
if (WriteOffset % Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize);
if (NOB < WriteBytes)
WriteBytes = NOB;
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EACCES;
}
BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section);
do {
Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to user failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EFAULT;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes);
/* Writing the data from Flash 2.x */
Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
NOB = NOB - WriteBytes;
if (NOB) {
WriteOffset = WriteOffset + WriteBytes;
InputAddr = InputAddr + WriteBytes;
if (NOB > Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize;
else
WriteBytes = NOB;
}
} while (NOB > 0);
BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
}
break;
case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: {
struct bcm_flash2x_bitmap *psFlash2xBitMap;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap))
return -EINVAL;
psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL);
if (psFlash2xBitMap == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory is not available");
return -ENOMEM;
}
/* Reading the Flash Sectio Bit map */
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(psFlash2xBitMap);
return -EACCES;
}
BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap);
up(&Adapter->NVMRdmWrmLock);
if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) {
kfree(psFlash2xBitMap);
return -EFAULT;
}
kfree(psFlash2xBitMap);
}
break;
case IOCTL_BCM_SET_ACTIVE_SECTION: {
enum bcm_flash2x_section_val eFlash2xSectionVal = 0;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SET_ACTIVE_SECTION Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal);
if (Status)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Failed to make it's priority Highest. Status %d", Status);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: {
/* Right Now we are taking care of only DSD */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called");
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_COPY_SECTION: {
struct bcm_flash2x_copy_section sCopySectStrut = {0};
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_COPY_SECTION Called");
Adapter->bAllDSDWriteAllow = FALSE;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed Status :%d", Status);
return -EFAULT;
}
Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of Copy_Section_Struct failed with Status :%d", Status);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source SEction :%x", sCopySectStrut.SrcSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Destination SEction :%x", sCopySectStrut.DstSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "offset :%x", sCopySectStrut.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "NOB :%x", sCopySectStrut.numOfBytes);
if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Source Section<%x> does not exixt in Flash ", sCopySectStrut.SrcSection);
return -EINVAL;
}
if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Destinatio Section<%x> does not exixt in Flash ", sCopySectStrut.DstSection);
return -EINVAL;
}
if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source and Destination section should be different");
return -EINVAL;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) {
if (IsNonCDLessDevice(Adapter)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is Non-CDLess hence won't have ISO !!");
Status = -EINVAL;
} else if (sCopySectStrut.numOfBytes == 0) {
Status = BcmCopyISO(Adapter, sCopySectStrut);
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Partial Copy of ISO section is not Allowed..");
Status = STATUS_FAILURE;
}
up(&Adapter->NVMRdmWrmLock);
return Status;
}
Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection,
sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_GET_FLASH_CS_INFO: {
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " IOCTL_BCM_GET_FLASH_CS_INFO Called");
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Connected device does not have flash");
Status = -EINVAL;
break;
}
if (IsFlash2x(Adapter) == TRUE) {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info)))
return -EFAULT;
} else {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info)))
return -EFAULT;
}
}
break;
case IOCTL_BCM_SELECT_DSD: {
UINT SectOfset = 0;
enum bcm_flash2x_section_val eFlash2xSectionVal;
eFlash2xSectionVal = NO_SECTION_VAL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SELECT_DSD Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Read Section :%d", eFlash2xSectionVal);
if ((eFlash2xSectionVal != DSD0) &&
(eFlash2xSectionVal != DSD1) &&
(eFlash2xSectionVal != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Passed section<%x> is not DSD section", eFlash2xSectionVal);
return STATUS_FAILURE;
}
SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal);
if (SectOfset == INVALID_OFFSET) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Provided Section val <%d> does not exixt in Flash 2.x", eFlash2xSectionVal);
return -EINVAL;
}
Adapter->bAllDSDWriteAllow = TRUE;
Adapter->ulFlashCalStart = SectOfset;
Adapter->eActiveDSD = eFlash2xSectionVal;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_NVM_RAW_READ: {
struct bcm_nvm_readwrite stNVMRead;
INT NOB ;
INT BuffSize ;
INT ReadOffset = 0;
UINT ReadBytes = 0 ;
PUCHAR pReadBuff;
void __user *OutPutBuff;
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "NVM TYPE is not Flash");
return -EINVAL;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user 1 failed\n");
return -EFAULT;
}
if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
NOB = stNVMRead.uiNumBytes;
/* In Raw-Read max Buff size : 64MB */
if (NOB > DEFAULT_BUFF_SIZE)
BuffSize = DEFAULT_BUFF_SIZE;
else
BuffSize = NOB;
ReadOffset = stNVMRead.uiOffset;
OutPutBuff = stNVMRead.pBuffer;
pReadBuff = kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
Status = -ENOMEM;
break;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
kfree(pReadBuff);
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Adapter->bFlashRawRead = TRUE;
while (NOB) {
if (NOB > DEFAULT_BUFF_SIZE)
ReadBytes = DEFAULT_BUFF_SIZE;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes;
}
}
Adapter->bFlashRawRead = FALSE;
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
break;
}
case IOCTL_BCM_CNTRLMSG_MASK: {
ULONG RxCntrlMsgBitMask = 0;
/* Copy Ioctl Buffer structure */
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of Ioctl buffer is failed from user space");
return -EFAULT;
}
if (IoBuffer.InputLength != sizeof(unsigned long)) {
Status = -EINVAL;
break;
}
Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of control bit mask failed from user space");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\n Got user defined cntrl msg bit mask :%lx", RxCntrlMsgBitMask);
pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask;
}
break;
case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: {
struct bcm_driver_info DevInfo;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\n");
DevInfo.MaxRDMBufferSize = BUFFER_4K;
DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START;
DevInfo.u32RxAlignmentCorrection = 0;
DevInfo.u32NVMType = Adapter->eNVMType;
DevInfo.u32InterfaceType = BCM_USB;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(DevInfo))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo)))
return -EFAULT;
}
break;
case IOCTL_BCM_TIME_SINCE_NET_ENTRY: {
struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_TIME_SINCE_NET_ENTRY called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed))
return -EINVAL;
stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry;
if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed)))
return -EFAULT;
}
break;
case IOCTL_CLOSE_NOTIFICATION:
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_CLOSE_NOTIFICATION");
break;
default:
pr_info(DRV_NAME ": unknown ioctl cmd=%#x\n", cmd);
Status = STATUS_FAILURE;
break;
}
return Status;
}
Commit Message: Staging: bcm: info leak in ioctl
The DevInfo.u32Reserved[] array isn't initialized so it leaks kernel
information to user space.
Reported-by: Nico Golde <[email protected]>
Reported-by: Fabian Yamaguchi <[email protected]>
Signed-off-by: Dan Carpenter <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static long bcm_char_ioctl(struct file *filp, UINT cmd, ULONG arg)
{
struct bcm_tarang_data *pTarang = filp->private_data;
void __user *argp = (void __user *)arg;
struct bcm_mini_adapter *Adapter = pTarang->Adapter;
INT Status = STATUS_FAILURE;
int timeout = 0;
struct bcm_ioctl_buffer IoBuffer;
int bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Parameters Passed to control IOCTL cmd=0x%X arg=0x%lX", cmd, arg);
if (_IOC_TYPE(cmd) != BCM_IOCTL)
return -EFAULT;
if (_IOC_DIR(cmd) & _IOC_READ)
Status = !access_ok(VERIFY_WRITE, argp, _IOC_SIZE(cmd));
else if (_IOC_DIR(cmd) & _IOC_WRITE)
Status = !access_ok(VERIFY_READ, argp, _IOC_SIZE(cmd));
else if (_IOC_NONE == (_IOC_DIR(cmd) & _IOC_NONE))
Status = STATUS_SUCCESS;
if (Status)
return -EFAULT;
if (Adapter->device_removed)
return -EFAULT;
if (FALSE == Adapter->fw_download_done) {
switch (cmd) {
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ:
case IOCTL_BCM_GPIO_SET_REQUEST:
case IOCTL_BCM_GPIO_STATUS_REQUEST:
return -EACCES;
default:
break;
}
}
Status = vendorextnIoctl(Adapter, cmd, arg);
if (Status != CONTINUE_COMMON_PATH)
return Status;
switch (cmd) {
/* Rdms for Swin Idle... */
case IOCTL_BCM_REGISTER_READ_PRIVATE: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff;
UINT Bufflen;
u16 temp_value;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
Bufflen = IoBuffer.OutputLength;
temp_value = 4 - (Bufflen % 4);
Bufflen += temp_value % 4;
temp_buff = kmalloc(Bufflen, GFP_KERNEL);
if (!temp_buff)
return -ENOMEM;
bytes = rdmalt(Adapter, (UINT)sRdmBuffer.Register,
(PUINT)temp_buff, Bufflen);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE_PRIVATE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmalt(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_REGISTER_READ:
case IOCTL_BCM_EEPROM_REGISTER_READ: {
struct bcm_rdm_buffer sRdmBuffer = {0};
PCHAR temp_buff = NULL;
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Rdms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sRdmBuffer))
return -EINVAL;
if (copy_from_user(&sRdmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IoBuffer.OutputLength > USHRT_MAX ||
IoBuffer.OutputLength == 0) {
return -EINVAL;
}
temp_buff = kmalloc(IoBuffer.OutputLength, GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
if ((((ULONG)sRdmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sRdmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Done On invalid Address : %x Access Denied.\n",
(int)sRdmBuffer.Register);
kfree(temp_buff);
return -EINVAL;
}
uiTempVar = sRdmBuffer.Register & EEPROM_REJECT_MASK;
bytes = rdmaltWithLock(Adapter, (UINT)sRdmBuffer.Register, (PUINT)temp_buff, IoBuffer.OutputLength);
if (bytes > 0) {
Status = STATUS_SUCCESS;
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, bytes)) {
kfree(temp_buff);
return -EFAULT;
}
} else {
Status = bytes;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_REGISTER_WRITE:
case IOCTL_BCM_EEPROM_REGISTER_WRITE: {
struct bcm_wrm_buffer sWrmBuffer = {0};
UINT uiTempVar = 0;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle Mode, Blocking Wrms\n");
return -EACCES;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(sWrmBuffer))
return -EINVAL;
/* Get WrmBuffer structure */
if (copy_from_user(&sWrmBuffer, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if ((((ULONG)sWrmBuffer.Register & 0x0F000000) != 0x0F000000) ||
((ULONG)sWrmBuffer.Register & 0x3)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)sWrmBuffer.Register);
return -EINVAL;
}
uiTempVar = sWrmBuffer.Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize) & VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
return -EFAULT;
}
Status = wrmaltWithLock(Adapter, (UINT)sWrmBuffer.Register,
(PUINT)sWrmBuffer.Data, sWrmBuffer.Length);
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "WRM Done\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "WRM Failed\n");
Status = -EFAULT;
}
break;
}
case IOCTL_BCM_GPIO_SET_REQUEST: {
UCHAR ucResetValue[4];
UINT value = 0;
UINT uiBit = 0;
UINT uiOperation = 0;
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
return -EACCES;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
uiOperation = gpio_info.uiGpioValue;
value = (1<<uiBit);
if (IsReqGpioIsLedInNVM(Adapter, value) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Sorry, Requested GPIO<0x%X> is not correspond to LED !!!", value);
Status = -EINVAL;
break;
}
/* Set - setting 1 */
if (uiOperation) {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to set the %dth GPIO\n", uiBit);
break;
}
} else {
/* Set the gpio output register */
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)(&value), sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO bit\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to clear the %dth GPIO\n", uiBit);
break;
}
}
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"GPIO_MODE_REGISTER read failed");
break;
} else {
Status = STATUS_SUCCESS;
}
/* Set the gpio mode register to output */
*(UINT *)ucResetValue |= (1<<uiBit);
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER,
(PUINT)ucResetValue, sizeof(UINT));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Set the GPIO to output Mode\n");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Failed to put GPIO in Output Mode\n");
break;
}
}
break;
case BCM_LED_THREAD_STATE_CHANGE_REQ: {
struct bcm_user_thread_req threadReq = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "User made LED thread InActive");
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "GPIO Can't be set/clear in Low power Mode");
Status = -EACCES;
break;
}
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(threadReq))
return -EINVAL;
if (copy_from_user(&threadReq, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
/* if LED thread is running(Actively or Inactively) set it state to make inactive */
if (Adapter->LEDInfo.led_thread_running) {
if (threadReq.ThreadState == LED_THREAD_ACTIVATION_REQ) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Activating thread req");
Adapter->DriverState = LED_THREAD_ACTIVE;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DeActivating Thread req.....");
Adapter->DriverState = LED_THREAD_INACTIVE;
}
/* signal thread. */
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
break;
case IOCTL_BCM_GPIO_STATUS_REQUEST: {
ULONG uiBit = 0;
UCHAR ucRead[4];
struct bcm_gpio_info gpio_info = {0};
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EACCES;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_info))
return -EINVAL;
if (copy_from_user(&gpio_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
uiBit = gpio_info.uiGpioNumber;
/* Set the gpio output register */
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER,
(PUINT)ucRead, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM Failed\n");
return Status;
} else {
Status = STATUS_SUCCESS;
}
}
break;
case IOCTL_BCM_GPIO_MULTI_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_info gpio_multi_info[MAX_IDX];
struct bcm_gpio_multi_info *pgpio_multi_info = (struct bcm_gpio_multi_info *)gpio_multi_info;
memset(pgpio_multi_info, 0, MAX_IDX * sizeof(struct bcm_gpio_multi_info));
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_info))
return -EINVAL;
if (copy_from_user(&gpio_multi_info, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_info[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_info[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
/* Set the gpio output register */
if ((pgpio_multi_info[WIMAX_IDX].uiGPIOMask) &
(pgpio_multi_info[WIMAX_IDX].uiGPIOCommand)) {
/* Set 1's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
pgpio_multi_info[WIMAX_IDX].uiGPIOValue;
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_SET_REG,
(PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_SET_REG Failed.");
return Status;
}
/* Clear to 0's in GPIO OUTPUT REGISTER */
*(UINT *)ucResetValue = (pgpio_multi_info[WIMAX_IDX].uiGPIOMask &
pgpio_multi_info[WIMAX_IDX].uiGPIOCommand &
(~(pgpio_multi_info[WIMAX_IDX].uiGPIOValue)));
if (*(UINT *) ucResetValue)
Status = wrmaltWithLock(Adapter, BCM_GPIO_OUTPUT_CLR_REG, (PUINT)ucResetValue, sizeof(ULONG));
if (Status != STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM to BCM_GPIO_OUTPUT_CLR_REG Failed.");
return Status;
}
}
if (pgpio_multi_info[WIMAX_IDX].uiGPIOMask) {
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_PIN_STATE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "RDM to GPIO_PIN_STATE_REGISTER Failed.");
return Status;
} else {
Status = STATUS_SUCCESS;
}
pgpio_multi_info[WIMAX_IDX].uiGPIOValue = (*(UINT *)ucResetValue &
pgpio_multi_info[WIMAX_IDX].uiGPIOMask);
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_info, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_BCM_GPIO_MODE_REQUEST: {
UCHAR ucResetValue[4];
struct bcm_gpio_multi_mode gpio_multi_mode[MAX_IDX];
struct bcm_gpio_multi_mode *pgpio_multi_mode = (struct bcm_gpio_multi_mode *)gpio_multi_mode;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE))
return -EINVAL;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength > sizeof(gpio_multi_mode))
return -EINVAL;
if (copy_from_user(&gpio_multi_mode, IoBuffer.InputBuffer, IoBuffer.InputLength))
return -EFAULT;
bytes = rdmaltWithLock(Adapter, (UINT)GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(UINT));
if (bytes < 0) {
Status = bytes;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Read of GPIO_MODE_REGISTER failed");
return Status;
} else {
Status = STATUS_SUCCESS;
}
/* Validating the request */
if (IsReqGpioIsLedInNVM(Adapter, pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Sorry, Requested GPIO<0x%X> is not correspond to NVM LED bit map<0x%X>!!!",
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask, Adapter->gpioBitMap);
Status = -EINVAL;
break;
}
if (pgpio_multi_mode[WIMAX_IDX].uiGPIOMask) {
/* write all OUT's (1's) */
*(UINT *) ucResetValue |= (pgpio_multi_mode[WIMAX_IDX].uiGPIOMode &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* write all IN's (0's) */
*(UINT *) ucResetValue &= ~((~pgpio_multi_mode[WIMAX_IDX].uiGPIOMode) &
pgpio_multi_mode[WIMAX_IDX].uiGPIOMask);
/* Currently implemented return the modes of all GPIO's
* else needs to bit AND with mask
*/
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
Status = wrmaltWithLock(Adapter, GPIO_MODE_REGISTER, (PUINT)ucResetValue, sizeof(ULONG));
if (Status == STATUS_SUCCESS) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"WRM to GPIO_MODE_REGISTER Done");
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"WRM to GPIO_MODE_REGISTER Failed");
Status = -EFAULT;
break;
}
} else {
/* if uiGPIOMask is 0 then return mode register configuration */
pgpio_multi_mode[WIMAX_IDX].uiGPIOMode = *(UINT *)ucResetValue;
}
Status = copy_to_user(IoBuffer.OutputBuffer, &gpio_multi_mode, IoBuffer.OutputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Failed while copying Content to IOBufer for user space err:%d", Status);
return -EFAULT;
}
}
break;
case IOCTL_MAC_ADDR_REQ:
case IOCTL_LINK_REQ:
case IOCTL_CM_REQUEST:
case IOCTL_SS_INFO_REQ:
case IOCTL_SEND_CONTROL_MESSAGE:
case IOCTL_IDLE_REQ: {
PVOID pvBuffer = NULL;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(struct bcm_link_request))
return -EINVAL;
if (IoBuffer.InputLength > MAX_CNTL_PKT_SIZE)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
down(&Adapter->LowPowerModeSync);
Status = wait_event_interruptible_timeout(Adapter->lowpower_mode_wait_queue,
!Adapter->bPreparingForLowPowerMode,
(1 * HZ));
if (Status == -ERESTARTSYS)
goto cntrlEnd;
if (Adapter->bPreparingForLowPowerMode) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"Preparing Idle Mode is still True - Hence Rejecting control message\n");
Status = STATUS_FAILURE;
goto cntrlEnd;
}
Status = CopyBufferToControlPacket(Adapter, (PVOID)pvBuffer);
cntrlEnd:
up(&Adapter->LowPowerModeSync);
kfree(pvBuffer);
break;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_START: {
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL,
"IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (down_trylock(&Adapter->fw_download_sema))
return -EBUSY;
Adapter->bBinDownloaded = FALSE;
Adapter->fw_download_process_pid = current->pid;
Adapter->bCfgDownloaded = FALSE;
Adapter->fw_download_done = FALSE;
netif_carrier_off(Adapter->dev);
netif_stop_queue(Adapter->dev);
Status = reset_card_proc(Adapter);
if (Status) {
pr_err(PFX "%s: reset_card_proc Failed!\n", Adapter->dev->name);
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
mdelay(10);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD: {
struct bcm_firmware_info *psFwInfo = NULL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Starting the firmware download PID =0x%x!!!!\n", current->pid);
if (!down_trylock(&Adapter->fw_download_sema)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Invalid way to download buffer. Use Start and then call this!!!\n");
up(&Adapter->fw_download_sema);
Status = -EINVAL;
return Status;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
up(&Adapter->fw_download_sema);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length for FW DLD is : %lx\n", IoBuffer.InputLength);
if (IoBuffer.InputLength > sizeof(struct bcm_firmware_info)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
psFwInfo = kmalloc(sizeof(*psFwInfo), GFP_KERNEL);
if (!psFwInfo) {
up(&Adapter->fw_download_sema);
return -ENOMEM;
}
if (copy_from_user(psFwInfo, IoBuffer.InputBuffer, IoBuffer.InputLength)) {
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
return -EFAULT;
}
if (!psFwInfo->pvMappedFirmwareAddress ||
(psFwInfo->u32FirmwareLength == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Something else is wrong %lu\n",
psFwInfo->u32FirmwareLength);
up(&Adapter->fw_download_sema);
kfree(psFwInfo);
Status = -EINVAL;
return Status;
}
Status = bcm_ioctl_fw_download(Adapter, psFwInfo);
if (Status != STATUS_SUCCESS) {
if (psFwInfo->u32StartingAddress == CONFIG_BEGIN_ADDR)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Configuration File Upload Failed\n");
else
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL: Firmware File Upload Failed\n");
/* up(&Adapter->fw_download_sema); */
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = DRIVER_INIT;
Adapter->LEDInfo.bLedInitDone = FALSE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
}
if (Status != STATUS_SUCCESS)
up(&Adapter->fw_download_sema);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, OSAL_DBG, DBG_LVL_ALL, "IOCTL: Firmware File Uploaded\n");
kfree(psFwInfo);
return Status;
}
case IOCTL_BCM_BUFFER_DOWNLOAD_STOP: {
if (!down_trylock(&Adapter->fw_download_sema)) {
up(&Adapter->fw_download_sema);
return -EINVAL;
}
if (down_trylock(&Adapter->NVMRdmWrmLock)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"FW download blocked as EEPROM Read/Write is in progress\n");
up(&Adapter->fw_download_sema);
return -EACCES;
}
Adapter->bBinDownloaded = TRUE;
Adapter->bCfgDownloaded = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->downloadDDR = 0;
/* setting the Mips to Run */
Status = run_card_proc(Adapter);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Firm Download Failed\n");
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG,
DBG_LVL_ALL, "Firm Download Over...\n");
}
mdelay(10);
/* Wait for MailBox Interrupt */
if (StartInterruptUrb((struct bcm_interface_adapter *)Adapter->pvInterfaceAdapter))
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Unable to send interrupt...\n");
timeout = 5*HZ;
Adapter->waiting_to_fw_download_done = FALSE;
wait_event_timeout(Adapter->ioctl_fw_dnld_wait_queue,
Adapter->waiting_to_fw_download_done, timeout);
Adapter->fw_download_process_pid = INVALID_PID;
Adapter->fw_download_done = TRUE;
atomic_set(&Adapter->CurrNumFreeTxDesc, 0);
Adapter->CurrNumRecvDescs = 0;
Adapter->PrevNumRecvDescs = 0;
atomic_set(&Adapter->cntrlpktCnt, 0);
Adapter->LinkUpStatus = 0;
Adapter->LinkStatus = 0;
if (Adapter->LEDInfo.led_thread_running & BCM_LED_THREAD_RUNNING_ACTIVELY) {
Adapter->DriverState = FW_DOWNLOAD_DONE;
wake_up(&Adapter->LEDInfo.notify_led_event);
}
if (!timeout)
Status = -ENODEV;
up(&Adapter->fw_download_sema);
up(&Adapter->NVMRdmWrmLock);
return Status;
}
case IOCTL_BE_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->BEBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_RTPS_BUCKET_SIZE:
Status = 0;
if (get_user(Adapter->rtPSBucketSize, (unsigned long __user *)arg))
Status = -EFAULT;
break;
case IOCTL_CHIP_RESET: {
INT NVMAccess = down_trylock(&Adapter->NVMRdmWrmLock);
if (NVMAccess) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, " IOCTL_BCM_CHIP_RESET not allowed as EEPROM Read/Write is in progress\n");
return -EACCES;
}
down(&Adapter->RxAppControlQueuelock);
Status = reset_card_proc(Adapter);
flushAllAppQ();
up(&Adapter->RxAppControlQueuelock);
up(&Adapter->NVMRdmWrmLock);
ResetCounters(Adapter);
break;
}
case IOCTL_QOS_THRESHOLD: {
USHORT uiLoopIndex;
Status = 0;
for (uiLoopIndex = 0; uiLoopIndex < NO_OF_QUEUES; uiLoopIndex++) {
if (get_user(Adapter->PackInfo[uiLoopIndex].uiThreshold,
(unsigned long __user *)arg)) {
Status = -EFAULT;
break;
}
}
break;
}
case IOCTL_DUMP_PACKET_INFO:
DumpPackInfo(Adapter);
DumpPhsRules(&Adapter->stBCMPhsContext);
Status = STATUS_SUCCESS;
break;
case IOCTL_GET_PACK_INFO:
if (copy_to_user(argp, &Adapter->PackInfo, sizeof(struct bcm_packet_info)*NO_OF_QUEUES))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_SWITCH_TRANSFER_MODE: {
UINT uiData = 0;
if (copy_from_user(&uiData, argp, sizeof(UINT)))
return -EFAULT;
if (uiData) {
/* Allow All Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: ETH_PACKET_TUNNELING_MODE\n");
Adapter->TransferMode = ETH_PACKET_TUNNELING_MODE;
} else {
/* Allow IP only Packets */
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SWITCH_TRANSFER_MODE: IP_PACKET_ONLY_MODE\n");
Adapter->TransferMode = IP_PACKET_ONLY_MODE;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_DRIVER_VERSION: {
ulong len;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
len = min_t(ulong, IoBuffer.OutputLength, strlen(DRV_VERSION) + 1);
if (copy_to_user(IoBuffer.OutputBuffer, DRV_VERSION, len))
return -EFAULT;
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_GET_CURRENT_STATUS: {
struct bcm_link_state link_state;
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user failed..\n");
return -EFAULT;
}
if (IoBuffer.OutputLength != sizeof(link_state)) {
Status = -EINVAL;
break;
}
memset(&link_state, 0, sizeof(link_state));
link_state.bIdleMode = Adapter->IdleMode;
link_state.bShutdownMode = Adapter->bShutStatus;
link_state.ucLinkStatus = Adapter->LinkStatus;
if (copy_to_user(IoBuffer.OutputBuffer, &link_state, min_t(size_t, sizeof(link_state), IoBuffer.OutputLength))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy_to_user Failed..\n");
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
}
case IOCTL_BCM_SET_MAC_TRACING: {
UINT tracing_flag;
/* copy ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&tracing_flag, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if (tracing_flag)
Adapter->pTarangs->MacTracingEnabled = TRUE;
else
Adapter->pTarangs->MacTracingEnabled = FALSE;
break;
}
case IOCTL_BCM_GET_DSX_INDICATION: {
ULONG ulSFId = 0;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_add_indication_alt)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Mismatch req: %lx needed is =0x%zx!!!",
IoBuffer.OutputLength, sizeof(struct bcm_add_indication_alt));
return -EINVAL;
}
if (copy_from_user(&ulSFId, IoBuffer.InputBuffer, sizeof(ulSFId)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Get DSX Data SF ID is =%lx\n", ulSFId);
get_dsx_sf_data_to_application(Adapter, ulSFId, IoBuffer.OutputBuffer);
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_GET_HOST_MIBS: {
PVOID temp_buff;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_host_stats_mibs)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0,
"Length Check failed %lu %zd\n",
IoBuffer.OutputLength, sizeof(struct bcm_host_stats_mibs));
return -EINVAL;
}
/* FIXME: HOST_STATS are too big for kmalloc (122048)! */
temp_buff = kzalloc(sizeof(struct bcm_host_stats_mibs), GFP_KERNEL);
if (!temp_buff)
return STATUS_FAILURE;
Status = ProcessGetHostMibs(Adapter, temp_buff);
GetDroppedAppCntrlPktMibs(temp_buff, pTarang);
if (Status != STATUS_FAILURE)
if (copy_to_user(IoBuffer.OutputBuffer, temp_buff, sizeof(struct bcm_host_stats_mibs))) {
kfree(temp_buff);
return -EFAULT;
}
kfree(temp_buff);
break;
}
case IOCTL_BCM_WAKE_UP_DEVICE_FROM_IDLE:
if ((FALSE == Adapter->bTriedToWakeUpFromlowPowerMode) && (TRUE == Adapter->IdleMode)) {
Adapter->usIdleModePattern = ABORT_IDLE_MODE;
Adapter->bWakeUpDevice = TRUE;
wake_up(&Adapter->process_rx_cntrlpkt);
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_BULK_WRM: {
struct bcm_bulk_wrm_buffer *pBulkBuffer;
UINT uiTempVar = 0;
PCHAR pvBuffer = NULL;
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "Device in Idle/Shutdown Mode, Blocking Wrms\n");
Status = -EACCES;
break;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.InputLength < sizeof(ULONG) * 2)
return -EINVAL;
pvBuffer = memdup_user(IoBuffer.InputBuffer,
IoBuffer.InputLength);
if (IS_ERR(pvBuffer))
return PTR_ERR(pvBuffer);
pBulkBuffer = (struct bcm_bulk_wrm_buffer *)pvBuffer;
if (((ULONG)pBulkBuffer->Register & 0x0F000000) != 0x0F000000 ||
((ULONG)pBulkBuffer->Register & 0x3)) {
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Done On invalid Address : %x Access Denied.\n", (int)pBulkBuffer->Register);
kfree(pvBuffer);
Status = -EINVAL;
break;
}
uiTempVar = pBulkBuffer->Register & EEPROM_REJECT_MASK;
if (!((Adapter->pstargetparams->m_u32Customize)&VSG_MODE) &&
((uiTempVar == EEPROM_REJECT_REG_1) ||
(uiTempVar == EEPROM_REJECT_REG_2) ||
(uiTempVar == EEPROM_REJECT_REG_3) ||
(uiTempVar == EEPROM_REJECT_REG_4)) &&
(cmd == IOCTL_BCM_REGISTER_WRITE)) {
kfree(pvBuffer);
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "EEPROM Access Denied, not in VSG Mode\n");
Status = -EFAULT;
break;
}
if (pBulkBuffer->SwapEndian == FALSE)
Status = wrmWithLock(Adapter, (UINT)pBulkBuffer->Register, (PCHAR)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
else
Status = wrmaltWithLock(Adapter, (UINT)pBulkBuffer->Register, (PUINT)pBulkBuffer->Values, IoBuffer.InputLength - 2*sizeof(ULONG));
if (Status != STATUS_SUCCESS)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "WRM Failed\n");
kfree(pvBuffer);
break;
}
case IOCTL_BCM_GET_NVM_SIZE:
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (Adapter->eNVMType == NVM_EEPROM || Adapter->eNVMType == NVM_FLASH) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiNVMDSDSize, sizeof(UINT)))
return -EFAULT;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_CAL_INIT: {
UINT uiSectorSize = 0 ;
if (Adapter->eNVMType == NVM_FLASH) {
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&uiSectorSize, IoBuffer.InputBuffer, sizeof(UINT)))
return -EFAULT;
if ((uiSectorSize < MIN_SECTOR_SIZE) || (uiSectorSize > MAX_SECTOR_SIZE)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize,
sizeof(UINT)))
return -EFAULT;
} else {
if (IsFlash2x(Adapter)) {
if (copy_to_user(IoBuffer.OutputBuffer, &Adapter->uiSectorSize, sizeof(UINT)))
return -EFAULT;
} else {
if ((TRUE == Adapter->bShutStatus) || (TRUE == Adapter->IdleMode)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is in Idle/Shutdown Mode\n");
return -EACCES;
}
Adapter->uiSectorSize = uiSectorSize;
BcmUpdateSectorSize(Adapter, Adapter->uiSectorSize);
}
}
Status = STATUS_SUCCESS;
} else {
Status = STATUS_FAILURE;
}
}
break;
case IOCTL_BCM_SET_DEBUG:
#ifdef DEBUG
{
struct bcm_user_debug_state sUserDebugState;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "In SET_DEBUG ioctl\n");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&sUserDebugState, IoBuffer.InputBuffer, sizeof(struct bcm_user_debug_state)))
return -EFAULT;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "IOCTL_BCM_SET_DEBUG: OnOff=%d Type = 0x%x ",
sUserDebugState.OnOff, sUserDebugState.Type);
/* sUserDebugState.Subtype <<= 1; */
sUserDebugState.Subtype = 1 << sUserDebugState.Subtype;
BCM_DEBUG_PRINT (Adapter, DBG_TYPE_PRINTK, 0, 0, "actual Subtype=0x%x\n", sUserDebugState.Subtype);
/* Update new 'DebugState' in the Adapter */
Adapter->stDebugState.type |= sUserDebugState.Type;
/* Subtype: A bitmap of 32 bits for Subtype per Type.
* Valid indexes in 'subtype' array: 1,2,4,8
* corresponding to valid Type values. Hence we can use the 'Type' field
* as the index value, ignoring the array entries 0,3,5,6,7 !
*/
if (sUserDebugState.OnOff)
Adapter->stDebugState.subtype[sUserDebugState.Type] |= sUserDebugState.Subtype;
else
Adapter->stDebugState.subtype[sUserDebugState.Type] &= ~sUserDebugState.Subtype;
BCM_SHOW_DEBUG_BITMAP(Adapter);
}
#endif
break;
case IOCTL_BCM_NVM_READ:
case IOCTL_BCM_NVM_WRITE: {
struct bcm_nvm_readwrite stNVMReadWrite;
PUCHAR pReadData = NULL;
ULONG ulDSDMagicNumInUsrBuff = 0;
struct timeval tv0, tv1;
memset(&tv0, 0, sizeof(struct timeval));
memset(&tv1, 0, sizeof(struct timeval));
if ((Adapter->eNVMType == NVM_FLASH) && (Adapter->uiFlashLayoutMajorVersion == 0)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "The Flash Control Section is Corrupted. Hence Rejection on NVM Read/Write\n");
return -EFAULT;
}
if (IsFlash2x(Adapter)) {
if ((Adapter->eActiveDSD != DSD0) &&
(Adapter->eActiveDSD != DSD1) &&
(Adapter->eActiveDSD != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "No DSD is active..hence NVM Command is blocked");
return STATUS_FAILURE;
}
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (copy_from_user(&stNVMReadWrite,
(IOCTL_BCM_NVM_READ == cmd) ? IoBuffer.OutputBuffer : IoBuffer.InputBuffer,
sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
/*
* Deny the access if the offset crosses the cal area limit.
*/
if (stNVMReadWrite.uiNumBytes > Adapter->uiNVMDSDSize)
return STATUS_FAILURE;
if (stNVMReadWrite.uiOffset > Adapter->uiNVMDSDSize - stNVMReadWrite.uiNumBytes) {
/* BCM_DEBUG_PRINT(Adapter,DBG_TYPE_PRINTK, 0, 0,"Can't allow access beyond NVM Size: 0x%x 0x%x\n", stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes); */
return STATUS_FAILURE;
}
pReadData = memdup_user(stNVMReadWrite.pBuffer,
stNVMReadWrite.uiNumBytes);
if (IS_ERR(pReadData))
return PTR_ERR(pReadData);
do_gettimeofday(&tv0);
if (IOCTL_BCM_NVM_READ == cmd) {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Status = BeceemNVMRead(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes);
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
if (copy_to_user(stNVMReadWrite.pBuffer, pReadData, stNVMReadWrite.uiNumBytes)) {
kfree(pReadData);
return -EFAULT;
}
} else {
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return -EACCES;
}
Adapter->bHeaderChangeAllowed = TRUE;
if (IsFlash2x(Adapter)) {
/*
* New Requirement:-
* DSD section updation will be allowed in two case:-
* 1. if DSD sig is present in DSD header means dongle is ok and updation is fruitfull
* 2. if point 1 failes then user buff should have DSD sig. this point ensures that if dongle is
* corrupted then user space program first modify the DSD header with valid DSD sig so
* that this as well as further write may be worthwhile.
*
* This restriction has been put assuming that if DSD sig is corrupted, DSD
* data won't be considered valid.
*/
Status = BcmFlash2xCorruptSig(Adapter, Adapter->eActiveDSD);
if (Status != STATUS_SUCCESS) {
if (((stNVMReadWrite.uiOffset + stNVMReadWrite.uiNumBytes) != Adapter->uiNVMDSDSize) ||
(stNVMReadWrite.uiNumBytes < SIGNATURE_SIZE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
ulDSDMagicNumInUsrBuff = ntohl(*(PUINT)(pReadData + stNVMReadWrite.uiNumBytes - SIGNATURE_SIZE));
if (ulDSDMagicNumInUsrBuff != DSD_IMAGE_MAGIC_NUMBER) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "DSD Sig is present neither in Flash nor User provided Input..");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadData);
return Status;
}
}
}
Status = BeceemNVMWrite(Adapter, (PUINT)pReadData, stNVMReadWrite.uiOffset, stNVMReadWrite.uiNumBytes, stNVMReadWrite.bVerify);
if (IsFlash2x(Adapter))
BcmFlash2xWriteSig(Adapter, Adapter->eActiveDSD);
Adapter->bHeaderChangeAllowed = FALSE;
up(&Adapter->NVMRdmWrmLock);
if (Status != STATUS_SUCCESS) {
kfree(pReadData);
return Status;
}
}
do_gettimeofday(&tv1);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " timetaken by Write/read :%ld msec\n", (tv1.tv_sec - tv0.tv_sec)*1000 + (tv1.tv_usec - tv0.tv_usec)/1000);
kfree(pReadData);
return STATUS_SUCCESS;
}
case IOCTL_BCM_FLASH2X_SECTION_READ: {
struct bcm_flash2x_readwrite sFlash2xRead = {0};
PUCHAR pReadBuff = NULL ;
UINT NOB = 0;
UINT BuffSize = 0;
UINT ReadBytes = 0;
UINT ReadOffset = 0;
void __user *OutPutBuff;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_READ Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xRead, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xRead.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%x", sFlash2xRead.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xRead.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xRead.bVerify);
/* This was internal to driver for raw read. now it has ben exposed to user space app. */
if (validateFlash2xReadWrite(Adapter, &sFlash2xRead) == FALSE)
return STATUS_FAILURE;
NOB = sFlash2xRead.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB;
ReadOffset = sFlash2xRead.offset ;
OutPutBuff = IoBuffer.OutputBuffer;
pReadBuff = (PCHAR)kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
return -ENOMEM;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EACCES;
}
while (NOB) {
if (NOB > Adapter->uiSectorSize)
ReadBytes = Adapter->uiSectorSize;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BcmFlash2xBulkRead(Adapter, (PUINT)pReadBuff, sFlash2xRead.Section, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes ;
}
}
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
}
break;
case IOCTL_BCM_FLASH2X_SECTION_WRITE: {
struct bcm_flash2x_readwrite sFlash2xWrite = {0};
PUCHAR pWriteBuff;
void __user *InputAddr;
UINT NOB = 0;
UINT BuffSize = 0;
UINT WriteOffset = 0;
UINT WriteBytes = 0;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
/* First make this False so that we can enable the Sector Permission Check in BeceemFlashBulkWrite */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_FLASH2X_SECTION_WRITE Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
/* Reading FLASH 2.x READ structure */
if (copy_from_user(&sFlash2xWrite, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_readwrite)))
return -EFAULT;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.Section :%x", sFlash2xWrite.Section);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.offset :%d", sFlash2xWrite.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.numOfBytes :%x", sFlash2xWrite.numOfBytes);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\nsFlash2xRead.bVerify :%x\n", sFlash2xWrite.bVerify);
if ((sFlash2xWrite.Section != VSA0) && (sFlash2xWrite.Section != VSA1) && (sFlash2xWrite.Section != VSA2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Only VSA write is allowed");
return -EINVAL;
}
if (validateFlash2xReadWrite(Adapter, &sFlash2xWrite) == FALSE)
return STATUS_FAILURE;
InputAddr = sFlash2xWrite.pDataBuff;
WriteOffset = sFlash2xWrite.offset;
NOB = sFlash2xWrite.numOfBytes;
if (NOB > Adapter->uiSectorSize)
BuffSize = Adapter->uiSectorSize;
else
BuffSize = NOB ;
pWriteBuff = kmalloc(BuffSize, GFP_KERNEL);
if (pWriteBuff == NULL)
return -ENOMEM;
/* extracting the remainder of the given offset. */
WriteBytes = Adapter->uiSectorSize;
if (WriteOffset % Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize - (WriteOffset % Adapter->uiSectorSize);
if (NOB < WriteBytes)
WriteBytes = NOB;
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EACCES;
}
BcmFlash2xCorruptSig(Adapter, sFlash2xWrite.Section);
do {
Status = copy_from_user(pWriteBuff, InputAddr, WriteBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to user failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
return -EFAULT;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pWriteBuff, WriteBytes);
/* Writing the data from Flash 2.x */
Status = BcmFlash2xBulkWrite(Adapter, (PUINT)pWriteBuff, sFlash2xWrite.Section, WriteOffset, WriteBytes, sFlash2xWrite.bVerify);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
NOB = NOB - WriteBytes;
if (NOB) {
WriteOffset = WriteOffset + WriteBytes;
InputAddr = InputAddr + WriteBytes;
if (NOB > Adapter->uiSectorSize)
WriteBytes = Adapter->uiSectorSize;
else
WriteBytes = NOB;
}
} while (NOB > 0);
BcmFlash2xWriteSig(Adapter, sFlash2xWrite.Section);
up(&Adapter->NVMRdmWrmLock);
kfree(pWriteBuff);
}
break;
case IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP: {
struct bcm_flash2x_bitmap *psFlash2xBitMap;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_GET_FLASH2X_SECTION_BITMAP Called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength != sizeof(struct bcm_flash2x_bitmap))
return -EINVAL;
psFlash2xBitMap = kzalloc(sizeof(struct bcm_flash2x_bitmap), GFP_KERNEL);
if (psFlash2xBitMap == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory is not available");
return -ENOMEM;
}
/* Reading the Flash Sectio Bit map */
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
kfree(psFlash2xBitMap);
return -EACCES;
}
BcmGetFlash2xSectionalBitMap(Adapter, psFlash2xBitMap);
up(&Adapter->NVMRdmWrmLock);
if (copy_to_user(IoBuffer.OutputBuffer, psFlash2xBitMap, sizeof(struct bcm_flash2x_bitmap))) {
kfree(psFlash2xBitMap);
return -EFAULT;
}
kfree(psFlash2xBitMap);
}
break;
case IOCTL_BCM_SET_ACTIVE_SECTION: {
enum bcm_flash2x_section_val eFlash2xSectionVal = 0;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SET_ACTIVE_SECTION Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Status = BcmSetActiveSection(Adapter, eFlash2xSectionVal);
if (Status)
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Failed to make it's priority Highest. Status %d", Status);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_IDENTIFY_ACTIVE_SECTION: {
/* Right Now we are taking care of only DSD */
Adapter->bAllDSDWriteAllow = FALSE;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_IDENTIFY_ACTIVE_SECTION called");
Status = STATUS_SUCCESS;
}
break;
case IOCTL_BCM_COPY_SECTION: {
struct bcm_flash2x_copy_section sCopySectStrut = {0};
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_COPY_SECTION Called");
Adapter->bAllDSDWriteAllow = FALSE;
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed Status :%d", Status);
return -EFAULT;
}
Status = copy_from_user(&sCopySectStrut, IoBuffer.InputBuffer, sizeof(struct bcm_flash2x_copy_section));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of Copy_Section_Struct failed with Status :%d", Status);
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source SEction :%x", sCopySectStrut.SrcSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Destination SEction :%x", sCopySectStrut.DstSection);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "offset :%x", sCopySectStrut.offset);
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "NOB :%x", sCopySectStrut.numOfBytes);
if (IsSectionExistInFlash(Adapter, sCopySectStrut.SrcSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Source Section<%x> does not exixt in Flash ", sCopySectStrut.SrcSection);
return -EINVAL;
}
if (IsSectionExistInFlash(Adapter, sCopySectStrut.DstSection) == FALSE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Destinatio Section<%x> does not exixt in Flash ", sCopySectStrut.DstSection);
return -EINVAL;
}
if (sCopySectStrut.SrcSection == sCopySectStrut.DstSection) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Source and Destination section should be different");
return -EINVAL;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
if (sCopySectStrut.SrcSection == ISO_IMAGE1 || sCopySectStrut.SrcSection == ISO_IMAGE2) {
if (IsNonCDLessDevice(Adapter)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Device is Non-CDLess hence won't have ISO !!");
Status = -EINVAL;
} else if (sCopySectStrut.numOfBytes == 0) {
Status = BcmCopyISO(Adapter, sCopySectStrut);
} else {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Partial Copy of ISO section is not Allowed..");
Status = STATUS_FAILURE;
}
up(&Adapter->NVMRdmWrmLock);
return Status;
}
Status = BcmCopySection(Adapter, sCopySectStrut.SrcSection,
sCopySectStrut.DstSection, sCopySectStrut.offset, sCopySectStrut.numOfBytes);
up(&Adapter->NVMRdmWrmLock);
}
break;
case IOCTL_BCM_GET_FLASH_CS_INFO: {
Status = STATUS_SUCCESS;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, " IOCTL_BCM_GET_FLASH_CS_INFO Called");
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Connected device does not have flash");
Status = -EINVAL;
break;
}
if (IsFlash2x(Adapter) == TRUE) {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash2x_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlash2xCSInfo, sizeof(struct bcm_flash2x_cs_info)))
return -EFAULT;
} else {
if (IoBuffer.OutputLength < sizeof(struct bcm_flash_cs_info))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, Adapter->psFlashCSInfo, sizeof(struct bcm_flash_cs_info)))
return -EFAULT;
}
}
break;
case IOCTL_BCM_SELECT_DSD: {
UINT SectOfset = 0;
enum bcm_flash2x_section_val eFlash2xSectionVal;
eFlash2xSectionVal = NO_SECTION_VAL;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_SELECT_DSD Called");
if (IsFlash2x(Adapter) != TRUE) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash Does not have 2.x map");
return -EINVAL;
}
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of IOCTL BUFFER failed");
return -EFAULT;
}
Status = copy_from_user(&eFlash2xSectionVal, IoBuffer.InputBuffer, sizeof(INT));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy of flash section val failed");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Read Section :%d", eFlash2xSectionVal);
if ((eFlash2xSectionVal != DSD0) &&
(eFlash2xSectionVal != DSD1) &&
(eFlash2xSectionVal != DSD2)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Passed section<%x> is not DSD section", eFlash2xSectionVal);
return STATUS_FAILURE;
}
SectOfset = BcmGetSectionValStartOffset(Adapter, eFlash2xSectionVal);
if (SectOfset == INVALID_OFFSET) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Provided Section val <%d> does not exixt in Flash 2.x", eFlash2xSectionVal);
return -EINVAL;
}
Adapter->bAllDSDWriteAllow = TRUE;
Adapter->ulFlashCalStart = SectOfset;
Adapter->eActiveDSD = eFlash2xSectionVal;
}
Status = STATUS_SUCCESS;
break;
case IOCTL_BCM_NVM_RAW_READ: {
struct bcm_nvm_readwrite stNVMRead;
INT NOB ;
INT BuffSize ;
INT ReadOffset = 0;
UINT ReadBytes = 0 ;
PUCHAR pReadBuff;
void __user *OutPutBuff;
if (Adapter->eNVMType != NVM_FLASH) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "NVM TYPE is not Flash");
return -EINVAL;
}
/* Copy Ioctl Buffer structure */
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer))) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "copy_from_user 1 failed\n");
return -EFAULT;
}
if (copy_from_user(&stNVMRead, IoBuffer.OutputBuffer, sizeof(struct bcm_nvm_readwrite)))
return -EFAULT;
NOB = stNVMRead.uiNumBytes;
/* In Raw-Read max Buff size : 64MB */
if (NOB > DEFAULT_BUFF_SIZE)
BuffSize = DEFAULT_BUFF_SIZE;
else
BuffSize = NOB;
ReadOffset = stNVMRead.uiOffset;
OutPutBuff = stNVMRead.pBuffer;
pReadBuff = kzalloc(BuffSize , GFP_KERNEL);
if (pReadBuff == NULL) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Memory allocation failed for Flash 2.x Read Structure");
Status = -ENOMEM;
break;
}
down(&Adapter->NVMRdmWrmLock);
if ((Adapter->IdleMode == TRUE) ||
(Adapter->bShutStatus == TRUE) ||
(Adapter->bPreparingForLowPowerMode == TRUE)) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Device is in Idle/Shutdown Mode\n");
kfree(pReadBuff);
up(&Adapter->NVMRdmWrmLock);
return -EACCES;
}
Adapter->bFlashRawRead = TRUE;
while (NOB) {
if (NOB > DEFAULT_BUFF_SIZE)
ReadBytes = DEFAULT_BUFF_SIZE;
else
ReadBytes = NOB;
/* Reading the data from Flash 2.x */
Status = BeceemNVMRead(Adapter, (PUINT)pReadBuff, ReadOffset, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Flash 2x read err with Status :%d", Status);
break;
}
BCM_DEBUG_PRINT_BUFFER(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, pReadBuff, ReadBytes);
Status = copy_to_user(OutPutBuff, pReadBuff, ReadBytes);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_PRINTK, 0, 0, "Copy to use failed with status :%d", Status);
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
return -EFAULT;
}
NOB = NOB - ReadBytes;
if (NOB) {
ReadOffset = ReadOffset + ReadBytes;
OutPutBuff = OutPutBuff + ReadBytes;
}
}
Adapter->bFlashRawRead = FALSE;
up(&Adapter->NVMRdmWrmLock);
kfree(pReadBuff);
break;
}
case IOCTL_BCM_CNTRLMSG_MASK: {
ULONG RxCntrlMsgBitMask = 0;
/* Copy Ioctl Buffer structure */
Status = copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer));
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of Ioctl buffer is failed from user space");
return -EFAULT;
}
if (IoBuffer.InputLength != sizeof(unsigned long)) {
Status = -EINVAL;
break;
}
Status = copy_from_user(&RxCntrlMsgBitMask, IoBuffer.InputBuffer, IoBuffer.InputLength);
if (Status) {
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "copy of control bit mask failed from user space");
return -EFAULT;
}
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "\n Got user defined cntrl msg bit mask :%lx", RxCntrlMsgBitMask);
pTarang->RxCntrlMsgBitMask = RxCntrlMsgBitMask;
}
break;
case IOCTL_BCM_GET_DEVICE_DRIVER_INFO: {
struct bcm_driver_info DevInfo;
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "Called IOCTL_BCM_GET_DEVICE_DRIVER_INFO\n");
memset(&DevInfo, 0, sizeof(DevInfo));
DevInfo.MaxRDMBufferSize = BUFFER_4K;
DevInfo.u32DSDStartOffset = EEPROM_CALPARAM_START;
DevInfo.u32RxAlignmentCorrection = 0;
DevInfo.u32NVMType = Adapter->eNVMType;
DevInfo.u32InterfaceType = BCM_USB;
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(DevInfo))
return -EINVAL;
if (copy_to_user(IoBuffer.OutputBuffer, &DevInfo, sizeof(DevInfo)))
return -EFAULT;
}
break;
case IOCTL_BCM_TIME_SINCE_NET_ENTRY: {
struct bcm_time_elapsed stTimeElapsedSinceNetEntry = {0};
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_BCM_TIME_SINCE_NET_ENTRY called");
if (copy_from_user(&IoBuffer, argp, sizeof(struct bcm_ioctl_buffer)))
return -EFAULT;
if (IoBuffer.OutputLength < sizeof(struct bcm_time_elapsed))
return -EINVAL;
stTimeElapsedSinceNetEntry.ul64TimeElapsedSinceNetEntry = get_seconds() - Adapter->liTimeSinceLastNetEntry;
if (copy_to_user(IoBuffer.OutputBuffer, &stTimeElapsedSinceNetEntry, sizeof(struct bcm_time_elapsed)))
return -EFAULT;
}
break;
case IOCTL_CLOSE_NOTIFICATION:
BCM_DEBUG_PRINT(Adapter, DBG_TYPE_OTHERS, OSAL_DBG, DBG_LVL_ALL, "IOCTL_CLOSE_NOTIFICATION");
break;
default:
pr_info(DRV_NAME ": unknown ioctl cmd=%#x\n", cmd);
Status = STATUS_FAILURE;
break;
}
return Status;
}
| 165,962 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SimplifiedBackwardsTextIterator::handleTextNode()
{
m_lastTextNode = m_node;
int startOffset;
int offsetInNode;
RenderText* renderer = handleFirstLetter(startOffset, offsetInNode);
if (!renderer)
return true;
String text = renderer->text();
if (!renderer->firstTextBox() && text.length() > 0)
return true;
m_positionEndOffset = m_offset;
m_offset = startOffset + offsetInNode;
m_positionNode = m_node;
m_positionStartOffset = m_offset;
ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(m_positionStartOffset <= m_positionEndOffset);
m_textLength = m_positionEndOffset - m_positionStartOffset;
m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
ASSERT(m_textCharacters >= text.characters());
ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
m_lastCharacter = text[m_positionEndOffset - 1];
return !m_shouldHandleFirstLetter;
}
Commit Message: Upgrade a TextIterator ASSERT to a RELEASE_ASSERT as a defensive measure.
BUG=156930,177197
[email protected]
Review URL: https://codereview.chromium.org/15057010
git-svn-id: svn://svn.chromium.org/blink/trunk@150123 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-119 | bool SimplifiedBackwardsTextIterator::handleTextNode()
{
m_lastTextNode = m_node;
int startOffset;
int offsetInNode;
RenderText* renderer = handleFirstLetter(startOffset, offsetInNode);
if (!renderer)
return true;
String text = renderer->text();
if (!renderer->firstTextBox() && text.length() > 0)
return true;
m_positionEndOffset = m_offset;
m_offset = startOffset + offsetInNode;
m_positionNode = m_node;
m_positionStartOffset = m_offset;
ASSERT(0 <= m_positionStartOffset - offsetInNode && m_positionStartOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(1 <= m_positionEndOffset - offsetInNode && m_positionEndOffset - offsetInNode <= static_cast<int>(text.length()));
ASSERT(m_positionStartOffset <= m_positionEndOffset);
m_textLength = m_positionEndOffset - m_positionStartOffset;
m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
ASSERT(m_textCharacters >= text.characters());
RELEASE_ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
m_lastCharacter = text[m_positionEndOffset - 1];
return !m_shouldHandleFirstLetter;
}
| 171,311 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
DCHECK(!options.executable);
DCHECK(!mapped_file_);
if (options.size == 0)
return false;
uint32 rounded_size = (options.size + 0xffff) & ~0xffff;
name_ = ASCIIToWide(options.name == NULL ? "" : *options.name);
mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size),
name_.empty() ? NULL : name_.c_str());
if (!mapped_file_)
return false;
created_size_ = options.size;
if (GetLastError() == ERROR_ALREADY_EXISTS) {
created_size_ = 0;
if (!options.open_existing) {
Close();
return false;
}
}
return true;
}
Commit Message: Fix integer overflow in Windows shared memory handling.
BUG=164490
Review URL: https://codereview.chromium.org/11450016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171369 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | bool SharedMemory::Create(const SharedMemoryCreateOptions& options) {
DCHECK(!options.executable);
DCHECK(!mapped_file_);
if (options.size == 0)
return false;
uint32 rounded_size = (options.size + 0xffff) & ~0xffff;
if (rounded_size < options.size)
return false;
name_ = ASCIIToWide(options.name == NULL ? "" : *options.name);
mapped_file_ = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE, 0, static_cast<DWORD>(rounded_size),
name_.empty() ? NULL : name_.c_str());
if (!mapped_file_)
return false;
created_size_ = options.size;
if (GetLastError() == ERROR_ALREADY_EXISTS) {
created_size_ = 0;
if (!options.open_existing) {
Close();
return false;
}
}
return true;
}
| 171,538 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create)
{
struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
struct inet_peer_base *base = family_to_base(daddr->family);
struct inet_peer *p;
unsigned int sequence;
int invalidated, gccnt = 0;
/* Attempt a lockless lookup first.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
sequence = read_seqbegin(&base->lock);
p = lookup_rcu(daddr, base);
invalidated = read_seqretry(&base->lock, sequence);
rcu_read_unlock();
if (p)
return p;
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
write_seqlock_bh(&base->lock);
relookup:
p = lookup(daddr, stack, base);
if (p != peer_avl_empty) {
atomic_inc(&p->refcnt);
write_sequnlock_bh(&base->lock);
return p;
}
if (!gccnt) {
gccnt = inet_peer_gc(base, stack, stackptr);
if (gccnt && create)
goto relookup;
}
p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
if (p) {
p->daddr = *daddr;
atomic_set(&p->refcnt, 1);
atomic_set(&p->rid, 0);
atomic_set(&p->ip_id_count, secure_ip_id(daddr->addr.a4));
p->tcp_ts_stamp = 0;
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->rate_last = 0;
p->pmtu_expires = 0;
p->pmtu_orig = 0;
memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
/* Link the node. */
link_to_pool(p, base);
base->total++;
}
write_sequnlock_bh(&base->lock);
return p;
}
Commit Message: ipv6: make fragment identifications less predictable
IPv6 fragment identification generation is way beyond what we use for
IPv4 : It uses a single generator. Its not scalable and allows DOS
attacks.
Now inetpeer is IPv6 aware, we can use it to provide a more secure and
scalable frag ident generator (per destination, instead of system wide)
This patch :
1) defines a new secure_ipv6_id() helper
2) extends inet_getid() to provide 32bit results
3) extends ipv6_select_ident() with a new dest parameter
Reported-by: Fernando Gont <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: | struct inet_peer *inet_getpeer(struct inetpeer_addr *daddr, int create)
struct inet_peer *inet_getpeer(const struct inetpeer_addr *daddr, int create)
{
struct inet_peer __rcu **stack[PEER_MAXDEPTH], ***stackptr;
struct inet_peer_base *base = family_to_base(daddr->family);
struct inet_peer *p;
unsigned int sequence;
int invalidated, gccnt = 0;
/* Attempt a lockless lookup first.
* Because of a concurrent writer, we might not find an existing entry.
*/
rcu_read_lock();
sequence = read_seqbegin(&base->lock);
p = lookup_rcu(daddr, base);
invalidated = read_seqretry(&base->lock, sequence);
rcu_read_unlock();
if (p)
return p;
/* If no writer did a change during our lookup, we can return early. */
if (!create && !invalidated)
return NULL;
/* retry an exact lookup, taking the lock before.
* At least, nodes should be hot in our cache.
*/
write_seqlock_bh(&base->lock);
relookup:
p = lookup(daddr, stack, base);
if (p != peer_avl_empty) {
atomic_inc(&p->refcnt);
write_sequnlock_bh(&base->lock);
return p;
}
if (!gccnt) {
gccnt = inet_peer_gc(base, stack, stackptr);
if (gccnt && create)
goto relookup;
}
p = create ? kmem_cache_alloc(peer_cachep, GFP_ATOMIC) : NULL;
if (p) {
p->daddr = *daddr;
atomic_set(&p->refcnt, 1);
atomic_set(&p->rid, 0);
atomic_set(&p->ip_id_count,
(daddr->family == AF_INET) ?
secure_ip_id(daddr->addr.a4) :
secure_ipv6_id(daddr->addr.a6));
p->tcp_ts_stamp = 0;
p->metrics[RTAX_LOCK-1] = INETPEER_METRICS_NEW;
p->rate_tokens = 0;
p->rate_last = 0;
p->pmtu_expires = 0;
p->pmtu_orig = 0;
memset(&p->redirect_learned, 0, sizeof(p->redirect_learned));
/* Link the node. */
link_to_pool(p, base);
base->total++;
}
write_sequnlock_bh(&base->lock);
return p;
}
| 165,850 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
return;
}
Commit Message: Fixed bit stream access to make sure that it is not read beyond the allocated size.
Bug: 25765591
Change-Id: I98c23a3c3f84f6710f29bffe5ed73adcf51d47f6
CWE ID: CWE-254 | INLINE void impeg2d_bit_stream_flush(void* pv_ctxt, UWORD32 u4_no_of_bits)
{
stream_t *ps_stream = (stream_t *)pv_ctxt;
if (ps_stream->u4_offset < ps_stream->u4_max_offset)
{
FLUSH_BITS(ps_stream->u4_offset,ps_stream->u4_buf,ps_stream->u4_buf_nxt,u4_no_of_bits,ps_stream->pu4_buf_aligned)
}
return;
}
| 173,941 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ContextualSearchDelegate::DecodeSearchTermFromJsonResponse(
const std::string& response,
std::string* search_term,
std::string* display_text,
std::string* alternate_term,
std::string* mid,
std::string* prevent_preload,
int* mention_start,
int* mention_end,
std::string* lang,
std::string* thumbnail_url,
std::string* caption) {
bool contains_xssi_escape =
base::StartsWith(response, kXssiEscape, base::CompareCase::SENSITIVE);
const std::string& proper_json =
contains_xssi_escape ? response.substr(sizeof(kXssiEscape) - 1)
: response;
JSONStringValueDeserializer deserializer(proper_json);
std::unique_ptr<base::Value> root =
deserializer.Deserialize(nullptr, nullptr);
const std::unique_ptr<base::DictionaryValue> dict =
base::DictionaryValue::From(std::move(root));
if (!dict)
return;
dict->GetString(kContextualSearchPreventPreload, prevent_preload);
dict->GetString(kContextualSearchResponseSearchTermParam, search_term);
dict->GetString(kContextualSearchResponseLanguageParam, lang);
if (!dict->GetString(kContextualSearchResponseDisplayTextParam,
display_text)) {
*display_text = *search_term;
}
dict->GetString(kContextualSearchResponseMidParam, mid);
if (!field_trial_->IsDecodeMentionsDisabled()) {
base::ListValue* mentions_list = nullptr;
dict->GetList(kContextualSearchMentions, &mentions_list);
if (mentions_list && mentions_list->GetSize() >= 2)
ExtractMentionsStartEnd(*mentions_list, mention_start, mention_end);
}
std::string selected_text;
dict->GetString(kContextualSearchResponseSelectedTextParam, &selected_text);
if (selected_text != *search_term) {
*alternate_term = selected_text;
} else {
std::string resolved_term;
dict->GetString(kContextualSearchResponseResolvedTermParam, &resolved_term);
if (resolved_term != *search_term) {
*alternate_term = resolved_term;
}
}
if (field_trial_->IsNowOnTapBarIntegrationEnabled()) {
dict->GetString(kContextualSearchCaption, caption);
dict->GetString(kContextualSearchThumbnail, thumbnail_url);
}
}
Commit Message: [Contextual Search] Change "Now on Tap" to "Contextual Cards"
BUG=644934
Review-Url: https://codereview.chromium.org/2361163003
Cr-Commit-Position: refs/heads/master@{#420899}
CWE ID: | void ContextualSearchDelegate::DecodeSearchTermFromJsonResponse(
const std::string& response,
std::string* search_term,
std::string* display_text,
std::string* alternate_term,
std::string* mid,
std::string* prevent_preload,
int* mention_start,
int* mention_end,
std::string* lang,
std::string* thumbnail_url,
std::string* caption) {
bool contains_xssi_escape =
base::StartsWith(response, kXssiEscape, base::CompareCase::SENSITIVE);
const std::string& proper_json =
contains_xssi_escape ? response.substr(sizeof(kXssiEscape) - 1)
: response;
JSONStringValueDeserializer deserializer(proper_json);
std::unique_ptr<base::Value> root =
deserializer.Deserialize(nullptr, nullptr);
const std::unique_ptr<base::DictionaryValue> dict =
base::DictionaryValue::From(std::move(root));
if (!dict)
return;
dict->GetString(kContextualSearchPreventPreload, prevent_preload);
dict->GetString(kContextualSearchResponseSearchTermParam, search_term);
dict->GetString(kContextualSearchResponseLanguageParam, lang);
if (!dict->GetString(kContextualSearchResponseDisplayTextParam,
display_text)) {
*display_text = *search_term;
}
dict->GetString(kContextualSearchResponseMidParam, mid);
if (!field_trial_->IsDecodeMentionsDisabled()) {
base::ListValue* mentions_list = nullptr;
dict->GetList(kContextualSearchMentions, &mentions_list);
if (mentions_list && mentions_list->GetSize() >= 2)
ExtractMentionsStartEnd(*mentions_list, mention_start, mention_end);
}
std::string selected_text;
dict->GetString(kContextualSearchResponseSelectedTextParam, &selected_text);
if (selected_text != *search_term) {
*alternate_term = selected_text;
} else {
std::string resolved_term;
dict->GetString(kContextualSearchResponseResolvedTermParam, &resolved_term);
if (resolved_term != *search_term) {
*alternate_term = resolved_term;
}
}
if (field_trial_->IsContextualCardsBarIntegrationEnabled()) {
// Get the basic Bar data for Contextual Cards integration directly
// from the root.
dict->GetString(kContextualSearchCaption, caption);
dict->GetString(kContextualSearchThumbnail, thumbnail_url);
}
}
| 171,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const Block* SimpleBlock::GetBlock() const
{
return &m_block;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const Block* SimpleBlock::GetBlock() const
| 174,285 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
uint8_t* buf, int buf_size)
{
int size, i;
uint8_t *ppcm[4] = {0};
if (buf_size < DV_PROFILE_BYTES ||
!(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) ||
buf_size < c->sys->frame_size) {
return -1; /* Broken frame, or not enough data */
}
/* Queueing audio packet */
/* FIXME: in case of no audio/bad audio we have to do something */
size = dv_extract_audio_info(c, buf);
for (i = 0; i < c->ach; i++) {
c->audio_pkt[i].size = size;
c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
ppcm[i] = c->audio_buf[i];
}
dv_extract_audio(buf, ppcm, c->sys);
/* We work with 720p frames split in half, thus even frames have
* channels 0,1 and odd 2,3. */
if (buf[1] & 0x0C) {
c->audio_pkt[2].size = c->audio_pkt[3].size = 0;
} else {
c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
c->abytes += size;
}
} else {
c->abytes += size;
}
Commit Message:
CWE ID: CWE-119 | int avpriv_dv_produce_packet(DVDemuxContext *c, AVPacket *pkt,
uint8_t* buf, int buf_size)
{
int size, i;
uint8_t *ppcm[4] = {0};
if (buf_size < DV_PROFILE_BYTES ||
!(c->sys = avpriv_dv_frame_profile(c->sys, buf, buf_size)) ||
buf_size < c->sys->frame_size) {
return -1; /* Broken frame, or not enough data */
}
/* Queueing audio packet */
/* FIXME: in case of no audio/bad audio we have to do something */
size = dv_extract_audio_info(c, buf);
for (i = 0; i < c->ach; i++) {
c->audio_pkt[i].size = size;
c->audio_pkt[i].pts = c->abytes * 30000*8 / c->ast[i]->codec->bit_rate;
ppcm[i] = c->audio_buf[i];
}
if (c->ach)
dv_extract_audio(buf, ppcm, c->sys);
/* We work with 720p frames split in half, thus even frames have
* channels 0,1 and odd 2,3. */
if (buf[1] & 0x0C) {
c->audio_pkt[2].size = c->audio_pkt[3].size = 0;
} else {
c->audio_pkt[0].size = c->audio_pkt[1].size = 0;
c->abytes += size;
}
} else {
c->abytes += size;
}
| 165,244 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WallpaperManager::OnWallpaperDecoded(
const AccountId& account_id,
const wallpaper::WallpaperInfo& info,
bool update_wallpaper,
MovableOnDestroyCallbackHolder on_finish,
std::unique_ptr<user_manager::UserImage> user_image) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
TRACE_EVENT_ASYNC_END0("ui", "LoadAndDecodeWallpaper", this);
if (user_image->image().isNull()) {
wallpaper::WallpaperInfo default_info(
"", wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED, wallpaper::DEFAULT,
base::Time::Now().LocalMidnight());
SetUserWallpaperInfo(account_id, default_info, true);
if (update_wallpaper)
DoSetDefaultWallpaper(account_id, std::move(on_finish));
return;
}
wallpaper_cache_[account_id].second = user_image->image();
if (update_wallpaper)
SetWallpaper(user_image->image(), info);
}
Commit Message: [reland] Do not set default wallpaper unless it should do so.
[email protected], [email protected]
Bug: 751382
Change-Id: Id0793dfe467f737526a95b1e66ed01fbb8860bda
Reviewed-on: https://chromium-review.googlesource.com/619754
Commit-Queue: Xiaoqian Dai <[email protected]>
Reviewed-by: Alexander Alekseev <[email protected]>
Reviewed-by: Biao She <[email protected]>
Cr-Original-Commit-Position: refs/heads/master@{#498325}
Reviewed-on: https://chromium-review.googlesource.com/646430
Cr-Commit-Position: refs/heads/master@{#498982}
CWE ID: CWE-200 | void WallpaperManager::OnWallpaperDecoded(
const AccountId& account_id,
const wallpaper::WallpaperInfo& info,
bool update_wallpaper,
MovableOnDestroyCallbackHolder on_finish,
std::unique_ptr<user_manager::UserImage> user_image) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
TRACE_EVENT_ASYNC_END0("ui", "LoadAndDecodeWallpaper", this);
if (user_image->image().isNull()) {
wallpaper::WallpaperInfo default_info(
"", wallpaper::WALLPAPER_LAYOUT_CENTER_CROPPED, wallpaper::DEFAULT,
base::Time::Now().LocalMidnight());
SetUserWallpaperInfo(account_id, default_info, true);
DoSetDefaultWallpaper(account_id, update_wallpaper, std::move(on_finish));
return;
}
wallpaper_cache_[account_id].second = user_image->image();
if (update_wallpaper)
SetWallpaper(user_image->image(), info);
}
| 171,968 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void controloptions (lua_State *L, int opt, const char **fmt,
Header *h) {
switch (opt) {
case ' ': return; /* ignore white spaces */
case '>': h->endian = BIG; return;
case '<': h->endian = LITTLE; return;
case '!': {
int a = getnum(L, fmt, MAXALIGN);
if (!isp2(a))
luaL_error(L, "alignment %d is not a power of 2", a);
h->align = a;
return;
}
default: {
const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt);
luaL_argerror(L, 1, msg);
}
}
}
Commit Message: Security: update Lua struct package for security.
During an auditing Apple found that the "struct" Lua package
we ship with Redis (http://www.inf.puc-rio.br/~roberto/struct/) contains
a security problem. A bound-checking statement fails because of integer
overflow. The bug exists since we initially integrated this package with
Lua, when scripting was introduced, so every version of Redis with
EVAL/EVALSHA capabilities exposed is affected.
Instead of just fixing the bug, the library was updated to the latest
version shipped by the author.
CWE ID: CWE-190 | static void controloptions (lua_State *L, int opt, const char **fmt,
Header *h) {
switch (opt) {
case ' ': return; /* ignore white spaces */
case '>': h->endian = BIG; return;
case '<': h->endian = LITTLE; return;
case '!': {
int a = getnum(fmt, MAXALIGN);
if (!isp2(a))
luaL_error(L, "alignment %d is not a power of 2", a);
h->align = a;
return;
}
default: {
const char *msg = lua_pushfstring(L, "invalid format option '%c'", opt);
luaL_argerror(L, 1, msg);
}
}
}
| 170,164 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionDevToolsClientHost::InfoBarDismissed() {
detach_reason_ = api::debugger::DETACH_REASON_CANCELED_BY_USER;
SendDetachedEvent();
Close();
}
Commit Message: [DevTools] Do not allow chrome.debugger to attach to web ui pages
If the page navigates to web ui, we force detach the debugger extension.
[email protected]
Bug: 798222
Change-Id: Idb46c2f59e839388397a8dfa6ce2e2a897698df3
Reviewed-on: https://chromium-review.googlesource.com/935961
Commit-Queue: Dmitry Gozman <[email protected]>
Reviewed-by: Devlin <[email protected]>
Reviewed-by: Pavel Feldman <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Cr-Commit-Position: refs/heads/master@{#540916}
CWE ID: CWE-20 | void ExtensionDevToolsClientHost::InfoBarDismissed() {
detach_reason_ = api::debugger::DETACH_REASON_CANCELED_BY_USER;
RespondDetachedToPendingRequests();
SendDetachedEvent();
Close();
}
| 173,238 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"passwordsAndAutofillPageTitle",
IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE},
{"autofill", IDS_SETTINGS_AUTOFILL},
{"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS},
{"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED},
{"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING},
{"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE},
{"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE},
{"addressCountry", IDS_SETTINGS_AUTOFILL_ADDRESSES_COUNTRY},
{"addressPhone", IDS_SETTINGS_AUTOFILL_ADDRESSES_PHONE},
{"addressEmail", IDS_SETTINGS_AUTOFILL_ADDRESSES_EMAIL},
{"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE},
{"creditCards", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING},
{"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE},
{"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR},
{"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL},
{"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE},
{"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD},
{"creditCardNumber", IDS_SETTINGS_CREDIT_CARD_NUMBER},
{"creditCardExpirationMonth", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_MONTH},
{"creditCardExpirationYear", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_YEAR},
{"creditCardExpired", IDS_SETTINGS_CREDIT_CARD_EXPIRED},
{"editCreditCardTitle", IDS_SETTINGS_EDIT_CREDIT_CARD_TITLE},
{"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE},
{"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL},
{"passwords", IDS_SETTINGS_PASSWORDS},
{"passwordsAutosigninLabel",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL},
{"passwordsAutosigninDescription",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC},
{"passwordsDetail", IDS_SETTINGS_PASSWORDS_DETAIL},
{"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING},
{"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING},
{"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION},
{"removePassword", IDS_SETTINGS_PASSWORD_REMOVE},
{"searchPasswords", IDS_SETTINGS_PASSWORD_SEARCH},
{"showPassword", IDS_SETTINGS_PASSWORD_SHOW},
{"hidePassword", IDS_SETTINGS_PASSWORD_HIDE},
{"passwordDetailsTitle", IDS_SETTINGS_PASSWORDS_VIEW_DETAILS_TITLE},
{"passwordViewDetails", IDS_SETTINGS_PASSWORD_DETAILS},
{"editPasswordWebsiteLabel", IDS_SETTINGS_PASSWORDS_WEBSITE},
{"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME},
{"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD},
{"noAddressesFound", IDS_SETTINGS_ADDRESS_NONE},
{"noCreditCardsFound", IDS_SETTINGS_CREDIT_CARD_NONE},
{"noCreditCardsPolicy", IDS_SETTINGS_CREDIT_CARD_DISABLED},
{"noPasswordsFound", IDS_SETTINGS_PASSWORDS_NONE},
{"noExceptionsFound", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_NONE},
{"import", IDS_PASSWORD_MANAGER_IMPORT_BUTTON},
{"exportMenuItem", IDS_SETTINGS_PASSWORDS_EXPORT_MENU_ITEM},
{"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO},
{"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD},
{"exportPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORT_TITLE},
{"exportPasswordsDescription", IDS_SETTINGS_PASSWORDS_EXPORT_DESCRIPTION},
{"exportPasswords", IDS_SETTINGS_PASSWORDS_EXPORT},
{"exportingPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_TITLE},
{"exportPasswordsTryAgain", IDS_SETTINGS_PASSWORDS_EXPORT_TRY_AGAIN},
{"exportPasswordsFailTitle",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TITLE},
{"exportPasswordsFailTips",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIPS},
{"exportPasswordsFailTipsEnoughSpace",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ENOUGH_SPACE},
{"exportPasswordsFailTipsAnotherFolder",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER}};
html_source->AddString(
"managePasswordsLabel",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS,
base::ASCIIToUTF16(
password_manager::kPasswordManagerAccountDashboardURL)));
html_source->AddString("passwordManagerLearnMoreURL",
chrome::kPasswordManagerLearnMoreURL);
html_source->AddString("manageAddressesUrl",
autofill::payments::GetManageAddressesUrl(0).spec());
html_source->AddString("manageCreditCardsUrl",
autofill::payments::GetManageInstrumentsUrl(0).spec());
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
}
Commit Message: [md-settings] Clarify Password Saving and Autofill Toggles
This change clarifies the wording around the password saving and
autofill toggles.
Bug: 822465
Cq-Include-Trybots: master.tryserver.chromium.linux:closure_compilation
Change-Id: I91b31fe61cd0754239f7908e8c04c7e69b72f670
Reviewed-on: https://chromium-review.googlesource.com/970541
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Reviewed-by: Vaclav Brozek <[email protected]>
Reviewed-by: Jochen Eisinger <[email protected]>
Cr-Commit-Position: refs/heads/master@{#544661}
CWE ID: CWE-200 | void AddPasswordsAndFormsStrings(content::WebUIDataSource* html_source) {
LocalizedString localized_strings[] = {
{"passwordsAndAutofillPageTitle",
IDS_SETTINGS_PASSWORDS_AND_AUTOFILL_PAGE_TITLE},
{"autofill", IDS_SETTINGS_AUTOFILL},
{"googlePayments", IDS_SETTINGS_GOOGLE_PAYMENTS},
{"googlePaymentsCached", IDS_SETTINGS_GOOGLE_PAYMENTS_CACHED},
{"autofillFormsLabel", IDS_SETTINGS_AUTOFILL_TOGGLE_LABEL},
{"addresses", IDS_SETTINGS_AUTOFILL_ADDRESSES_HEADING},
{"addAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_ADD_TITLE},
{"editAddressTitle", IDS_SETTINGS_AUTOFILL_ADDRESSES_EDIT_TITLE},
{"addressCountry", IDS_SETTINGS_AUTOFILL_ADDRESSES_COUNTRY},
{"addressPhone", IDS_SETTINGS_AUTOFILL_ADDRESSES_PHONE},
{"addressEmail", IDS_SETTINGS_AUTOFILL_ADDRESSES_EMAIL},
{"removeAddress", IDS_SETTINGS_ADDRESS_REMOVE},
{"creditCards", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_HEADING},
{"removeCreditCard", IDS_SETTINGS_CREDIT_CARD_REMOVE},
{"clearCreditCard", IDS_SETTINGS_CREDIT_CARD_CLEAR},
{"creditCardType", IDS_SETTINGS_AUTOFILL_CREDIT_CARD_TYPE_COLUMN_LABEL},
{"creditCardExpiration", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_DATE},
{"creditCardName", IDS_SETTINGS_NAME_ON_CREDIT_CARD},
{"creditCardNumber", IDS_SETTINGS_CREDIT_CARD_NUMBER},
{"creditCardExpirationMonth", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_MONTH},
{"creditCardExpirationYear", IDS_SETTINGS_CREDIT_CARD_EXPIRATION_YEAR},
{"creditCardExpired", IDS_SETTINGS_CREDIT_CARD_EXPIRED},
{"editCreditCardTitle", IDS_SETTINGS_EDIT_CREDIT_CARD_TITLE},
{"addCreditCardTitle", IDS_SETTINGS_ADD_CREDIT_CARD_TITLE},
{"autofillDetail", IDS_SETTINGS_AUTOFILL_DETAIL},
{"passwords", IDS_SETTINGS_PASSWORDS},
{"passwordsSavePasswordsLabel",
IDS_SETTINGS_PASSWORDS_SAVE_PASSWORDS_TOGGLE_LABEL},
{"passwordsAutosigninLabel",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_LABEL},
{"passwordsAutosigninDescription",
IDS_SETTINGS_PASSWORDS_AUTOSIGNIN_CHECKBOX_DESC},
{"passwordsDetail", IDS_SETTINGS_PASSWORDS_DETAIL},
{"savedPasswordsHeading", IDS_SETTINGS_PASSWORDS_SAVED_HEADING},
{"passwordExceptionsHeading", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_HEADING},
{"deletePasswordException", IDS_SETTINGS_PASSWORDS_DELETE_EXCEPTION},
{"removePassword", IDS_SETTINGS_PASSWORD_REMOVE},
{"searchPasswords", IDS_SETTINGS_PASSWORD_SEARCH},
{"showPassword", IDS_SETTINGS_PASSWORD_SHOW},
{"hidePassword", IDS_SETTINGS_PASSWORD_HIDE},
{"passwordDetailsTitle", IDS_SETTINGS_PASSWORDS_VIEW_DETAILS_TITLE},
{"passwordViewDetails", IDS_SETTINGS_PASSWORD_DETAILS},
{"editPasswordWebsiteLabel", IDS_SETTINGS_PASSWORDS_WEBSITE},
{"editPasswordUsernameLabel", IDS_SETTINGS_PASSWORDS_USERNAME},
{"editPasswordPasswordLabel", IDS_SETTINGS_PASSWORDS_PASSWORD},
{"noAddressesFound", IDS_SETTINGS_ADDRESS_NONE},
{"noCreditCardsFound", IDS_SETTINGS_CREDIT_CARD_NONE},
{"noCreditCardsPolicy", IDS_SETTINGS_CREDIT_CARD_DISABLED},
{"noPasswordsFound", IDS_SETTINGS_PASSWORDS_NONE},
{"noExceptionsFound", IDS_SETTINGS_PASSWORDS_EXCEPTIONS_NONE},
{"import", IDS_PASSWORD_MANAGER_IMPORT_BUTTON},
{"exportMenuItem", IDS_SETTINGS_PASSWORDS_EXPORT_MENU_ITEM},
{"undoRemovePassword", IDS_SETTINGS_PASSWORD_UNDO},
{"passwordDeleted", IDS_SETTINGS_PASSWORD_DELETED_PASSWORD},
{"exportPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORT_TITLE},
{"exportPasswordsDescription", IDS_SETTINGS_PASSWORDS_EXPORT_DESCRIPTION},
{"exportPasswords", IDS_SETTINGS_PASSWORDS_EXPORT},
{"exportingPasswordsTitle", IDS_SETTINGS_PASSWORDS_EXPORTING_TITLE},
{"exportPasswordsTryAgain", IDS_SETTINGS_PASSWORDS_EXPORT_TRY_AGAIN},
{"exportPasswordsFailTitle",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TITLE},
{"exportPasswordsFailTips",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIPS},
{"exportPasswordsFailTipsEnoughSpace",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ENOUGH_SPACE},
{"exportPasswordsFailTipsAnotherFolder",
IDS_SETTINGS_PASSWORDS_EXPORTING_FAILURE_TIP_ANOTHER_FOLDER}};
html_source->AddString(
"managePasswordsLabel",
l10n_util::GetStringFUTF16(
IDS_SETTINGS_PASSWORDS_MANAGE_PASSWORDS,
base::ASCIIToUTF16(
password_manager::kPasswordManagerAccountDashboardURL)));
html_source->AddString("passwordManagerLearnMoreURL",
chrome::kPasswordManagerLearnMoreURL);
html_source->AddString("manageAddressesUrl",
autofill::payments::GetManageAddressesUrl(0).spec());
html_source->AddString("manageCreditCardsUrl",
autofill::payments::GetManageInstrumentsUrl(0).spec());
AddLocalizedStringsBulk(html_source, localized_strings,
arraysize(localized_strings));
}
| 172,794 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
int (*output)(struct net *, struct sock *, struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ?
inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id;
int ptr, offset = 0, err = 0;
u8 *prevhdr, nexthdr = 0;
hlen = ip6_find_1stfragopt(skb, &prevhdr);
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (unlikely(!skb->ignore_df && skb->len > mtu))
goto fail_toobig;
if (IP6CB(skb)->frag_max_size) {
if (IP6CB(skb)->frag_max_size > mtu)
goto fail_toobig;
/* don't send fragments larger than what we received */
mtu = IP6CB(skb)->frag_max_size;
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
if (mtu < hlen + sizeof(struct frag_hdr) + 8)
goto fail_toobig;
mtu -= hlen + sizeof(struct frag_hdr);
frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr);
if (skb->ip_summed == CHECKSUM_PARTIAL &&
(err = skb_checksum_help(skb)))
goto fail;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
if (skb_has_frag_list(skb)) {
unsigned int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb) ||
skb_headroom(skb) < (hroom + sizeof(struct frag_hdr)))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr)))
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
__skb_pull(skb, hlen);
fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
fh->identification = frag_id;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(net, sk, skb);
if (!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
ip6_rt_put(rt);
return 0;
}
kfree_skb_list(frag);
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
ip6_rt_put(rt);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while (left > 0) {
u8 *fragnexthdr_offset;
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/* Allocate buffer */
frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC);
if (!frag) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
fragnexthdr_offset = skb_network_header(frag);
fragnexthdr_offset += prevhdr - skb_network_header(skb);
*fragnexthdr_offset = NEXTHDR_FRAGMENT;
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag),
len));
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(net, sk, frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
consume_skb(skb);
return err;
fail_toobig:
if (skb->sk && dst_allfrag(skb_dst(skb)))
sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK);
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
err = -EMSGSIZE;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
Commit Message: ipv6: Prevent overrun when parsing v6 header options
The KASAN warning repoted below was discovered with a syzkaller
program. The reproducer is basically:
int s = socket(AF_INET6, SOCK_RAW, NEXTHDR_HOP);
send(s, &one_byte_of_data, 1, MSG_MORE);
send(s, &more_than_mtu_bytes_data, 2000, 0);
The socket() call sets the nexthdr field of the v6 header to
NEXTHDR_HOP, the first send call primes the payload with a non zero
byte of data, and the second send call triggers the fragmentation path.
The fragmentation code tries to parse the header options in order
to figure out where to insert the fragment option. Since nexthdr points
to an invalid option, the calculation of the size of the network header
can made to be much larger than the linear section of the skb and data
is read outside of it.
This fix makes ip6_find_1stfrag return an error if it detects
running out-of-bounds.
[ 42.361487] ==================================================================
[ 42.364412] BUG: KASAN: slab-out-of-bounds in ip6_fragment+0x11c8/0x3730
[ 42.365471] Read of size 840 at addr ffff88000969e798 by task ip6_fragment-oo/3789
[ 42.366469]
[ 42.366696] CPU: 1 PID: 3789 Comm: ip6_fragment-oo Not tainted 4.11.0+ #41
[ 42.367628] Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.1-1ubuntu1 04/01/2014
[ 42.368824] Call Trace:
[ 42.369183] dump_stack+0xb3/0x10b
[ 42.369664] print_address_description+0x73/0x290
[ 42.370325] kasan_report+0x252/0x370
[ 42.370839] ? ip6_fragment+0x11c8/0x3730
[ 42.371396] check_memory_region+0x13c/0x1a0
[ 42.371978] memcpy+0x23/0x50
[ 42.372395] ip6_fragment+0x11c8/0x3730
[ 42.372920] ? nf_ct_expect_unregister_notifier+0x110/0x110
[ 42.373681] ? ip6_copy_metadata+0x7f0/0x7f0
[ 42.374263] ? ip6_forward+0x2e30/0x2e30
[ 42.374803] ip6_finish_output+0x584/0x990
[ 42.375350] ip6_output+0x1b7/0x690
[ 42.375836] ? ip6_finish_output+0x990/0x990
[ 42.376411] ? ip6_fragment+0x3730/0x3730
[ 42.376968] ip6_local_out+0x95/0x160
[ 42.377471] ip6_send_skb+0xa1/0x330
[ 42.377969] ip6_push_pending_frames+0xb3/0xe0
[ 42.378589] rawv6_sendmsg+0x2051/0x2db0
[ 42.379129] ? rawv6_bind+0x8b0/0x8b0
[ 42.379633] ? _copy_from_user+0x84/0xe0
[ 42.380193] ? debug_check_no_locks_freed+0x290/0x290
[ 42.380878] ? ___sys_sendmsg+0x162/0x930
[ 42.381427] ? rcu_read_lock_sched_held+0xa3/0x120
[ 42.382074] ? sock_has_perm+0x1f6/0x290
[ 42.382614] ? ___sys_sendmsg+0x167/0x930
[ 42.383173] ? lock_downgrade+0x660/0x660
[ 42.383727] inet_sendmsg+0x123/0x500
[ 42.384226] ? inet_sendmsg+0x123/0x500
[ 42.384748] ? inet_recvmsg+0x540/0x540
[ 42.385263] sock_sendmsg+0xca/0x110
[ 42.385758] SYSC_sendto+0x217/0x380
[ 42.386249] ? SYSC_connect+0x310/0x310
[ 42.386783] ? __might_fault+0x110/0x1d0
[ 42.387324] ? lock_downgrade+0x660/0x660
[ 42.387880] ? __fget_light+0xa1/0x1f0
[ 42.388403] ? __fdget+0x18/0x20
[ 42.388851] ? sock_common_setsockopt+0x95/0xd0
[ 42.389472] ? SyS_setsockopt+0x17f/0x260
[ 42.390021] ? entry_SYSCALL_64_fastpath+0x5/0xbe
[ 42.390650] SyS_sendto+0x40/0x50
[ 42.391103] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.391731] RIP: 0033:0x7fbbb711e383
[ 42.392217] RSP: 002b:00007ffff4d34f28 EFLAGS: 00000246 ORIG_RAX: 000000000000002c
[ 42.393235] RAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fbbb711e383
[ 42.394195] RDX: 0000000000001000 RSI: 00007ffff4d34f60 RDI: 0000000000000003
[ 42.395145] RBP: 0000000000000046 R08: 00007ffff4d34f40 R09: 0000000000000018
[ 42.396056] R10: 0000000000000000 R11: 0000000000000246 R12: 0000000000400aad
[ 42.396598] R13: 0000000000000066 R14: 00007ffff4d34ee0 R15: 00007fbbb717af00
[ 42.397257]
[ 42.397411] Allocated by task 3789:
[ 42.397702] save_stack_trace+0x16/0x20
[ 42.398005] save_stack+0x46/0xd0
[ 42.398267] kasan_kmalloc+0xad/0xe0
[ 42.398548] kasan_slab_alloc+0x12/0x20
[ 42.398848] __kmalloc_node_track_caller+0xcb/0x380
[ 42.399224] __kmalloc_reserve.isra.32+0x41/0xe0
[ 42.399654] __alloc_skb+0xf8/0x580
[ 42.400003] sock_wmalloc+0xab/0xf0
[ 42.400346] __ip6_append_data.isra.41+0x2472/0x33d0
[ 42.400813] ip6_append_data+0x1a8/0x2f0
[ 42.401122] rawv6_sendmsg+0x11ee/0x2db0
[ 42.401505] inet_sendmsg+0x123/0x500
[ 42.401860] sock_sendmsg+0xca/0x110
[ 42.402209] ___sys_sendmsg+0x7cb/0x930
[ 42.402582] __sys_sendmsg+0xd9/0x190
[ 42.402941] SyS_sendmsg+0x2d/0x50
[ 42.403273] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.403718]
[ 42.403871] Freed by task 1794:
[ 42.404146] save_stack_trace+0x16/0x20
[ 42.404515] save_stack+0x46/0xd0
[ 42.404827] kasan_slab_free+0x72/0xc0
[ 42.405167] kfree+0xe8/0x2b0
[ 42.405462] skb_free_head+0x74/0xb0
[ 42.405806] skb_release_data+0x30e/0x3a0
[ 42.406198] skb_release_all+0x4a/0x60
[ 42.406563] consume_skb+0x113/0x2e0
[ 42.406910] skb_free_datagram+0x1a/0xe0
[ 42.407288] netlink_recvmsg+0x60d/0xe40
[ 42.407667] sock_recvmsg+0xd7/0x110
[ 42.408022] ___sys_recvmsg+0x25c/0x580
[ 42.408395] __sys_recvmsg+0xd6/0x190
[ 42.408753] SyS_recvmsg+0x2d/0x50
[ 42.409086] entry_SYSCALL_64_fastpath+0x1f/0xbe
[ 42.409513]
[ 42.409665] The buggy address belongs to the object at ffff88000969e780
[ 42.409665] which belongs to the cache kmalloc-512 of size 512
[ 42.410846] The buggy address is located 24 bytes inside of
[ 42.410846] 512-byte region [ffff88000969e780, ffff88000969e980)
[ 42.411941] The buggy address belongs to the page:
[ 42.412405] page:ffffea000025a780 count:1 mapcount:0 mapping: (null) index:0x0 compound_mapcount: 0
[ 42.413298] flags: 0x100000000008100(slab|head)
[ 42.413729] raw: 0100000000008100 0000000000000000 0000000000000000 00000001800c000c
[ 42.414387] raw: ffffea00002a9500 0000000900000007 ffff88000c401280 0000000000000000
[ 42.415074] page dumped because: kasan: bad access detected
[ 42.415604]
[ 42.415757] Memory state around the buggy address:
[ 42.416222] ffff88000969e880: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.416904] ffff88000969e900: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
[ 42.417591] >ffff88000969e980: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc
[ 42.418273] ^
[ 42.418588] ffff88000969ea00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419273] ffff88000969ea80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb
[ 42.419882] ==================================================================
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Craig Gallek <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-125 | int ip6_fragment(struct net *net, struct sock *sk, struct sk_buff *skb,
int (*output)(struct net *, struct sock *, struct sk_buff *))
{
struct sk_buff *frag;
struct rt6_info *rt = (struct rt6_info *)skb_dst(skb);
struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ?
inet6_sk(skb->sk) : NULL;
struct ipv6hdr *tmp_hdr;
struct frag_hdr *fh;
unsigned int mtu, hlen, left, len;
int hroom, troom;
__be32 frag_id;
int ptr, offset = 0, err = 0;
u8 *prevhdr, nexthdr = 0;
hlen = ip6_find_1stfragopt(skb, &prevhdr);
if (hlen < 0) {
err = hlen;
goto fail;
}
nexthdr = *prevhdr;
mtu = ip6_skb_dst_mtu(skb);
/* We must not fragment if the socket is set to force MTU discovery
* or if the skb it not generated by a local socket.
*/
if (unlikely(!skb->ignore_df && skb->len > mtu))
goto fail_toobig;
if (IP6CB(skb)->frag_max_size) {
if (IP6CB(skb)->frag_max_size > mtu)
goto fail_toobig;
/* don't send fragments larger than what we received */
mtu = IP6CB(skb)->frag_max_size;
if (mtu < IPV6_MIN_MTU)
mtu = IPV6_MIN_MTU;
}
if (np && np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
if (mtu < hlen + sizeof(struct frag_hdr) + 8)
goto fail_toobig;
mtu -= hlen + sizeof(struct frag_hdr);
frag_id = ipv6_select_ident(net, &ipv6_hdr(skb)->daddr,
&ipv6_hdr(skb)->saddr);
if (skb->ip_summed == CHECKSUM_PARTIAL &&
(err = skb_checksum_help(skb)))
goto fail;
hroom = LL_RESERVED_SPACE(rt->dst.dev);
if (skb_has_frag_list(skb)) {
unsigned int first_len = skb_pagelen(skb);
struct sk_buff *frag2;
if (first_len - hlen > mtu ||
((first_len - hlen) & 7) ||
skb_cloned(skb) ||
skb_headroom(skb) < (hroom + sizeof(struct frag_hdr)))
goto slow_path;
skb_walk_frags(skb, frag) {
/* Correct geometry. */
if (frag->len > mtu ||
((frag->len & 7) && frag->next) ||
skb_headroom(frag) < (hlen + hroom + sizeof(struct frag_hdr)))
goto slow_path_clean;
/* Partially cloned skb? */
if (skb_shared(frag))
goto slow_path_clean;
BUG_ON(frag->sk);
if (skb->sk) {
frag->sk = skb->sk;
frag->destructor = sock_wfree;
}
skb->truesize -= frag->truesize;
}
err = 0;
offset = 0;
/* BUILD HEADER */
*prevhdr = NEXTHDR_FRAGMENT;
tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC);
if (!tmp_hdr) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
frag = skb_shinfo(skb)->frag_list;
skb_frag_list_init(skb);
__skb_pull(skb, hlen);
fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr));
__skb_push(skb, hlen);
skb_reset_network_header(skb);
memcpy(skb_network_header(skb), tmp_hdr, hlen);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(IP6_MF);
fh->identification = frag_id;
first_len = skb_pagelen(skb);
skb->data_len = first_len - skb_headlen(skb);
skb->len = first_len;
ipv6_hdr(skb)->payload_len = htons(first_len -
sizeof(struct ipv6hdr));
dst_hold(&rt->dst);
for (;;) {
/* Prepare header of the next frame,
* before previous one went down. */
if (frag) {
frag->ip_summed = CHECKSUM_NONE;
skb_reset_transport_header(frag);
fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr));
__skb_push(frag, hlen);
skb_reset_network_header(frag);
memcpy(skb_network_header(frag), tmp_hdr,
hlen);
offset += skb->len - hlen - sizeof(struct frag_hdr);
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->frag_off = htons(offset);
if (frag->next)
fh->frag_off |= htons(IP6_MF);
fh->identification = frag_id;
ipv6_hdr(frag)->payload_len =
htons(frag->len -
sizeof(struct ipv6hdr));
ip6_copy_metadata(frag, skb);
}
err = output(net, sk, skb);
if (!err)
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGCREATES);
if (err || !frag)
break;
skb = frag;
frag = skb->next;
skb->next = NULL;
}
kfree(tmp_hdr);
if (err == 0) {
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGOKS);
ip6_rt_put(rt);
return 0;
}
kfree_skb_list(frag);
IP6_INC_STATS(net, ip6_dst_idev(&rt->dst),
IPSTATS_MIB_FRAGFAILS);
ip6_rt_put(rt);
return err;
slow_path_clean:
skb_walk_frags(skb, frag2) {
if (frag2 == frag)
break;
frag2->sk = NULL;
frag2->destructor = NULL;
skb->truesize += frag2->truesize;
}
}
slow_path:
left = skb->len - hlen; /* Space per frame */
ptr = hlen; /* Where to start from */
/*
* Fragment the datagram.
*/
troom = rt->dst.dev->needed_tailroom;
/*
* Keep copying data until we run out.
*/
while (left > 0) {
u8 *fragnexthdr_offset;
len = left;
/* IF: it doesn't fit, use 'mtu' - the data space left */
if (len > mtu)
len = mtu;
/* IF: we are not sending up to and including the packet end
then align the next start on an eight byte boundary */
if (len < left) {
len &= ~7;
}
/* Allocate buffer */
frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) +
hroom + troom, GFP_ATOMIC);
if (!frag) {
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
err = -ENOMEM;
goto fail;
}
/*
* Set up data on packet
*/
ip6_copy_metadata(frag, skb);
skb_reserve(frag, hroom);
skb_put(frag, len + hlen + sizeof(struct frag_hdr));
skb_reset_network_header(frag);
fh = (struct frag_hdr *)(skb_network_header(frag) + hlen);
frag->transport_header = (frag->network_header + hlen +
sizeof(struct frag_hdr));
/*
* Charge the memory for the fragment to any owner
* it might possess
*/
if (skb->sk)
skb_set_owner_w(frag, skb->sk);
/*
* Copy the packet header into the new buffer.
*/
skb_copy_from_linear_data(skb, skb_network_header(frag), hlen);
fragnexthdr_offset = skb_network_header(frag);
fragnexthdr_offset += prevhdr - skb_network_header(skb);
*fragnexthdr_offset = NEXTHDR_FRAGMENT;
/*
* Build fragment header.
*/
fh->nexthdr = nexthdr;
fh->reserved = 0;
fh->identification = frag_id;
/*
* Copy a block of the IP datagram.
*/
BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag),
len));
left -= len;
fh->frag_off = htons(offset);
if (left > 0)
fh->frag_off |= htons(IP6_MF);
ipv6_hdr(frag)->payload_len = htons(frag->len -
sizeof(struct ipv6hdr));
ptr += len;
offset += len;
/*
* Put this fragment into the sending queue.
*/
err = output(net, sk, frag);
if (err)
goto fail;
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGCREATES);
}
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGOKS);
consume_skb(skb);
return err;
fail_toobig:
if (skb->sk && dst_allfrag(skb_dst(skb)))
sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK);
skb->dev = skb_dst(skb)->dev;
icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu);
err = -EMSGSIZE;
fail:
IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)),
IPSTATS_MIB_FRAGFAILS);
kfree_skb(skb);
return err;
}
| 168,131 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void encode_frame(vpx_codec_ctx_t *codec,
vpx_image_t *img,
int frame_index,
VpxVideoWriter *writer) {
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0,
VPX_DL_GOOD_QUALITY);
if (res != VPX_CODEC_OK)
die_codec(codec, "Failed to encode frame");
while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer,
pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts)) {
die_codec(codec, "Failed to write compressed frame");
}
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
}
Commit Message: Merge Conflict Fix CL to lmp-mr1-release for ag/849478
DO NOT MERGE - libvpx: Pull from upstream
Current HEAD: 7105df53d7dc13d5e575bc8df714ec8d1da36b06
BUG=23452792
Change-Id: Ic78176fc369e0bacc71d423e0e2e6075d004aaec
CWE ID: CWE-119 | static void encode_frame(vpx_codec_ctx_t *codec,
static int encode_frame(vpx_codec_ctx_t *codec,
vpx_image_t *img,
int frame_index,
VpxVideoWriter *writer) {
int got_pkts = 0;
vpx_codec_iter_t iter = NULL;
const vpx_codec_cx_pkt_t *pkt = NULL;
const vpx_codec_err_t res = vpx_codec_encode(codec, img, frame_index, 1, 0,
VPX_DL_GOOD_QUALITY);
if (res != VPX_CODEC_OK)
die_codec(codec, "Failed to encode frame");
while ((pkt = vpx_codec_get_cx_data(codec, &iter)) != NULL) {
got_pkts = 1;
if (pkt->kind == VPX_CODEC_CX_FRAME_PKT) {
const int keyframe = (pkt->data.frame.flags & VPX_FRAME_IS_KEY) != 0;
if (!vpx_video_writer_write_frame(writer,
pkt->data.frame.buf,
pkt->data.frame.sz,
pkt->data.frame.pts)) {
die_codec(codec, "Failed to write compressed frame");
}
printf(keyframe ? "K" : ".");
fflush(stdout);
}
}
return got_pkts;
}
| 174,481 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
bp += 4;
while (bp < ep) {
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_TCHECK2(bp[0], 4 + olen);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);
if (advance < 0) {
ND_PRINT((ndo, "..."));
break;
}
ptr += advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp+4))));
bp += 8; len -= 8;
/* encapsulated multicast packet */
ip = (const struct ip *)bp;
switch (IP_V(ip)) {
case 0: /* Null header */
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
bp += 4; len -= 4;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
if (bp >= ep)
break;
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
}
if (bp + 4 > ep)
break;
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
if (bp >= ep)
goto jp_done;
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
if (bp + 4 > ep) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
}
jp_done:
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
bp += 4;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (bp + sizeof(uint16_t) >= ep) break;
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
if (bp >= ep) break;
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
/* Encoded-Unicast-BSR-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (bp >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
bp += 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp,
pimv2_unicast,
0)) < 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (bp + 2 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",prio=%d", bp[2]));
bp += 4;
}
ND_PRINT((ndo, ")"));
}
bs_done:
break;
}
case PIMV2_TYPE_ASSERT:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp + 8 > ep)
break;
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
bp += 4;
/* Prefix-Cnt, Priority, and Holdtime */
if (bp >= ep) break;
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " prio=%d", bp[1]));
if (bp + 3 >= ep) break;
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
/* Encoded-Unicast-RP-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_TCHECK2(bp[0], 2);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
}
Commit Message: CVE-2017-12996/PIMv2: Make sure PIM TLVs have the right length.
We do bounds checks based on the TLV length, so if the TLV's length is
too short, and we don't check for that, we could end up fetching data
past the end of the TLV - including past the length of the captured data
in the packet.
This fixes a buffer over-read discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add tests using the capture files supplied by the reporter(s).
CWE ID: CWE-125 | pimv2_print(netdissect_options *ndo,
register const u_char *bp, register u_int len, const u_char *bp2)
{
register const u_char *ep;
register const struct pim *pim = (const struct pim *)bp;
int advance;
enum checksum_status cksum_status;
ep = (const u_char *)ndo->ndo_snapend;
if (bp >= ep)
return;
if (ep > bp + len)
ep = bp + len;
ND_TCHECK(pim->pim_rsv);
pimv2_addr_len = pim->pim_rsv;
if (pimv2_addr_len != 0)
ND_PRINT((ndo, ", RFC2117-encoding"));
ND_PRINT((ndo, ", cksum 0x%04x ", EXTRACT_16BITS(&pim->pim_cksum)));
if (EXTRACT_16BITS(&pim->pim_cksum) == 0) {
ND_PRINT((ndo, "(unverified)"));
} else {
if (PIM_TYPE(pim->pim_typever) == PIMV2_TYPE_REGISTER) {
/*
* The checksum only covers the packet header,
* not the encapsulated packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, 8);
if (cksum_status == INCORRECT) {
/*
* To quote RFC 4601, "For interoperability
* reasons, a message carrying a checksum
* calculated over the entire PIM Register
* message should also be accepted."
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
} else {
/*
* The checksum covers the entire packet.
*/
cksum_status = pimv2_check_checksum(ndo, bp, bp2, len);
}
switch (cksum_status) {
case CORRECT:
ND_PRINT((ndo, "(correct)"));
break;
case INCORRECT:
ND_PRINT((ndo, "(incorrect)"));
break;
case UNVERIFIED:
ND_PRINT((ndo, "(unverified)"));
break;
}
}
switch (PIM_TYPE(pim->pim_typever)) {
case PIMV2_TYPE_HELLO:
{
uint16_t otype, olen;
bp += 4;
while (bp < ep) {
ND_TCHECK2(bp[0], 4);
otype = EXTRACT_16BITS(&bp[0]);
olen = EXTRACT_16BITS(&bp[2]);
ND_TCHECK2(bp[0], 4 + olen);
ND_PRINT((ndo, "\n\t %s Option (%u), length %u, Value: ",
tok2str(pimv2_hello_option_values, "Unknown", otype),
otype,
olen));
bp += 4;
switch (otype) {
case PIMV2_HELLO_OPTION_HOLDTIME:
if (olen != 2) {
ND_PRINT((ndo, "ERROR: Option Length != 2 Bytes (%u)", olen));
} else {
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
}
break;
case PIMV2_HELLO_OPTION_LANPRUNEDELAY:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
char t_bit;
uint16_t lan_delay, override_interval;
lan_delay = EXTRACT_16BITS(bp);
override_interval = EXTRACT_16BITS(bp+2);
t_bit = (lan_delay & 0x8000)? 1 : 0;
lan_delay &= ~0x8000;
ND_PRINT((ndo, "\n\t T-bit=%d, LAN delay %dms, Override interval %dms",
t_bit, lan_delay, override_interval));
}
break;
case PIMV2_HELLO_OPTION_DR_PRIORITY_OLD:
case PIMV2_HELLO_OPTION_DR_PRIORITY:
switch (olen) {
case 0:
ND_PRINT((ndo, "Bi-Directional Capability (Old)"));
break;
case 4:
ND_PRINT((ndo, "%u", EXTRACT_32BITS(bp)));
break;
default:
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
break;
}
break;
case PIMV2_HELLO_OPTION_GENID:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "0x%08x", EXTRACT_32BITS(bp)));
}
break;
case PIMV2_HELLO_OPTION_REFRESH_CAP:
if (olen != 4) {
ND_PRINT((ndo, "ERROR: Option Length != 4 Bytes (%u)", olen));
} else {
ND_PRINT((ndo, "v%d", *bp));
if (*(bp+1) != 0) {
ND_PRINT((ndo, ", interval "));
unsigned_relts_print(ndo, *(bp+1));
}
if (EXTRACT_16BITS(bp+2) != 0) {
ND_PRINT((ndo, " ?0x%04x?", EXTRACT_16BITS(bp+2)));
}
}
break;
case PIMV2_HELLO_OPTION_BIDIR_CAP:
break;
case PIMV2_HELLO_OPTION_ADDRESS_LIST_OLD:
case PIMV2_HELLO_OPTION_ADDRESS_LIST:
if (ndo->ndo_vflag > 1) {
const u_char *ptr = bp;
while (ptr < (bp+olen)) {
ND_PRINT((ndo, "\n\t "));
advance = pimv2_addr_print(ndo, ptr, pimv2_unicast, 0);
if (advance < 0) {
ND_PRINT((ndo, "..."));
break;
}
ptr += advance;
}
}
break;
default:
if (ndo->ndo_vflag <= 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
break;
}
/* do we want to see an additionally hexdump ? */
if (ndo->ndo_vflag> 1)
print_unknown_data(ndo, bp, "\n\t ", olen);
bp += olen;
}
break;
}
case PIMV2_TYPE_REGISTER:
{
const struct ip *ip;
ND_TCHECK2(*(bp + 4), PIMV2_REGISTER_FLAG_LEN);
ND_PRINT((ndo, ", Flags [ %s ]\n\t",
tok2str(pimv2_register_flag_values,
"none",
EXTRACT_32BITS(bp+4))));
bp += 8; len -= 8;
/* encapsulated multicast packet */
ip = (const struct ip *)bp;
switch (IP_V(ip)) {
case 0: /* Null header */
ND_PRINT((ndo, "IP-Null-header %s > %s",
ipaddr_string(ndo, &ip->ip_src),
ipaddr_string(ndo, &ip->ip_dst)));
break;
case 4: /* IPv4 */
ip_print(ndo, bp, len);
break;
case 6: /* IPv6 */
ip6_print(ndo, bp, len);
break;
default:
ND_PRINT((ndo, "IP ver %d", IP_V(ip)));
break;
}
break;
}
case PIMV2_TYPE_REGISTER_STOP:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " source="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
break;
case PIMV2_TYPE_JOIN_PRUNE:
case PIMV2_TYPE_GRAFT:
case PIMV2_TYPE_GRAFT_ACK:
/*
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* |PIM Ver| Type | Addr length | Checksum |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Unicast-Upstream Neighbor Address |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Reserved | Num groups | Holdtime |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Number of Joined Sources | Number of Pruned Sources |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Joined Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-1 |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Pruned Source Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | . |
* | . |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | Encoded-Multicast Group Address-n |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
{
uint8_t ngroup;
uint16_t holdtime;
uint16_t njoin;
uint16_t nprune;
int i, j;
bp += 4; len -= 4;
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
if (bp >= ep)
break;
ND_PRINT((ndo, ", upstream-neighbor: "));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
}
if (bp + 4 > ep)
break;
ngroup = bp[1];
holdtime = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, "\n\t %u group(s)", ngroup));
if (PIM_TYPE(pim->pim_typever) != 7) { /*not for Graft-ACK*/
ND_PRINT((ndo, ", holdtime: "));
if (holdtime == 0xffff)
ND_PRINT((ndo, "infinite"));
else
unsigned_relts_print(ndo, holdtime);
}
bp += 4; len -= 4;
for (i = 0; i < ngroup; i++) {
if (bp >= ep)
goto jp_done;
ND_PRINT((ndo, "\n\t group #%u: ", i+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
if (bp + 4 > ep) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
njoin = EXTRACT_16BITS(&bp[0]);
nprune = EXTRACT_16BITS(&bp[2]);
ND_PRINT((ndo, ", joined sources: %u, pruned sources: %u", njoin, nprune));
bp += 4; len -= 4;
for (j = 0; j < njoin; j++) {
ND_PRINT((ndo, "\n\t joined source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
for (j = 0; j < nprune; j++) {
ND_PRINT((ndo, "\n\t pruned source #%u: ", j+1));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_source, 0)) < 0) {
ND_PRINT((ndo, "...)"));
goto jp_done;
}
bp += advance; len -= advance;
}
}
jp_done:
break;
}
case PIMV2_TYPE_BOOTSTRAP:
{
int i, j, frpcnt;
bp += 4;
/* Fragment Tag, Hash Mask len, and BSR-priority */
if (bp + sizeof(uint16_t) >= ep) break;
ND_PRINT((ndo, " tag=%x", EXTRACT_16BITS(bp)));
bp += sizeof(uint16_t);
if (bp >= ep) break;
ND_PRINT((ndo, " hashmlen=%d", bp[0]));
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " BSRprio=%d", bp[1]));
bp += 2;
/* Encoded-Unicast-BSR-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " BSR="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
for (i = 0; bp < ep; i++) {
/* Encoded-Group Address */
ND_PRINT((ndo, " (group%d: ", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
/* RP-Count, Frag RP-Cnt, and rsvd */
if (bp >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " RPcnt=%d", bp[0]));
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, " FRPcnt=%d", frpcnt = bp[1]));
bp += 4;
for (j = 0; j < frpcnt && bp < ep; j++) {
/* each RP info */
ND_PRINT((ndo, " RP%d=", j));
if ((advance = pimv2_addr_print(ndo, bp,
pimv2_unicast,
0)) < 0) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
bp += advance;
if (bp + 1 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
if (bp + 2 >= ep) {
ND_PRINT((ndo, "...)"));
goto bs_done;
}
ND_PRINT((ndo, ",prio=%d", bp[2]));
bp += 4;
}
ND_PRINT((ndo, ")"));
}
bs_done:
break;
}
case PIMV2_TYPE_ASSERT:
bp += 4; len -= 4;
if (bp >= ep)
break;
ND_PRINT((ndo, " group="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp >= ep)
break;
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance; len -= advance;
if (bp + 8 > ep)
break;
if (bp[0] & 0x80)
ND_PRINT((ndo, " RPT"));
ND_PRINT((ndo, " pref=%u", EXTRACT_32BITS(&bp[0]) & 0x7fffffff));
ND_PRINT((ndo, " metric=%u", EXTRACT_32BITS(&bp[4])));
break;
case PIMV2_TYPE_CANDIDATE_RP:
{
int i, pfxcnt;
bp += 4;
/* Prefix-Cnt, Priority, and Holdtime */
if (bp >= ep) break;
ND_PRINT((ndo, " prefix-cnt=%d", bp[0]));
pfxcnt = bp[0];
if (bp + 1 >= ep) break;
ND_PRINT((ndo, " prio=%d", bp[1]));
if (bp + 3 >= ep) break;
ND_PRINT((ndo, " holdtime="));
unsigned_relts_print(ndo, EXTRACT_16BITS(&bp[2]));
bp += 4;
/* Encoded-Unicast-RP-Address */
if (bp >= ep) break;
ND_PRINT((ndo, " RP="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
/* Encoded-Group Addresses */
for (i = 0; i < pfxcnt && bp < ep; i++) {
ND_PRINT((ndo, " Group%d=", i));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0))
< 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
}
break;
}
case PIMV2_TYPE_PRUNE_REFRESH:
ND_PRINT((ndo, " src="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " grp="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_group, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_PRINT((ndo, " forwarder="));
if ((advance = pimv2_addr_print(ndo, bp, pimv2_unicast, 0)) < 0) {
ND_PRINT((ndo, "..."));
break;
}
bp += advance;
ND_TCHECK2(bp[0], 2);
ND_PRINT((ndo, " TUNR "));
unsigned_relts_print(ndo, EXTRACT_16BITS(bp));
break;
default:
ND_PRINT((ndo, " [type %d]", PIM_TYPE(pim->pim_typever)));
break;
}
return;
trunc:
ND_PRINT((ndo, "[|pim]"));
}
| 167,911 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ZSTD_encodeSequences_body(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets)
{
BIT_CStream_t blockStream;
FSE_CState_t stateMatchLength;
FSE_CState_t stateOffsetBits;
FSE_CState_t stateLitLength;
CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
/* first symbols */
FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
if (longOffsets) {
U32 const ofBits = ofCodeTable[nbSeq-1];
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
BIT_flushBits(&blockStream);
}
BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
ofBits - extraBits);
} else {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
}
BIT_flushBits(&blockStream);
{ size_t n;
for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
BYTE const llCode = llCodeTable[n];
BYTE const ofCode = ofCodeTable[n];
BYTE const mlCode = mlCodeTable[n];
U32 const llBits = LL_bits[llCode];
U32 const ofBits = ofCode;
U32 const mlBits = ML_bits[mlCode];
DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
sequences[n].litLength,
sequences[n].matchLength + MINMATCH,
sequences[n].offset);
/* 32b*/ /* 64b*/
/* (7)*/ /* (7)*/
FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
BIT_flushBits(&blockStream); /* (7)*/
BIT_addBits(&blockStream, sequences[n].litLength, llBits);
if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
if (longOffsets) {
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[n].offset, extraBits);
BIT_flushBits(&blockStream); /* (7)*/
}
BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
ofBits - extraBits); /* 31 */
} else {
BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
}
BIT_flushBits(&blockStream); /* (7)*/
} }
DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
FSE_flushCState(&blockStream, &stateMatchLength);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
FSE_flushCState(&blockStream, &stateOffsetBits);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
FSE_flushCState(&blockStream, &stateLitLength);
{ size_t const streamSize = BIT_closeCStream(&blockStream);
if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
return streamSize;
}
}
Commit Message: fixed T36302429
CWE ID: CWE-362 | ZSTD_encodeSequences_body(
void* dst, size_t dstCapacity,
FSE_CTable const* CTable_MatchLength, BYTE const* mlCodeTable,
FSE_CTable const* CTable_OffsetBits, BYTE const* ofCodeTable,
FSE_CTable const* CTable_LitLength, BYTE const* llCodeTable,
seqDef const* sequences, size_t nbSeq, int longOffsets)
{
BIT_CStream_t blockStream;
FSE_CState_t stateMatchLength;
FSE_CState_t stateOffsetBits;
FSE_CState_t stateLitLength;
CHECK_E(BIT_initCStream(&blockStream, dst, dstCapacity), dstSize_tooSmall); /* not enough space remaining */
DEBUGLOG(6, "available space for bitstream : %i (dstCapacity=%u)",
(int)(blockStream.endPtr - blockStream.startPtr),
(unsigned)dstCapacity);
/* first symbols */
FSE_initCState2(&stateMatchLength, CTable_MatchLength, mlCodeTable[nbSeq-1]);
FSE_initCState2(&stateOffsetBits, CTable_OffsetBits, ofCodeTable[nbSeq-1]);
FSE_initCState2(&stateLitLength, CTable_LitLength, llCodeTable[nbSeq-1]);
BIT_addBits(&blockStream, sequences[nbSeq-1].litLength, LL_bits[llCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[nbSeq-1].matchLength, ML_bits[mlCodeTable[nbSeq-1]]);
if (MEM_32bits()) BIT_flushBits(&blockStream);
if (longOffsets) {
U32 const ofBits = ofCodeTable[nbSeq-1];
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, extraBits);
BIT_flushBits(&blockStream);
}
BIT_addBits(&blockStream, sequences[nbSeq-1].offset >> extraBits,
ofBits - extraBits);
} else {
BIT_addBits(&blockStream, sequences[nbSeq-1].offset, ofCodeTable[nbSeq-1]);
}
BIT_flushBits(&blockStream);
{ size_t n;
for (n=nbSeq-2 ; n<nbSeq ; n--) { /* intentional underflow */
BYTE const llCode = llCodeTable[n];
BYTE const ofCode = ofCodeTable[n];
BYTE const mlCode = mlCodeTable[n];
U32 const llBits = LL_bits[llCode];
U32 const ofBits = ofCode;
U32 const mlBits = ML_bits[mlCode];
DEBUGLOG(6, "encoding: litlen:%2u - matchlen:%2u - offCode:%7u",
sequences[n].litLength,
sequences[n].matchLength + MINMATCH,
sequences[n].offset);
/* 32b*/ /* 64b*/
/* (7)*/ /* (7)*/
FSE_encodeSymbol(&blockStream, &stateOffsetBits, ofCode); /* 15 */ /* 15 */
FSE_encodeSymbol(&blockStream, &stateMatchLength, mlCode); /* 24 */ /* 24 */
if (MEM_32bits()) BIT_flushBits(&blockStream); /* (7)*/
FSE_encodeSymbol(&blockStream, &stateLitLength, llCode); /* 16 */ /* 33 */
if (MEM_32bits() || (ofBits+mlBits+llBits >= 64-7-(LLFSELog+MLFSELog+OffFSELog)))
BIT_flushBits(&blockStream); /* (7)*/
BIT_addBits(&blockStream, sequences[n].litLength, llBits);
if (MEM_32bits() && ((llBits+mlBits)>24)) BIT_flushBits(&blockStream);
BIT_addBits(&blockStream, sequences[n].matchLength, mlBits);
if (MEM_32bits() || (ofBits+mlBits+llBits > 56)) BIT_flushBits(&blockStream);
if (longOffsets) {
int const extraBits = ofBits - MIN(ofBits, STREAM_ACCUMULATOR_MIN-1);
if (extraBits) {
BIT_addBits(&blockStream, sequences[n].offset, extraBits);
BIT_flushBits(&blockStream); /* (7)*/
}
BIT_addBits(&blockStream, sequences[n].offset >> extraBits,
ofBits - extraBits); /* 31 */
} else {
BIT_addBits(&blockStream, sequences[n].offset, ofBits); /* 31 */
}
BIT_flushBits(&blockStream); /* (7)*/
DEBUGLOG(7, "remaining space : %i", (int)(blockStream.endPtr - blockStream.ptr));
} }
DEBUGLOG(6, "ZSTD_encodeSequences: flushing ML state with %u bits", stateMatchLength.stateLog);
FSE_flushCState(&blockStream, &stateMatchLength);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing Off state with %u bits", stateOffsetBits.stateLog);
FSE_flushCState(&blockStream, &stateOffsetBits);
DEBUGLOG(6, "ZSTD_encodeSequences: flushing LL state with %u bits", stateLitLength.stateLog);
FSE_flushCState(&blockStream, &stateLitLength);
{ size_t const streamSize = BIT_closeCStream(&blockStream);
if (streamSize==0) return ERROR(dstSize_tooSmall); /* not enough space */
return streamSize;
}
}
| 169,674 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: create_principal3_2_svc(cprinc3_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name, service_name;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_ADD;
log_unauth("kadm5_create_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_create_principal_3((void *)handle,
&arg->rec, arg->mask,
arg->n_ks_tuple,
arg->ks_tuple,
arg->passwd);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_create_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
exit_func:
free_server_handle(handle);
return &ret;
}
Commit Message: Fix leaks in kadmin server stubs [CVE-2015-8631]
In each kadmind server stub, initialize the client_name and
server_name variables, and release them in the cleanup handler. Many
of the stubs will otherwise leak the client and server name if
krb5_unparse_name() fails. Also make sure to free the prime_arg
variables in rename_principal_2_svc(), or we can leak the first one if
unparsing the second one fails. Discovered by Simo Sorce.
CVE-2015-8631:
In all versions of MIT krb5, an authenticated attacker can cause
kadmind to leak memory by supplying a null principal name in a request
which uses one. Repeating these requests will eventually cause
kadmind to exhaust all available memory.
CVSSv2 Vector: AV:N/AC:L/Au:S/C:N/I:N/A:C/E:POC/RL:OF/RC:C
ticket: 8343 (new)
target_version: 1.14-next
target_version: 1.13-next
tags: pullup
CWE ID: CWE-119 | create_principal3_2_svc(cprinc3_arg *arg, struct svc_req *rqstp)
{
static generic_ret ret;
char *prime_arg;
gss_buffer_desc client_name = GSS_C_EMPTY_BUFFER;
gss_buffer_desc service_name = GSS_C_EMPTY_BUFFER;
OM_uint32 minor_stat;
kadm5_server_handle_t handle;
restriction_t *rp;
const char *errmsg = NULL;
xdr_free(xdr_generic_ret, &ret);
if ((ret.code = new_server_handle(arg->api_version, rqstp, &handle)))
goto exit_func;
if ((ret.code = check_handle((void *)handle)))
goto exit_func;
ret.api_version = handle->api_version;
if (setup_gss_names(rqstp, &client_name, &service_name) < 0) {
ret.code = KADM5_FAILURE;
goto exit_func;
}
if (krb5_unparse_name(handle->context, arg->rec.principal, &prime_arg)) {
ret.code = KADM5_BAD_PRINCIPAL;
goto exit_func;
}
if (CHANGEPW_SERVICE(rqstp)
|| !kadm5int_acl_check(handle->context, rqst2name(rqstp), ACL_ADD,
arg->rec.principal, &rp)
|| kadm5int_acl_impose_restrictions(handle->context,
&arg->rec, &arg->mask, rp)) {
ret.code = KADM5_AUTH_ADD;
log_unauth("kadm5_create_principal", prime_arg,
&client_name, &service_name, rqstp);
} else {
ret.code = kadm5_create_principal_3((void *)handle,
&arg->rec, arg->mask,
arg->n_ks_tuple,
arg->ks_tuple,
arg->passwd);
if( ret.code != 0 )
errmsg = krb5_get_error_message(handle->context, ret.code);
log_done("kadm5_create_principal", prime_arg, errmsg,
&client_name, &service_name, rqstp);
if (errmsg != NULL)
krb5_free_error_message(handle->context, errmsg);
}
free(prime_arg);
exit_func:
gss_release_buffer(&minor_stat, &client_name);
gss_release_buffer(&minor_stat, &service_name);
free_server_handle(handle);
return &ret;
}
| 167,509 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SSLCertErrorHandler::SSLCertErrorHandler(
base::WeakPtr<Delegate> delegate,
const content::GlobalRequestID& id,
ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id,
const net::SSLInfo& ssl_info,
bool fatal)
: SSLErrorHandler(delegate, id, resource_type, url, render_process_id,
render_view_id),
ssl_info_(ssl_info),
cert_error_(net::MapCertStatusToNetError(ssl_info.cert_status)),
fatal_(fatal) {
}
Commit Message: Inherits SupportsWeakPtr<T> instead of having WeakPtrFactory<T>
This change refines r137676.
BUG=122654
TEST=browser_test
Review URL: https://chromiumcodereview.appspot.com/10332233
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139771 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | SSLCertErrorHandler::SSLCertErrorHandler(
const base::WeakPtr<Delegate>& delegate,
const content::GlobalRequestID& id,
ResourceType::Type resource_type,
const GURL& url,
int render_process_id,
int render_view_id,
const net::SSLInfo& ssl_info,
bool fatal)
: SSLErrorHandler(delegate, id, resource_type, url, render_process_id,
render_view_id),
ssl_info_(ssl_info),
cert_error_(net::MapCertStatusToNetError(ssl_info.cert_status)),
fatal_(fatal) {
}
| 170,994 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
ND_PRINT((ndo," n len=%d", ntohs(e.len) - 4));
if (2 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (1 < ndo->ndo_vflag && 4 < ntohs(e.len)) {
ND_PRINT((ndo," "));
if (!ike_show_somedata(ndo, (const u_char *)(const uint8_t *)(ext + 1), ep))
goto trunc;
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
Commit Message: CVE-2017-12990/Fix printing of ISAKMPv1 Notification payload data.
The closest thing to a specification for the contents of the payload
data is draft-ietf-ipsec-notifymsg-04, and nothing in there says that it
is ever a complete ISAKMP message, so don't dissect types we don't have
specific code for as a complete ISAKMP message.
While we're at it, fix a comment, and clean up printing of V1 Nonce,
V2 Authentication payloads, and v2 Notice payloads.
This fixes an infinite loop discovered by Forcepoint's security
researchers Otto Airamo & Antti Levomäki.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-835 | ikev1_nonce_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext,
u_int item_len _U_,
const u_char *ep,
uint32_t phase _U_, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
struct isakmp_gen e;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_NONCE)));
ND_TCHECK(*ext);
UNALIGNED_MEMCPY(&e, ext, sizeof(e));
/*
* Our caller has ensured that the length is >= 4.
*/
ND_PRINT((ndo," n len=%u", ntohs(e.len) - 4));
if (ntohs(e.len) > 4) {
if (ndo->ndo_vflag > 2) {
ND_PRINT((ndo, " "));
if (!rawprint(ndo, (const uint8_t *)(ext + 1), ntohs(e.len) - 4))
goto trunc;
} else if (ndo->ndo_vflag > 1) {
ND_PRINT((ndo, " "));
if (!ike_show_somedata(ndo, (const u_char *)(ext + 1), ep))
goto trunc;
}
}
return (const u_char *)ext + ntohs(e.len);
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_NONCE)));
return NULL;
}
| 167,925 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: InternalWebIntentsDispatcherTest() {
replied_ = 0;
}
Commit Message: Fix uninitialized member in ctor.
[email protected]
[email protected]
BUG=none
TEST=none
Review URL: https://chromiumcodereview.appspot.com/10377180
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137606 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | InternalWebIntentsDispatcherTest() {
InternalWebIntentsDispatcherTest()
: replied_(0),
notified_reply_type_(webkit_glue::WEB_INTENT_REPLY_INVALID) {
}
| 170,761 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian,
const unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) ((buffer[1] << 8) | buffer[0]);
return((unsigned short) (value & 0xffff));
}
value=(unsigned short) ((((unsigned char *) buffer)[0] << 8) |
((unsigned char *) buffer)[1]);
return((unsigned short) (value & 0xffff));
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline unsigned short ReadPropertyUnsignedShort(const EndianType endian,
const unsigned char *buffer)
{
unsigned short
value;
if (endian == LSBEndian)
{
value=(unsigned short) buffer[1] << 8;
value|=(unsigned short) buffer[0];
return(value & 0xffff);
}
value=(unsigned short) buffer[0] << 8;
value|=(unsigned short) buffer[1];
return(value & 0xffff);
}
| 169,957 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: MagickExport int LocaleUppercase(const int c)
{
if (c < 0)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
Commit Message: ...
CWE ID: CWE-125 | MagickExport int LocaleUppercase(const int c)
{
if (c == EOF)
return(c);
#if defined(MAGICKCORE_LOCALE_SUPPORT)
if (c_locale != (locale_t) NULL)
return(toupper_l((int) ((unsigned char) c),c_locale));
#endif
return(toupper((int) ((unsigned char) c)));
}
| 170,236 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ScreenLayoutObserver::GetDisplayMessageForNotification(
const ScreenLayoutObserver::DisplayInfoMap& old_info,
base::string16* out_message,
base::string16* out_additional_message) {
if (old_display_mode_ != current_display_mode_) {
if (current_display_mode_ == DisplayMode::MIRRORING) {
*out_message = GetEnterMirrorModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::MIRRORING &&
GetExitMirrorModeMessage(out_message, out_additional_message)) {
return true;
}
if (current_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetEnterUnifiedModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetExitUnifiedModeMessage();
return true;
}
if (current_display_mode_ == DisplayMode::DOCKED ||
old_display_mode_ == DisplayMode::DOCKED) {
return false;
}
}
if (display_info_.size() < old_info.size()) {
for (const auto& iter : old_info) {
if (display_info_.count(iter.first))
continue;
*out_message =
GetDisplayRemovedMessage(iter.second, out_additional_message);
return true;
}
} else if (display_info_.size() > old_info.size()) {
for (const auto& iter : display_info_) {
if (old_info.count(iter.first))
continue;
*out_message = GetDisplayAddedMessage(iter.first, out_additional_message);
return true;
}
}
for (const auto& iter : display_info_) {
DisplayInfoMap::const_iterator old_iter = old_info.find(iter.first);
if (old_iter == old_info.end()) {
NOTREACHED() << "A display mode transition that should have been handled"
"earlier.";
return false;
}
if (iter.second.configured_ui_scale() !=
old_iter->second.configured_ui_scale()) {
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_RESOLUTION_CHANGED,
GetDisplayName(iter.first), GetDisplaySize(iter.first));
return true;
}
if (iter.second.GetActiveRotation() !=
old_iter->second.GetActiveRotation()) {
int rotation_text_id = 0;
switch (iter.second.GetActiveRotation()) {
case display::Display::ROTATE_0:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_STANDARD_ORIENTATION;
break;
case display::Display::ROTATE_90:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90;
break;
case display::Display::ROTATE_180:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180;
break;
case display::Display::ROTATE_270:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270;
break;
}
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_ROTATED, GetDisplayName(iter.first),
l10n_util::GetStringUTF16(rotation_text_id));
return true;
}
}
return false;
}
Commit Message: Avoid Showing rotation change notification when source is accelerometer
BUG=717252
TEST=Manually rotate device with accelerometer and observe there's no notification
Review-Url: https://codereview.chromium.org/2853113005
Cr-Commit-Position: refs/heads/master@{#469058}
CWE ID: CWE-17 | bool ScreenLayoutObserver::GetDisplayMessageForNotification(
const ScreenLayoutObserver::DisplayInfoMap& old_info,
base::string16* out_message,
base::string16* out_additional_message) {
if (old_display_mode_ != current_display_mode_) {
if (current_display_mode_ == DisplayMode::MIRRORING) {
*out_message = GetEnterMirrorModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::MIRRORING &&
GetExitMirrorModeMessage(out_message, out_additional_message)) {
return true;
}
if (current_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetEnterUnifiedModeMessage();
return true;
}
if (old_display_mode_ == DisplayMode::UNIFIED) {
*out_message = GetExitUnifiedModeMessage();
return true;
}
if (current_display_mode_ == DisplayMode::DOCKED ||
old_display_mode_ == DisplayMode::DOCKED) {
return false;
}
}
if (display_info_.size() < old_info.size()) {
for (const auto& iter : old_info) {
if (display_info_.count(iter.first))
continue;
*out_message =
GetDisplayRemovedMessage(iter.second, out_additional_message);
return true;
}
} else if (display_info_.size() > old_info.size()) {
for (const auto& iter : display_info_) {
if (old_info.count(iter.first))
continue;
*out_message = GetDisplayAddedMessage(iter.first, out_additional_message);
return true;
}
}
for (const auto& iter : display_info_) {
DisplayInfoMap::const_iterator old_iter = old_info.find(iter.first);
if (old_iter == old_info.end()) {
NOTREACHED() << "A display mode transition that should have been handled"
"earlier.";
return false;
}
if (iter.second.configured_ui_scale() !=
old_iter->second.configured_ui_scale()) {
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_RESOLUTION_CHANGED,
GetDisplayName(iter.first), GetDisplaySize(iter.first));
return true;
}
// We don't show rotation change notification when the rotation source is
// the accelerometer.
if (iter.second.active_rotation_source() !=
display::Display::ROTATION_SOURCE_ACCELEROMETER &&
iter.second.GetActiveRotation() !=
old_iter->second.GetActiveRotation()) {
int rotation_text_id = 0;
switch (iter.second.GetActiveRotation()) {
case display::Display::ROTATE_0:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_STANDARD_ORIENTATION;
break;
case display::Display::ROTATE_90:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_90;
break;
case display::Display::ROTATE_180:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_180;
break;
case display::Display::ROTATE_270:
rotation_text_id = IDS_ASH_STATUS_TRAY_DISPLAY_ORIENTATION_270;
break;
}
*out_additional_message = l10n_util::GetStringFUTF16(
IDS_ASH_STATUS_TRAY_DISPLAY_ROTATED, GetDisplayName(iter.first),
l10n_util::GetStringUTF16(rotation_text_id));
return true;
}
}
return false;
}
| 172,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token,
policy::BrowserPolicyConnector::TokenType token_type) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
NOTREACHED() << "Cloud policy subsystem not initialized.";
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentOtherFailed,
policy::kMetricEnrollmentSize);
if (is_showing_)
actor_->ShowFatalEnrollmentError();
return;
}
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
connector->SetDeviceCredentials(user_, token, token_type);
}
Commit Message: Reset the device policy machinery upon retrying enrollment.
BUG=chromium-os:18208
TEST=See bug description
Review URL: http://codereview.chromium.org/7676005
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97615 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void EnterpriseEnrollmentScreen::RegisterForDevicePolicy(
const std::string& token,
policy::BrowserPolicyConnector::TokenType token_type) {
policy::BrowserPolicyConnector* connector =
g_browser_process->browser_policy_connector();
if (!connector->device_cloud_policy_subsystem()) {
NOTREACHED() << "Cloud policy subsystem not initialized.";
UMA_HISTOGRAM_ENUMERATION(policy::kMetricEnrollment,
policy::kMetricEnrollmentOtherFailed,
policy::kMetricEnrollmentSize);
if (is_showing_)
actor_->ShowFatalEnrollmentError();
return;
}
connector->ScheduleServiceInitialization(0);
registrar_.reset(new policy::CloudPolicySubsystem::ObserverRegistrar(
connector->device_cloud_policy_subsystem(), this));
connector->RegisterForDevicePolicy(user_, token, token_type);
}
| 170,278 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
Commit Message: fixed out of bounds writes
Thanks to Eric Sesterhenn from X41 D-SEC GmbH
for reporting the problems.
CWE ID: CWE-415 | static int sc_pkcs15emu_sc_hsm_init (sc_pkcs15_card_t * p15card)
{
sc_card_t *card = p15card->card;
sc_hsm_private_data_t *priv = (sc_hsm_private_data_t *) card->drv_data;
sc_file_t *file = NULL;
sc_path_t path;
u8 filelist[MAX_EXT_APDU_LENGTH];
int filelistlength;
int r, i;
sc_cvc_t devcert;
struct sc_app_info *appinfo;
struct sc_pkcs15_auth_info pin_info;
struct sc_pkcs15_object pin_obj;
struct sc_pin_cmd_data pindata;
u8 efbin[1024];
u8 *ptr;
size_t len;
LOG_FUNC_CALLED(card->ctx);
appinfo = calloc(1, sizeof(struct sc_app_info));
if (appinfo == NULL) {
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->aid = sc_hsm_aid;
appinfo->ddo.aid = sc_hsm_aid;
p15card->app = appinfo;
sc_path_set(&path, SC_PATH_TYPE_DF_NAME, sc_hsm_aid.value, sc_hsm_aid.len, 0, 0);
r = sc_select_file(card, &path, &file);
LOG_TEST_RET(card->ctx, r, "Could not select SmartCard-HSM application");
p15card->card->version.hw_major = 24; /* JCOP 2.4.1r3 */
p15card->card->version.hw_minor = 13;
if (file && file->prop_attr && file->prop_attr_len >= 2) {
p15card->card->version.fw_major = file->prop_attr[file->prop_attr_len - 2];
p15card->card->version.fw_minor = file->prop_attr[file->prop_attr_len - 1];
}
sc_file_free(file);
/* Read device certificate to determine serial number */
if (priv->EF_C_DevAut && priv->EF_C_DevAut_len) {
ptr = priv->EF_C_DevAut;
len = priv->EF_C_DevAut_len;
} else {
len = sizeof efbin;
r = read_file(p15card, (u8 *) "\x2F\x02", efbin, &len, 1);
LOG_TEST_RET(card->ctx, r, "Skipping optional EF.C_DevAut");
if (len > 0) {
/* save EF_C_DevAut for further use */
ptr = realloc(priv->EF_C_DevAut, len);
if (ptr) {
memcpy(ptr, efbin, len);
priv->EF_C_DevAut = ptr;
priv->EF_C_DevAut_len = len;
}
}
ptr = efbin;
}
memset(&devcert, 0 ,sizeof(devcert));
r = sc_pkcs15emu_sc_hsm_decode_cvc(p15card, (const u8 **)&ptr, &len, &devcert);
LOG_TEST_RET(card->ctx, r, "Could not decode EF.C_DevAut");
sc_pkcs15emu_sc_hsm_read_tokeninfo(p15card);
if (p15card->tokeninfo->label == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->label = strdup("GoID");
} else {
p15card->tokeninfo->label = strdup("SmartCard-HSM");
}
if (p15card->tokeninfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
if ((p15card->tokeninfo->manufacturer_id != NULL) && !strcmp("(unknown)", p15card->tokeninfo->manufacturer_id)) {
free(p15card->tokeninfo->manufacturer_id);
p15card->tokeninfo->manufacturer_id = NULL;
}
if (p15card->tokeninfo->manufacturer_id == NULL) {
if (p15card->card->type == SC_CARD_TYPE_SC_HSM_GOID
|| p15card->card->type == SC_CARD_TYPE_SC_HSM_SOC) {
p15card->tokeninfo->manufacturer_id = strdup("Bundesdruckerei GmbH");
} else {
p15card->tokeninfo->manufacturer_id = strdup("www.CardContact.de");
}
if (p15card->tokeninfo->manufacturer_id == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
}
appinfo->label = strdup(p15card->tokeninfo->label);
if (appinfo->label == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
len = strnlen(devcert.chr, sizeof devcert.chr); /* Strip last 5 digit sequence number from CHR */
assert(len >= 8);
len -= 5;
p15card->tokeninfo->serial_number = calloc(len + 1, 1);
if (p15card->tokeninfo->serial_number == NULL)
LOG_FUNC_RETURN(card->ctx, SC_ERROR_OUT_OF_MEMORY);
memcpy(p15card->tokeninfo->serial_number, devcert.chr, len);
*(p15card->tokeninfo->serial_number + len) = 0;
sc_hsm_set_serialnr(card, p15card->tokeninfo->serial_number);
sc_pkcs15emu_sc_hsm_free_cvc(&devcert);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 1;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x81;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_EXCHANGE_REF_DATA;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_ASCII_NUMERIC;
pin_info.attrs.pin.min_length = 6;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 15;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 3;
pin_info.max_tries = 3;
pin_obj.auth_id.len = 1;
pin_obj.auth_id.value[0] = 2;
strlcpy(pin_obj.label, "UserPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE|SC_PKCS15_CO_FLAG_MODIFIABLE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
memset(&pin_info, 0, sizeof(pin_info));
memset(&pin_obj, 0, sizeof(pin_obj));
pin_info.auth_id.len = 1;
pin_info.auth_id.value[0] = 2;
pin_info.path.aid = sc_hsm_aid;
pin_info.auth_type = SC_PKCS15_PIN_AUTH_TYPE_PIN;
pin_info.attrs.pin.reference = 0x88;
pin_info.attrs.pin.flags = SC_PKCS15_PIN_FLAG_LOCAL|SC_PKCS15_PIN_FLAG_INITIALIZED|SC_PKCS15_PIN_FLAG_UNBLOCK_DISABLED|SC_PKCS15_PIN_FLAG_SO_PIN;
pin_info.attrs.pin.type = SC_PKCS15_PIN_TYPE_BCD;
pin_info.attrs.pin.min_length = 16;
pin_info.attrs.pin.stored_length = 0;
pin_info.attrs.pin.max_length = 16;
pin_info.attrs.pin.pad_char = '\0';
pin_info.tries_left = 15;
pin_info.max_tries = 15;
strlcpy(pin_obj.label, "SOPIN", sizeof(pin_obj.label));
pin_obj.flags = SC_PKCS15_CO_FLAG_PRIVATE;
r = sc_pkcs15emu_add_pin_obj(p15card, &pin_obj, &pin_info);
if (r < 0)
LOG_FUNC_RETURN(card->ctx, r);
if (card->type == SC_CARD_TYPE_SC_HSM_SOC
|| card->type == SC_CARD_TYPE_SC_HSM_GOID) {
/* SC-HSM of this type always has a PIN-Pad */
r = SC_SUCCESS;
} else {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x85;
r = sc_pin_cmd(card, &pindata, NULL);
}
if (r == SC_ERROR_DATA_OBJECT_NOT_FOUND) {
memset(&pindata, 0, sizeof(pindata));
pindata.cmd = SC_PIN_CMD_GET_INFO;
pindata.pin_type = SC_AC_CHV;
pindata.pin_reference = 0x86;
r = sc_pin_cmd(card, &pindata, NULL);
}
if ((r != SC_ERROR_DATA_OBJECT_NOT_FOUND) && (r != SC_ERROR_INCORRECT_PARAMETERS))
card->caps |= SC_CARD_CAP_PROTECTED_AUTHENTICATION_PATH;
filelistlength = sc_list_files(card, filelist, sizeof(filelist));
LOG_TEST_RET(card->ctx, filelistlength, "Could not enumerate file and key identifier");
for (i = 0; i < filelistlength; i += 2) {
switch(filelist[i]) {
case KEY_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_prkd(p15card, filelist[i + 1]);
break;
case DCOD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_dcod(p15card, filelist[i + 1]);
break;
case CD_PREFIX:
r = sc_pkcs15emu_sc_hsm_add_cd(p15card, filelist[i + 1]);
break;
}
if (r != SC_SUCCESS) {
sc_log(card->ctx, "Error %d adding elements to framework", r);
}
}
LOG_FUNC_RETURN(card->ctx, SC_SUCCESS);
}
| 169,078 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void StopInputMethodDaemon() {
if (!initialized_successfully_)
return;
should_launch_ime_ = false;
if (ibus_daemon_process_handle_ != base::kNullProcessHandle) {
const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_);
if (!chromeos::StopInputMethodProcess(input_method_status_connection_)) {
LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to "
<< "PID " << pid;
base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */);
}
VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated";
ibus_daemon_process_handle_ = base::kNullProcessHandle;
}
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void StopInputMethodDaemon() {
if (!initialized_successfully_)
return;
should_launch_ime_ = false;
if (ibus_daemon_process_handle_ != base::kNullProcessHandle) {
const base::ProcessId pid = base::GetProcId(ibus_daemon_process_handle_);
if (!ibus_controller_->StopInputMethodProcess()) {
LOG(ERROR) << "StopInputMethodProcess IPC failed. Sending SIGTERM to "
<< "PID " << pid;
base::KillProcess(ibus_daemon_process_handle_, -1, false /* wait */);
}
VLOG(1) << "ibus-daemon (PID=" << pid << ") is terminated";
ibus_daemon_process_handle_ = base::kNullProcessHandle;
}
}
| 170,508 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr)
{
uint32 i;
float xres = 0.0, yres = 0.0;
uint16 nstrips = 0, ntiles = 0, planar = 0;
uint16 bps = 0, spp = 0, res_unit = 0;
uint16 orientation = 0;
uint16 input_compression = 0, input_photometric = 0;
uint16 subsampling_horiz, subsampling_vert;
uint32 width = 0, length = 0;
uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0;
uint32 tw = 0, tl = 0; /* Tile width and length */
uint32 tile_rowsize = 0;
unsigned char *read_buff = NULL;
unsigned char *new_buff = NULL;
int readunit = 0;
static uint32 prev_readsize = 0;
TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
TIFFError("loadImage","Image lacks Photometric interpreation tag");
if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
TIFFError("loadimage","Image lacks image width tag");
if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
TIFFError("loadimage","Image lacks image length tag");
TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
res_unit = RESUNIT_INCH;
if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
input_compression = COMPRESSION_NONE;
#ifdef DEBUG2
char compressionid[16];
switch (input_compression)
{
case COMPRESSION_NONE: /* 1 dump mode */
strcpy (compressionid, "None/dump");
break;
case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
strcpy (compressionid, "Huffman RLE");
break;
case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
strcpy (compressionid, "Group3 Fax");
break;
case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
strcpy (compressionid, "Group4 Fax");
break;
case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
strcpy (compressionid, "LZW");
break;
case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
strcpy (compressionid, "Old Jpeg");
break;
case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
strcpy (compressionid, "New Jpeg");
break;
case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
strcpy (compressionid, "Next RLE");
break;
case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
strcpy (compressionid, "CITTRLEW");
break;
case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
strcpy (compressionid, "Mac Packbits");
break;
case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
strcpy (compressionid, "Thunderscan");
break;
case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
strcpy (compressionid, "IT8 padded");
break;
case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
strcpy (compressionid, "IT8 RLE");
break;
case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
strcpy (compressionid, "IT8 mono");
break;
case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
strcpy (compressionid, "IT8 lineart");
break;
case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
strcpy (compressionid, "Pixar 10 bit");
break;
case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
strcpy (compressionid, "Pixar 11bit");
break;
case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
strcpy (compressionid, "Deflate");
break;
case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
strcpy (compressionid, "Adobe deflate");
break;
default:
strcpy (compressionid, "None/unknown");
break;
}
TIFFError("loadImage", "Input compression %s", compressionid);
#endif
scanlinesize = TIFFScanlineSize(in);
image->bps = bps;
image->spp = spp;
image->planar = planar;
image->width = width;
image->length = length;
image->xres = xres;
image->yres = yres;
image->res_unit = res_unit;
image->compression = input_compression;
image->photometric = input_photometric;
#ifdef DEBUG2
char photometricid[12];
switch (input_photometric)
{
case PHOTOMETRIC_MINISWHITE:
strcpy (photometricid, "MinIsWhite");
break;
case PHOTOMETRIC_MINISBLACK:
strcpy (photometricid, "MinIsBlack");
break;
case PHOTOMETRIC_RGB:
strcpy (photometricid, "RGB");
break;
case PHOTOMETRIC_PALETTE:
strcpy (photometricid, "Palette");
break;
case PHOTOMETRIC_MASK:
strcpy (photometricid, "Mask");
break;
case PHOTOMETRIC_SEPARATED:
strcpy (photometricid, "Separated");
break;
case PHOTOMETRIC_YCBCR:
strcpy (photometricid, "YCBCR");
break;
case PHOTOMETRIC_CIELAB:
strcpy (photometricid, "CIELab");
break;
case PHOTOMETRIC_ICCLAB:
strcpy (photometricid, "ICCLab");
break;
case PHOTOMETRIC_ITULAB:
strcpy (photometricid, "ITULab");
break;
case PHOTOMETRIC_LOGL:
strcpy (photometricid, "LogL");
break;
case PHOTOMETRIC_LOGLUV:
strcpy (photometricid, "LOGLuv");
break;
default:
strcpy (photometricid, "Unknown");
break;
}
TIFFError("loadImage", "Input photometric interpretation %s", photometricid);
#endif
image->orientation = orientation;
switch (orientation)
{
case 0:
case ORIENTATION_TOPLEFT:
image->adjustments = 0;
break;
case ORIENTATION_TOPRIGHT:
image->adjustments = MIRROR_HORIZ;
break;
case ORIENTATION_BOTRIGHT:
image->adjustments = ROTATECW_180;
break;
case ORIENTATION_BOTLEFT:
image->adjustments = MIRROR_VERT;
break;
case ORIENTATION_LEFTTOP:
image->adjustments = MIRROR_VERT | ROTATECW_90;
break;
case ORIENTATION_RIGHTTOP:
image->adjustments = ROTATECW_90;
break;
case ORIENTATION_RIGHTBOT:
image->adjustments = MIRROR_VERT | ROTATECW_270;
break;
case ORIENTATION_LEFTBOT:
image->adjustments = ROTATECW_270;
break;
default:
image->adjustments = 0;
image->orientation = ORIENTATION_TOPLEFT;
}
if ((bps == 0) || (spp == 0))
{
TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)",
spp, bps);
return (-1);
}
if (TIFFIsTiled(in))
{
readunit = TILE;
tlsize = TIFFTileSize(in);
ntiles = TIFFNumberOfTiles(in);
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
tile_rowsize = TIFFTileRowSize(in);
if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
{
TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero.");
exit(-1);
}
buffsize = tlsize * ntiles;
if (tlsize != (buffsize / ntiles))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
if (buffsize < (uint32)(ntiles * tl * tile_rowsize))
{
buffsize = ntiles * tl * tile_rowsize;
if (ntiles != (buffsize / tl / tile_rowsize))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
#ifdef DEBUG2
TIFFError("loadImage",
"Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu",
tlsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Tilesize: %u, Number of Tiles: %u, Tile row size: %u",
tlsize, ntiles, tile_rowsize);
}
else
{
uint32 buffsize_check;
readunit = STRIP;
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
stsize = TIFFStripSize(in);
nstrips = TIFFNumberOfStrips(in);
if (nstrips == 0 || stsize == 0)
{
TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero.");
exit(-1);
}
buffsize = stsize * nstrips;
if (stsize != (buffsize / nstrips))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
buffsize_check = ((length * width * spp * bps) + 7);
if (length != ((buffsize_check - 7) / width / spp / bps))
{
TIFFError("loadImage", "Integer overflow detected.");
exit(-1);
}
if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8))
{
buffsize = ((length * width * spp * bps) + 7) / 8;
#ifdef DEBUG2
TIFFError("loadImage",
"Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu",
stsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u",
stsize, nstrips, rowsperstrip, scanlinesize);
}
if (input_compression == COMPRESSION_JPEG)
{ /* Force conversion to RGB */
jpegcolormode = JPEGCOLORMODE_RGB;
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
/* The clause up to the read statement is taken from Tom Lane's tiffcp patch */
else
{ /* Otherwise, can't handle subsampled input */
if (input_photometric == PHOTOMETRIC_YCBCR)
{
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsampling_horiz, &subsampling_vert);
if (subsampling_horiz != 1 || subsampling_vert != 1)
{
TIFFError("loadImage",
"Can't copy/convert subsampled image with subsampling %d horiz %d vert",
subsampling_horiz, subsampling_vert);
return (-1);
}
}
}
read_buff = *read_ptr;
/* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
/* outside buffer */
if (!read_buff)
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
else
{
if (prev_readsize < buffsize)
{
new_buff = _TIFFrealloc(read_buff, buffsize+3);
if (!new_buff)
{
free (read_buff);
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
read_buff = new_buff;
}
}
if (!read_buff)
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff[buffsize] = 0;
read_buff[buffsize+1] = 0;
read_buff[buffsize+2] = 0;
prev_readsize = buffsize;
*read_ptr = read_buff;
/* N.B. The read functions used copy separate plane data into a buffer as interleaved
* samples rather than separate planes so the same logic works to extract regions
* regardless of the way the data are organized in the input file.
*/
switch (readunit) {
case STRIP:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigStripsIntoBuffer(in, read_buff)))
{
TIFFError("loadImage", "Unable to read contiguous strips into buffer");
return (-1);
}
}
else
{
if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump)))
{
TIFFError("loadImage", "Unable to read separate strips into buffer");
return (-1);
}
}
break;
case TILE:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read contiguous tiles into buffer");
return (-1);
}
}
else
{
if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read separate tiles into buffer");
return (-1);
}
}
break;
default: TIFFError("loadImage", "Unsupported image file format");
return (-1);
break;
}
if ((dump->infile != NULL) && (dump->level == 2))
{
dump_info (dump->infile, dump->format, "loadImage",
"Image width %d, length %d, Raw image data, %4d bytes",
width, length, buffsize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d", bps, spp);
for (i = 0; i < length; i++)
dump_buffer(dump->infile, dump->format, 1, scanlinesize,
i, read_buff + (i * scanlinesize));
}
return (0);
} /* end loadImage */
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787 | loadImage(TIFF* in, struct image_data *image, struct dump_opts *dump, unsigned char **read_ptr)
{
uint32 i;
float xres = 0.0, yres = 0.0;
uint32 nstrips = 0, ntiles = 0;
uint16 planar = 0;
uint16 bps = 0, spp = 0, res_unit = 0;
uint16 orientation = 0;
uint16 input_compression = 0, input_photometric = 0;
uint16 subsampling_horiz, subsampling_vert;
uint32 width = 0, length = 0;
uint32 stsize = 0, tlsize = 0, buffsize = 0, scanlinesize = 0;
uint32 tw = 0, tl = 0; /* Tile width and length */
uint32 tile_rowsize = 0;
unsigned char *read_buff = NULL;
unsigned char *new_buff = NULL;
int readunit = 0;
static uint32 prev_readsize = 0;
TIFFGetFieldDefaulted(in, TIFFTAG_BITSPERSAMPLE, &bps);
TIFFGetFieldDefaulted(in, TIFFTAG_SAMPLESPERPIXEL, &spp);
TIFFGetFieldDefaulted(in, TIFFTAG_PLANARCONFIG, &planar);
TIFFGetFieldDefaulted(in, TIFFTAG_ORIENTATION, &orientation);
if (! TIFFGetFieldDefaulted(in, TIFFTAG_PHOTOMETRIC, &input_photometric))
TIFFError("loadImage","Image lacks Photometric interpreation tag");
if (! TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &width))
TIFFError("loadimage","Image lacks image width tag");
if(! TIFFGetField(in, TIFFTAG_IMAGELENGTH, &length))
TIFFError("loadimage","Image lacks image length tag");
TIFFGetFieldDefaulted(in, TIFFTAG_XRESOLUTION, &xres);
TIFFGetFieldDefaulted(in, TIFFTAG_YRESOLUTION, &yres);
if (!TIFFGetFieldDefaulted(in, TIFFTAG_RESOLUTIONUNIT, &res_unit))
res_unit = RESUNIT_INCH;
if (!TIFFGetField(in, TIFFTAG_COMPRESSION, &input_compression))
input_compression = COMPRESSION_NONE;
#ifdef DEBUG2
char compressionid[16];
switch (input_compression)
{
case COMPRESSION_NONE: /* 1 dump mode */
strcpy (compressionid, "None/dump");
break;
case COMPRESSION_CCITTRLE: /* 2 CCITT modified Huffman RLE */
strcpy (compressionid, "Huffman RLE");
break;
case COMPRESSION_CCITTFAX3: /* 3 CCITT Group 3 fax encoding */
strcpy (compressionid, "Group3 Fax");
break;
case COMPRESSION_CCITTFAX4: /* 4 CCITT Group 4 fax encoding */
strcpy (compressionid, "Group4 Fax");
break;
case COMPRESSION_LZW: /* 5 Lempel-Ziv & Welch */
strcpy (compressionid, "LZW");
break;
case COMPRESSION_OJPEG: /* 6 !6.0 JPEG */
strcpy (compressionid, "Old Jpeg");
break;
case COMPRESSION_JPEG: /* 7 %JPEG DCT compression */
strcpy (compressionid, "New Jpeg");
break;
case COMPRESSION_NEXT: /* 32766 NeXT 2-bit RLE */
strcpy (compressionid, "Next RLE");
break;
case COMPRESSION_CCITTRLEW: /* 32771 #1 w/ word alignment */
strcpy (compressionid, "CITTRLEW");
break;
case COMPRESSION_PACKBITS: /* 32773 Macintosh RLE */
strcpy (compressionid, "Mac Packbits");
break;
case COMPRESSION_THUNDERSCAN: /* 32809 ThunderScan RLE */
strcpy (compressionid, "Thunderscan");
break;
case COMPRESSION_IT8CTPAD: /* 32895 IT8 CT w/padding */
strcpy (compressionid, "IT8 padded");
break;
case COMPRESSION_IT8LW: /* 32896 IT8 Linework RLE */
strcpy (compressionid, "IT8 RLE");
break;
case COMPRESSION_IT8MP: /* 32897 IT8 Monochrome picture */
strcpy (compressionid, "IT8 mono");
break;
case COMPRESSION_IT8BL: /* 32898 IT8 Binary line art */
strcpy (compressionid, "IT8 lineart");
break;
case COMPRESSION_PIXARFILM: /* 32908 Pixar companded 10bit LZW */
strcpy (compressionid, "Pixar 10 bit");
break;
case COMPRESSION_PIXARLOG: /* 32909 Pixar companded 11bit ZIP */
strcpy (compressionid, "Pixar 11bit");
break;
case COMPRESSION_DEFLATE: /* 32946 Deflate compression */
strcpy (compressionid, "Deflate");
break;
case COMPRESSION_ADOBE_DEFLATE: /* 8 Deflate compression */
strcpy (compressionid, "Adobe deflate");
break;
default:
strcpy (compressionid, "None/unknown");
break;
}
TIFFError("loadImage", "Input compression %s", compressionid);
#endif
scanlinesize = TIFFScanlineSize(in);
image->bps = bps;
image->spp = spp;
image->planar = planar;
image->width = width;
image->length = length;
image->xres = xres;
image->yres = yres;
image->res_unit = res_unit;
image->compression = input_compression;
image->photometric = input_photometric;
#ifdef DEBUG2
char photometricid[12];
switch (input_photometric)
{
case PHOTOMETRIC_MINISWHITE:
strcpy (photometricid, "MinIsWhite");
break;
case PHOTOMETRIC_MINISBLACK:
strcpy (photometricid, "MinIsBlack");
break;
case PHOTOMETRIC_RGB:
strcpy (photometricid, "RGB");
break;
case PHOTOMETRIC_PALETTE:
strcpy (photometricid, "Palette");
break;
case PHOTOMETRIC_MASK:
strcpy (photometricid, "Mask");
break;
case PHOTOMETRIC_SEPARATED:
strcpy (photometricid, "Separated");
break;
case PHOTOMETRIC_YCBCR:
strcpy (photometricid, "YCBCR");
break;
case PHOTOMETRIC_CIELAB:
strcpy (photometricid, "CIELab");
break;
case PHOTOMETRIC_ICCLAB:
strcpy (photometricid, "ICCLab");
break;
case PHOTOMETRIC_ITULAB:
strcpy (photometricid, "ITULab");
break;
case PHOTOMETRIC_LOGL:
strcpy (photometricid, "LogL");
break;
case PHOTOMETRIC_LOGLUV:
strcpy (photometricid, "LOGLuv");
break;
default:
strcpy (photometricid, "Unknown");
break;
}
TIFFError("loadImage", "Input photometric interpretation %s", photometricid);
#endif
image->orientation = orientation;
switch (orientation)
{
case 0:
case ORIENTATION_TOPLEFT:
image->adjustments = 0;
break;
case ORIENTATION_TOPRIGHT:
image->adjustments = MIRROR_HORIZ;
break;
case ORIENTATION_BOTRIGHT:
image->adjustments = ROTATECW_180;
break;
case ORIENTATION_BOTLEFT:
image->adjustments = MIRROR_VERT;
break;
case ORIENTATION_LEFTTOP:
image->adjustments = MIRROR_VERT | ROTATECW_90;
break;
case ORIENTATION_RIGHTTOP:
image->adjustments = ROTATECW_90;
break;
case ORIENTATION_RIGHTBOT:
image->adjustments = MIRROR_VERT | ROTATECW_270;
break;
case ORIENTATION_LEFTBOT:
image->adjustments = ROTATECW_270;
break;
default:
image->adjustments = 0;
image->orientation = ORIENTATION_TOPLEFT;
}
if ((bps == 0) || (spp == 0))
{
TIFFError("loadImage", "Invalid samples per pixel (%d) or bits per sample (%d)",
spp, bps);
return (-1);
}
if (TIFFIsTiled(in))
{
readunit = TILE;
tlsize = TIFFTileSize(in);
ntiles = TIFFNumberOfTiles(in);
TIFFGetField(in, TIFFTAG_TILEWIDTH, &tw);
TIFFGetField(in, TIFFTAG_TILELENGTH, &tl);
tile_rowsize = TIFFTileRowSize(in);
if (ntiles == 0 || tlsize == 0 || tile_rowsize == 0)
{
TIFFError("loadImage", "File appears to be tiled, but the number of tiles, tile size, or tile rowsize is zero.");
exit(-1);
}
buffsize = tlsize * ntiles;
if (tlsize != (buffsize / ntiles))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
if (buffsize < (uint32)(ntiles * tl * tile_rowsize))
{
buffsize = ntiles * tl * tile_rowsize;
if (ntiles != (buffsize / tl / tile_rowsize))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
#ifdef DEBUG2
TIFFError("loadImage",
"Tilesize %u is too small, using ntiles * tilelength * tilerowsize %lu",
tlsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Tilesize: %u, Number of Tiles: %u, Tile row size: %u",
tlsize, ntiles, tile_rowsize);
}
else
{
uint32 buffsize_check;
readunit = STRIP;
TIFFGetFieldDefaulted(in, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
stsize = TIFFStripSize(in);
nstrips = TIFFNumberOfStrips(in);
if (nstrips == 0 || stsize == 0)
{
TIFFError("loadImage", "File appears to be striped, but the number of stipes or stripe size is zero.");
exit(-1);
}
buffsize = stsize * nstrips;
if (stsize != (buffsize / nstrips))
{
TIFFError("loadImage", "Integer overflow when calculating buffer size");
exit(-1);
}
buffsize_check = ((length * width * spp * bps) + 7);
if (length != ((buffsize_check - 7) / width / spp / bps))
{
TIFFError("loadImage", "Integer overflow detected.");
exit(-1);
}
if (buffsize < (uint32) (((length * width * spp * bps) + 7) / 8))
{
buffsize = ((length * width * spp * bps) + 7) / 8;
#ifdef DEBUG2
TIFFError("loadImage",
"Stripsize %u is too small, using imagelength * width * spp * bps / 8 = %lu",
stsize, (unsigned long)buffsize);
#endif
}
if (dump->infile != NULL)
dump_info (dump->infile, dump->format, "",
"Stripsize: %u, Number of Strips: %u, Rows per Strip: %u, Scanline size: %u",
stsize, nstrips, rowsperstrip, scanlinesize);
}
if (input_compression == COMPRESSION_JPEG)
{ /* Force conversion to RGB */
jpegcolormode = JPEGCOLORMODE_RGB;
TIFFSetField(in, TIFFTAG_JPEGCOLORMODE, JPEGCOLORMODE_RGB);
}
/* The clause up to the read statement is taken from Tom Lane's tiffcp patch */
else
{ /* Otherwise, can't handle subsampled input */
if (input_photometric == PHOTOMETRIC_YCBCR)
{
TIFFGetFieldDefaulted(in, TIFFTAG_YCBCRSUBSAMPLING,
&subsampling_horiz, &subsampling_vert);
if (subsampling_horiz != 1 || subsampling_vert != 1)
{
TIFFError("loadImage",
"Can't copy/convert subsampled image with subsampling %d horiz %d vert",
subsampling_horiz, subsampling_vert);
return (-1);
}
}
}
read_buff = *read_ptr;
/* +3 : add a few guard bytes since reverseSamples16bits() can read a bit */
/* outside buffer */
if (!read_buff)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
{
if (prev_readsize < buffsize)
{
if( buffsize > 0xFFFFFFFFU - 3 )
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
new_buff = _TIFFrealloc(read_buff, buffsize+3);
if (!new_buff)
{
free (read_buff);
read_buff = (unsigned char *)_TIFFmalloc(buffsize+3);
}
else
read_buff = new_buff;
}
}
if (!read_buff)
{
TIFFError("loadImage", "Unable to allocate/reallocate read buffer");
return (-1);
}
read_buff[buffsize] = 0;
read_buff[buffsize+1] = 0;
read_buff[buffsize+2] = 0;
prev_readsize = buffsize;
*read_ptr = read_buff;
/* N.B. The read functions used copy separate plane data into a buffer as interleaved
* samples rather than separate planes so the same logic works to extract regions
* regardless of the way the data are organized in the input file.
*/
switch (readunit) {
case STRIP:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigStripsIntoBuffer(in, read_buff)))
{
TIFFError("loadImage", "Unable to read contiguous strips into buffer");
return (-1);
}
}
else
{
if (!(readSeparateStripsIntoBuffer(in, read_buff, length, width, spp, dump)))
{
TIFFError("loadImage", "Unable to read separate strips into buffer");
return (-1);
}
}
break;
case TILE:
if (planar == PLANARCONFIG_CONTIG)
{
if (!(readContigTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read contiguous tiles into buffer");
return (-1);
}
}
else
{
if (!(readSeparateTilesIntoBuffer(in, read_buff, length, width, tw, tl, spp, bps)))
{
TIFFError("loadImage", "Unable to read separate tiles into buffer");
return (-1);
}
}
break;
default: TIFFError("loadImage", "Unsupported image file format");
return (-1);
break;
}
if ((dump->infile != NULL) && (dump->level == 2))
{
dump_info (dump->infile, dump->format, "loadImage",
"Image width %d, length %d, Raw image data, %4d bytes",
width, length, buffsize);
dump_info (dump->infile, dump->format, "",
"Bits per sample %d, Samples per pixel %d", bps, spp);
for (i = 0; i < length; i++)
dump_buffer(dump->infile, dump->format, 1, scanlinesize,
i, read_buff + (i * scanlinesize));
}
return (0);
} /* end loadImage */
| 166,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int em_loop(struct x86_emulate_ctxt *ctxt)
{
register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -1);
if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&
(ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
jmp_rel(ctxt, ctxt->src.val);
return X86EMUL_CONTINUE;
}
Commit Message: KVM: x86: Emulator fixes for eip canonical checks on near branches
Before changing rip (during jmp, call, ret, etc.) the target should be asserted
to be canonical one, as real CPUs do. During sysret, both target rsp and rip
should be canonical. If any of these values is noncanonical, a #GP exception
should occur. The exception to this rule are syscall and sysenter instructions
in which the assigned rip is checked during the assignment to the relevant
MSRs.
This patch fixes the emulator to behave as real CPUs do for near branches.
Far branches are handled by the next patch.
This fixes CVE-2014-3647.
Cc: [email protected]
Signed-off-by: Nadav Amit <[email protected]>
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-264 | static int em_loop(struct x86_emulate_ctxt *ctxt)
{
int rc = X86EMUL_CONTINUE;
register_address_increment(ctxt, reg_rmw(ctxt, VCPU_REGS_RCX), -1);
if ((address_mask(ctxt, reg_read(ctxt, VCPU_REGS_RCX)) != 0) &&
(ctxt->b == 0xe2 || test_cc(ctxt->b ^ 0x5, ctxt->eflags)))
rc = jmp_rel(ctxt, ctxt->src.val);
return rc;
}
| 169,912 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
SyncCredentials credentials;
credentials.email = "[email protected]";
credentials.sync_token = "sometoken";
sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
EXPECT_CALL(*sync_notifier_mock_, SetState(""));
EXPECT_CALL(*sync_notifier_mock_,
UpdateCredentials(credentials.email, credentials.sync_token));
EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
Times(AtLeast(1)).
WillRepeatedly(
Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
sync_manager_.AddObserver(&observer_);
EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
WillOnce(SaveArg<0>(&js_backend_));
EXPECT_FALSE(sync_notifier_observer_);
EXPECT_FALSE(js_backend_.IsInitialized());
sync_manager_.Init(temp_dir_.path(),
WeakHandle<JsEventHandler>(),
"bogus", 0, false,
base::MessageLoopProxy::current(),
new TestHttpPostProviderFactory(), this,
&extensions_activity_monitor_, this, "bogus",
credentials,
false /* enable_sync_tabs_for_other_clients */,
sync_notifier_mock_, "",
sync_api::SyncManager::TEST_IN_MEMORY,
&encryptor_,
&handler_,
NULL);
EXPECT_TRUE(sync_notifier_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(1, update_enabled_types_call_count_);
ModelSafeRoutingInfo routes;
GetModelSafeRoutingInfo(&routes);
for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
++i) {
type_roots_[i->first] = MakeServerNodeForType(
sync_manager_.GetUserShare(), i->first);
}
PumpLoop();
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | void SetUp() {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
SyncCredentials credentials;
credentials.email = "[email protected]";
credentials.sync_token = "sometoken";
sync_notifier_mock_ = new StrictMock<SyncNotifierMock>();
EXPECT_CALL(*sync_notifier_mock_, AddObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierAddObserver));
EXPECT_CALL(*sync_notifier_mock_, SetUniqueId(_));
EXPECT_CALL(*sync_notifier_mock_, SetState(""));
EXPECT_CALL(*sync_notifier_mock_,
UpdateCredentials(credentials.email, credentials.sync_token));
EXPECT_CALL(*sync_notifier_mock_, UpdateEnabledTypes(_)).
Times(AtLeast(1)).
WillRepeatedly(
Invoke(this, &SyncManagerTest::SyncNotifierUpdateEnabledTypes));
EXPECT_CALL(*sync_notifier_mock_, RemoveObserver(_)).
WillOnce(Invoke(this, &SyncManagerTest::SyncNotifierRemoveObserver));
sync_manager_.AddObserver(&observer_);
EXPECT_CALL(observer_, OnInitializationComplete(_, _)).
WillOnce(SaveArg<0>(&js_backend_));
EXPECT_FALSE(sync_notifier_observer_);
EXPECT_FALSE(js_backend_.IsInitialized());
sync_manager_.Init(temp_dir_.path(),
WeakHandle<JsEventHandler>(),
"bogus", 0, false,
base::MessageLoopProxy::current(),
new TestHttpPostProviderFactory(), this,
&extensions_activity_monitor_, this, "bogus",
credentials,
sync_notifier_mock_, "",
sync_api::SyncManager::TEST_IN_MEMORY,
&encryptor_,
&handler_,
NULL);
EXPECT_TRUE(sync_notifier_observer_);
EXPECT_TRUE(js_backend_.IsInitialized());
EXPECT_EQ(1, update_enabled_types_call_count_);
ModelSafeRoutingInfo routes;
GetModelSafeRoutingInfo(&routes);
for (ModelSafeRoutingInfo::iterator i = routes.begin(); i != routes.end();
++i) {
type_roots_[i->first] = MakeServerNodeForType(
sync_manager_.GetUserShare(), i->first);
}
PumpLoop();
}
| 170,799 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_class_init (MyObjectClass *mobject_class)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (mobject_class);
gobject_class->finalize = my_object_finalize;
gobject_class->set_property = my_object_set_property;
gobject_class->get_property = my_object_get_property;
g_object_class_install_property (gobject_class,
PROP_THIS_IS_A_STRING,
g_param_spec_string ("this_is_a_string",
_("Sample string"),
_("Example of a string property"),
"default value",
G_PARAM_READWRITE));
signals[FROBNICATE] =
g_signal_new ("frobnicate",
G_OBJECT_CLASS_TYPE (mobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
0,
NULL, NULL,
g_cclosure_marshal_VOID__INT,
G_TYPE_NONE, 1, G_TYPE_INT);
signals[SIG0] =
g_signal_new ("sig0",
G_OBJECT_CLASS_TYPE (mobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
0,
NULL, NULL,
my_object_marshal_VOID__STRING_INT_STRING,
G_TYPE_NONE, 3, G_TYPE_STRING, G_TYPE_INT, G_TYPE_STRING);
signals[SIG1] =
g_signal_new ("sig1",
G_OBJECT_CLASS_TYPE (mobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
0,
NULL, NULL,
my_object_marshal_VOID__STRING_BOXED,
G_TYPE_NONE, 2, G_TYPE_STRING, G_TYPE_VALUE);
signals[SIG2] =
g_signal_new ("sig2",
G_OBJECT_CLASS_TYPE (mobject_class),
G_SIGNAL_RUN_LAST | G_SIGNAL_DETAILED,
0,
NULL, NULL,
g_cclosure_marshal_VOID__BOXED,
G_TYPE_NONE, 1, DBUS_TYPE_G_STRING_STRING_HASHTABLE);
}
Commit Message:
CWE ID: CWE-264 | my_object_class_init (MyObjectClass *mobject_class)
| 165,090 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int hashtable_do_rehash(hashtable_t *hashtable)
{
list_t *list, *next;
pair_t *pair;
size_t i, index, new_size;
jsonp_free(hashtable->buckets);
hashtable->num_buckets++;
new_size = num_buckets(hashtable);
hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t));
if(!hashtable->buckets)
return -1;
for(i = 0; i < num_buckets(hashtable); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
list = hashtable->list.next;
list_init(&hashtable->list);
for(; list != &hashtable->list; list = next) {
next = list->next;
pair = list_to_pair(list);
index = pair->hash % new_size;
insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list);
}
return 0;
}
Commit Message: CVE-2013-6401: Change hash function, randomize hashes
Thanks to Florian Weimer and Eric Sesterhenn for reporting, reviewing
and testing.
CWE ID: CWE-310 | static int hashtable_do_rehash(hashtable_t *hashtable)
{
list_t *list, *next;
pair_t *pair;
size_t i, index, new_size;
jsonp_free(hashtable->buckets);
hashtable->order++;
new_size = hashsize(hashtable->order);
hashtable->buckets = jsonp_malloc(new_size * sizeof(bucket_t));
if(!hashtable->buckets)
return -1;
for(i = 0; i < hashsize(hashtable->order); i++)
{
hashtable->buckets[i].first = hashtable->buckets[i].last =
&hashtable->list;
}
list = hashtable->list.next;
list_init(&hashtable->list);
for(; list != &hashtable->list; list = next) {
next = list->next;
pair = list_to_pair(list);
index = pair->hash % new_size;
insert_to_bucket(hashtable, &hashtable->buckets[index], &pair->list);
}
return 0;
}
| 166,529 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int __init pf_init(void)
{ /* preliminary initialisation */
struct pf_unit *pf;
int unit;
if (disable)
return -EINVAL;
pf_init_units();
if (pf_detect())
return -ENODEV;
pf_busy = 0;
if (register_blkdev(major, name)) {
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++)
put_disk(pf->disk);
return -EBUSY;
}
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
struct gendisk *disk = pf->disk;
if (!pf->present)
continue;
disk->private_data = pf;
add_disk(disk);
}
return 0;
}
Commit Message: paride/pf: Fix potential NULL pointer dereference
Syzkaller report this:
pf: pf version 1.04, major 47, cluster 64, nice 0
pf: No ATAPI disk detected
kasan: CONFIG_KASAN_INLINE enabled
kasan: GPF could be caused by NULL-ptr deref or user memory access
general protection fault: 0000 [#1] SMP KASAN PTI
CPU: 0 PID: 9887 Comm: syz-executor.0 Tainted: G C 5.1.0-rc3+ #8
Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014
RIP: 0010:pf_init+0x7af/0x1000 [pf]
Code: 46 77 d2 48 89 d8 48 c1 e8 03 80 3c 28 00 74 08 48 89 df e8 03 25 a6 d2 4c 8b 23 49 8d bc 24 80 05 00 00 48 89 f8 48 c1 e8 03 <80> 3c 28 00 74 05 e8 e6 24 a6 d2 49 8b bc 24 80 05 00 00 e8 79 34
RSP: 0018:ffff8881abcbf998 EFLAGS: 00010202
RAX: 00000000000000b0 RBX: ffffffffc1e4a8a8 RCX: ffffffffaec50788
RDX: 0000000000039b10 RSI: ffffc9000153c000 RDI: 0000000000000580
RBP: dffffc0000000000 R08: ffffed103ee44e59 R09: ffffed103ee44e59
R10: 0000000000000001 R11: ffffed103ee44e58 R12: 0000000000000000
R13: ffffffffc1e4b028 R14: 0000000000000000 R15: 0000000000000020
FS: 00007f1b78a91700(0000) GS:ffff8881f7200000(0000) knlGS:0000000000000000
CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: 00007f6d72b207f8 CR3: 00000001d5790004 CR4: 00000000007606f0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
? 0xffffffffc1e50000
do_one_initcall+0xbc/0x47d init/main.c:901
do_init_module+0x1b5/0x547 kernel/module.c:3456
load_module+0x6405/0x8c10 kernel/module.c:3804
__do_sys_finit_module+0x162/0x190 kernel/module.c:3898
do_syscall_64+0x9f/0x450 arch/x86/entry/common.c:290
entry_SYSCALL_64_after_hwframe+0x49/0xbe
RIP: 0033:0x462e99
Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48
RSP: 002b:00007f1b78a90c58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139
RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99
RDX: 0000000000000000 RSI: 0000000020000180 RDI: 0000000000000003
RBP: 00007f1b78a90c70 R08: 0000000000000000 R09: 0000000000000000
R10: 0000000000000000 R11: 0000000000000246 R12: 00007f1b78a916bc
R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004
Modules linked in: pf(+) paride gpio_tps65218 tps65218 i2c_cht_wc ati_remote dc395x act_meta_skbtcindex act_ife ife ecdh_generic rc_xbox_dvd sky81452_regulator v4l2_fwnode leds_blinkm snd_usb_hiface comedi(C) aes_ti slhc cfi_cmdset_0020 mtd cfi_util sx8654 mdio_gpio of_mdio fixed_phy mdio_bitbang libphy alcor_pci matrix_keymap hid_uclogic usbhid scsi_transport_fc videobuf2_v4l2 videobuf2_dma_sg snd_soc_pcm179x_spi snd_soc_pcm179x_codec i2c_demux_pinctrl mdev snd_indigodj isl6405 mii enc28j60 cmac adt7316_i2c(C) adt7316(C) fmc_trivial fmc nf_reject_ipv4 authenc rc_dtt200u rtc_ds1672 dvb_usb_dibusb_mc dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb dvb_core videobuf2_common videobuf2_vmalloc videobuf2_memops regulator_haptic adf7242 mac802154 ieee802154 s5h1409 da9034_ts snd_intel8x0m wmi cx24120 usbcore sdhci_cadence sdhci_pltfm sdhci mmc_core joydev i2c_algo_bit scsi_transport_iscsi iscsi_boot_sysfs ves1820 lockd grace nfs_acl auth_rpcgss sunrp
c
ip_vs snd_soc_adau7002 snd_cs4281 snd_rawmidi gameport snd_opl3_lib snd_seq_device snd_hwdep snd_ac97_codec ad7418 hid_primax hid snd_soc_cs4265 snd_soc_core snd_pcm_dmaengine snd_pcm snd_timer ac97_bus snd_compress snd soundcore ti_adc108s102 eeprom_93cx6 i2c_algo_pca mlxreg_hotplug st_pressure st_sensors industrialio_triggered_buffer kfifo_buf industrialio v4l2_common videodev media snd_soc_adau_utils rc_pinnacle_grey rc_core pps_gpio leds_lm3692x nandcore ledtrig_pattern iptable_security iptable_raw iptable_mangle iptable_nat nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun mousedev ppdev tpm kvm_intel kvm irqbypass crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel aesni_intel ide_pci_generic aes_x86_64 piix crypto_simd input_leds psmouse cryp
td
glue_helper ide_core intel_agp serio_raw intel_gtt agpgart ata_generic i2c_piix4 pata_acpi parport_pc parport rtc_cmos floppy sch_fq_codel ip_tables x_tables sha1_ssse3 sha1_generic ipv6 [last unloaded: paride]
Dumping ftrace buffer:
(ftrace buffer empty)
---[ end trace 7a818cf5f210d79e ]---
If alloc_disk fails in pf_init_units, pf->disk will be
NULL, however in pf_detect and pf_exit, it's not check
this before free.It may result a NULL pointer dereference.
Also when register_blkdev failed, blk_cleanup_queue() and
blk_mq_free_tag_set() should be called to free resources.
Reported-by: Hulk Robot <[email protected]>
Fixes: 6ce59025f118 ("paride/pf: cleanup queues when detection fails")
Signed-off-by: YueHaibing <[email protected]>
Signed-off-by: Jens Axboe <[email protected]>
CWE ID: CWE-476 | static int __init pf_init(void)
{ /* preliminary initialisation */
struct pf_unit *pf;
int unit;
if (disable)
return -EINVAL;
pf_init_units();
if (pf_detect())
return -ENODEV;
pf_busy = 0;
if (register_blkdev(major, name)) {
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
if (!pf->disk)
continue;
blk_cleanup_queue(pf->disk->queue);
blk_mq_free_tag_set(&pf->tag_set);
put_disk(pf->disk);
}
return -EBUSY;
}
for (pf = units, unit = 0; unit < PF_UNITS; pf++, unit++) {
struct gendisk *disk = pf->disk;
if (!pf->present)
continue;
disk->private_data = pf;
add_disk(disk);
}
return 0;
}
| 169,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)
{
struct mmu_gather tlb;
struct vm_area_struct *vma;
bool ret = true;
/*
* We have to make sure to not race with the victim exit path
* and cause premature new oom victim selection:
* __oom_reap_task_mm exit_mm
* mmget_not_zero
* mmput
* atomic_dec_and_test
* exit_oom_victim
* [...]
* out_of_memory
* select_bad_process
* # no TIF_MEMDIE task selects new victim
* unmap_page_range # frees some memory
*/
mutex_lock(&oom_lock);
if (!down_read_trylock(&mm->mmap_sem)) {
ret = false;
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
/*
* If the mm has notifiers then we would need to invalidate them around
* unmap_page_range and that is risky because notifiers can sleep and
* what they do is basically undeterministic. So let's have a short
* sleep to give the oom victim some more time.
* TODO: we really want to get rid of this ugly hack and make sure that
* notifiers cannot block for unbounded amount of time and add
* mmu_notifier_invalidate_range_{start,end} around unmap_page_range
*/
if (mm_has_notifiers(mm)) {
up_read(&mm->mmap_sem);
schedule_timeout_idle(HZ);
goto unlock_oom;
}
/*
* MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't
* work on the mm anymore. The check for MMF_OOM_SKIP must run
* under mmap_sem for reading because it serializes against the
* down_write();up_write() cycle in exit_mmap().
*/
if (test_bit(MMF_OOM_SKIP, &mm->flags)) {
up_read(&mm->mmap_sem);
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
trace_start_task_reaping(tsk->pid);
/*
* Tell all users of get_user/copy_from_user etc... that the content
* is no longer stable. No barriers really needed because unmapping
* should imply barriers already and the reader would hit a page fault
* if it stumbled over a reaped memory.
*/
set_bit(MMF_UNSTABLE, &mm->flags);
tlb_gather_mmu(&tlb, mm, 0, -1);
for (vma = mm->mmap ; vma; vma = vma->vm_next) {
if (!can_madv_dontneed_vma(vma))
continue;
/*
* Only anonymous pages have a good chance to be dropped
* without additional steps which we cannot afford as we
* are OOM already.
*
* We do not even care about fs backed pages because all
* which are reclaimable have already been reclaimed and
* we do not want to block exit_mmap by keeping mm ref
* count elevated without a good reason.
*/
if (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED))
unmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end,
NULL);
}
tlb_finish_mmu(&tlb, 0, -1);
pr_info("oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\n",
task_pid_nr(tsk), tsk->comm,
K(get_mm_counter(mm, MM_ANONPAGES)),
K(get_mm_counter(mm, MM_FILEPAGES)),
K(get_mm_counter(mm, MM_SHMEMPAGES)));
up_read(&mm->mmap_sem);
trace_finish_task_reaping(tsk->pid);
unlock_oom:
mutex_unlock(&oom_lock);
return ret;
}
Commit Message: mm, oom_reaper: gather each vma to prevent leaking TLB entry
tlb_gather_mmu(&tlb, mm, 0, -1) means gathering the whole virtual memory
space. In this case, tlb->fullmm is true. Some archs like arm64
doesn't flush TLB when tlb->fullmm is true:
commit 5a7862e83000 ("arm64: tlbflush: avoid flushing when fullmm == 1").
Which causes leaking of tlb entries.
Will clarifies his patch:
"Basically, we tag each address space with an ASID (PCID on x86) which
is resident in the TLB. This means we can elide TLB invalidation when
pulling down a full mm because we won't ever assign that ASID to
another mm without doing TLB invalidation elsewhere (which actually
just nukes the whole TLB).
I think that means that we could potentially not fault on a kernel
uaccess, because we could hit in the TLB"
There could be a window between complete_signal() sending IPI to other
cores and all threads sharing this mm are really kicked off from cores.
In this window, the oom reaper may calls tlb_flush_mmu_tlbonly() to
flush TLB then frees pages. However, due to the above problem, the TLB
entries are not really flushed on arm64. Other threads are possible to
access these pages through TLB entries. Moreover, a copy_to_user() can
also write to these pages without generating page fault, causes
use-after-free bugs.
This patch gathers each vma instead of gathering full vm space. In this
case tlb->fullmm is not true. The behavior of oom reaper become similar
to munmapping before do_exit, which should be safe for all archs.
Link: http://lkml.kernel.org/r/[email protected]
Fixes: aac453635549 ("mm, oom: introduce oom reaper")
Signed-off-by: Wang Nan <[email protected]>
Acked-by: Michal Hocko <[email protected]>
Acked-by: David Rientjes <[email protected]>
Cc: Minchan Kim <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Bob Liu <[email protected]>
Cc: Ingo Molnar <[email protected]>
Cc: Roman Gushchin <[email protected]>
Cc: Konstantin Khlebnikov <[email protected]>
Cc: Andrea Arcangeli <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-416 | static bool __oom_reap_task_mm(struct task_struct *tsk, struct mm_struct *mm)
{
struct mmu_gather tlb;
struct vm_area_struct *vma;
bool ret = true;
/*
* We have to make sure to not race with the victim exit path
* and cause premature new oom victim selection:
* __oom_reap_task_mm exit_mm
* mmget_not_zero
* mmput
* atomic_dec_and_test
* exit_oom_victim
* [...]
* out_of_memory
* select_bad_process
* # no TIF_MEMDIE task selects new victim
* unmap_page_range # frees some memory
*/
mutex_lock(&oom_lock);
if (!down_read_trylock(&mm->mmap_sem)) {
ret = false;
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
/*
* If the mm has notifiers then we would need to invalidate them around
* unmap_page_range and that is risky because notifiers can sleep and
* what they do is basically undeterministic. So let's have a short
* sleep to give the oom victim some more time.
* TODO: we really want to get rid of this ugly hack and make sure that
* notifiers cannot block for unbounded amount of time and add
* mmu_notifier_invalidate_range_{start,end} around unmap_page_range
*/
if (mm_has_notifiers(mm)) {
up_read(&mm->mmap_sem);
schedule_timeout_idle(HZ);
goto unlock_oom;
}
/*
* MMF_OOM_SKIP is set by exit_mmap when the OOM reaper can't
* work on the mm anymore. The check for MMF_OOM_SKIP must run
* under mmap_sem for reading because it serializes against the
* down_write();up_write() cycle in exit_mmap().
*/
if (test_bit(MMF_OOM_SKIP, &mm->flags)) {
up_read(&mm->mmap_sem);
trace_skip_task_reaping(tsk->pid);
goto unlock_oom;
}
trace_start_task_reaping(tsk->pid);
/*
* Tell all users of get_user/copy_from_user etc... that the content
* is no longer stable. No barriers really needed because unmapping
* should imply barriers already and the reader would hit a page fault
* if it stumbled over a reaped memory.
*/
set_bit(MMF_UNSTABLE, &mm->flags);
for (vma = mm->mmap ; vma; vma = vma->vm_next) {
if (!can_madv_dontneed_vma(vma))
continue;
/*
* Only anonymous pages have a good chance to be dropped
* without additional steps which we cannot afford as we
* are OOM already.
*
* We do not even care about fs backed pages because all
* which are reclaimable have already been reclaimed and
* we do not want to block exit_mmap by keeping mm ref
* count elevated without a good reason.
*/
if (vma_is_anonymous(vma) || !(vma->vm_flags & VM_SHARED)) {
tlb_gather_mmu(&tlb, mm, vma->vm_start, vma->vm_end);
unmap_page_range(&tlb, vma, vma->vm_start, vma->vm_end,
NULL);
tlb_finish_mmu(&tlb, vma->vm_start, vma->vm_end);
}
}
pr_info("oom_reaper: reaped process %d (%s), now anon-rss:%lukB, file-rss:%lukB, shmem-rss:%lukB\n",
task_pid_nr(tsk), tsk->comm,
K(get_mm_counter(mm, MM_ANONPAGES)),
K(get_mm_counter(mm, MM_FILEPAGES)),
K(get_mm_counter(mm, MM_SHMEMPAGES)));
up_read(&mm->mmap_sem);
trace_finish_task_reaping(tsk->pid);
unlock_oom:
mutex_unlock(&oom_lock);
return ret;
}
| 169,412 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int v9fs_xattr_set_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
int retval;
struct posix_acl *acl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* set the attribute on the remote. Without even looking at the
* xattr value. We leave it to the server to validate
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_set(dentry, handler->name, value, size,
flags);
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (value) {
/* update the cached acl value */
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
else if (acl) {
retval = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (retval)
goto err_out;
}
} else
acl = NULL;
switch (handler->flags) {
case ACL_TYPE_ACCESS:
if (acl) {
umode_t mode = inode->i_mode;
retval = posix_acl_equiv_mode(acl, &mode);
if (retval < 0)
goto err_out;
else {
struct iattr iattr;
if (retval == 0) {
/*
* ACL can be represented
* by the mode bits. So don't
* update ACL.
*/
acl = NULL;
value = NULL;
size = 0;
}
/* Updte the mode bits */
iattr.ia_mode = ((mode & S_IALLUGO) |
(inode->i_mode & ~S_IALLUGO));
iattr.ia_valid = ATTR_MODE;
/* FIXME should we update ctime ?
* What is the following setxattr update the
* mode ?
*/
v9fs_vfs_setattr_dotl(dentry, &iattr);
}
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
retval = acl ? -EINVAL : 0;
goto err_out;
}
break;
default:
BUG();
}
retval = v9fs_xattr_set(dentry, handler->name, value, size, flags);
if (!retval)
set_cached_acl(inode, handler->flags, acl);
err_out:
posix_acl_release(acl);
return retval;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285 | static int v9fs_xattr_set_acl(const struct xattr_handler *handler,
struct dentry *dentry, struct inode *inode,
const char *name, const void *value,
size_t size, int flags)
{
int retval;
struct posix_acl *acl;
struct v9fs_session_info *v9ses;
v9ses = v9fs_dentry2v9ses(dentry);
/*
* set the attribute on the remote. Without even looking at the
* xattr value. We leave it to the server to validate
*/
if ((v9ses->flags & V9FS_ACCESS_MASK) != V9FS_ACCESS_CLIENT)
return v9fs_xattr_set(dentry, handler->name, value, size,
flags);
if (S_ISLNK(inode->i_mode))
return -EOPNOTSUPP;
if (!inode_owner_or_capable(inode))
return -EPERM;
if (value) {
/* update the cached acl value */
acl = posix_acl_from_xattr(&init_user_ns, value, size);
if (IS_ERR(acl))
return PTR_ERR(acl);
else if (acl) {
retval = posix_acl_valid(inode->i_sb->s_user_ns, acl);
if (retval)
goto err_out;
}
} else
acl = NULL;
switch (handler->flags) {
case ACL_TYPE_ACCESS:
if (acl) {
struct iattr iattr;
retval = posix_acl_update_mode(inode, &iattr.ia_mode, &acl);
if (retval)
goto err_out;
if (!acl) {
/*
* ACL can be represented
* by the mode bits. So don't
* update ACL.
*/
value = NULL;
size = 0;
}
iattr.ia_valid = ATTR_MODE;
/* FIXME should we update ctime ?
* What is the following setxattr update the
* mode ?
*/
v9fs_vfs_setattr_dotl(dentry, &iattr);
}
break;
case ACL_TYPE_DEFAULT:
if (!S_ISDIR(inode->i_mode)) {
retval = acl ? -EINVAL : 0;
goto err_out;
}
break;
default:
BUG();
}
retval = v9fs_xattr_set(dentry, handler->name, value, size, flags);
if (!retval)
set_cached_acl(inode, handler->flags, acl);
err_out:
posix_acl_release(acl);
return retval;
}
| 166,966 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: const TransformPaintPropertyNode* t0() {
return TransformPaintPropertyNode::Root();
}
Commit Message: Reland "[CI] Make paint property nodes non-ref-counted"
This reverts commit 887383b30842d9d9006e11bb6932660a3cb5b1b7.
Reason for revert: Retry in M69.
Original change's description:
> Revert "[CI] Make paint property nodes non-ref-counted"
>
> This reverts commit 70fc0b018c9517558b7aa2be00edf2debb449123.
>
> Reason for revert: Caused bugs found by clusterfuzz
>
> Original change's description:
> > [CI] Make paint property nodes non-ref-counted
> >
> > Now all paint property nodes are owned by ObjectPaintProperties
> > (and LocalFrameView temporarily before removing non-RLS mode).
> > Others just use raw pointers or references.
> >
> > Bug: 833496
> > Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> > Change-Id: I2d544fe153bb94698623248748df63c8aa2081ae
> > Reviewed-on: https://chromium-review.googlesource.com/1031101
> > Reviewed-by: Tien-Ren Chen <[email protected]>
> > Commit-Queue: Xianzhu Wang <[email protected]>
> > Cr-Commit-Position: refs/heads/master@{#554626}
>
> [email protected],[email protected],[email protected]
>
> Change-Id: I02bb50d6744cb81a797246a0116b677e80a3c69f
> No-Presubmit: true
> No-Tree-Checks: true
> No-Try: true
> Bug: 833496,837932,837943
> Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
> Reviewed-on: https://chromium-review.googlesource.com/1034292
> Reviewed-by: Xianzhu Wang <[email protected]>
> Commit-Queue: Xianzhu Wang <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#554653}
[email protected],[email protected],[email protected]
# Not skipping CQ checks because original CL landed > 1 day ago.
Bug: 833496, 837932, 837943
Change-Id: I0b4ef70db1f1f211ba97c30d617225355c750992
Cq-Include-Trybots: master.tryserver.blink:linux_trusty_blink_rel;master.tryserver.chromium.linux:linux_layout_tests_slimming_paint_v2
Reviewed-on: https://chromium-review.googlesource.com/1083491
Commit-Queue: Xianzhu Wang <[email protected]>
Reviewed-by: Xianzhu Wang <[email protected]>
Cr-Commit-Position: refs/heads/master@{#563930}
CWE ID: | const TransformPaintPropertyNode* t0() {
| 171,823 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NavigatorImpl::NavigateToEntry(
FrameTreeNode* frame_tree_node,
const FrameNavigationEntry& frame_entry,
const NavigationEntryImpl& entry,
ReloadType reload_type,
bool is_same_document_history_load,
bool is_history_navigation_in_new_child,
bool is_pending_entry,
const scoped_refptr<ResourceRequestBodyImpl>& post_body) {
TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
GURL dest_url = frame_entry.url();
Referrer dest_referrer = frame_entry.referrer();
if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
dest_url = entry.GetOriginalRequestURL();
dest_referrer = Referrer();
}
if (!dest_url.is_valid() && !dest_url.is_empty()) {
LOG(WARNING) << "Refusing to load invalid URL: "
<< dest_url.possibly_invalid_spec();
return false;
}
if (dest_url.spec().size() > url::kMaxURLChars) {
LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
<< " characters.";
return false;
}
base::TimeTicks navigation_start = base::TimeTicks::Now();
TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(
"navigation,rail", "NavigationTiming navigationStart",
TRACE_EVENT_SCOPE_GLOBAL, navigation_start);
LoFiState lofi_state = LOFI_UNSPECIFIED;
if (!frame_tree_node->IsMainFrame()) {
lofi_state = frame_tree_node->frame_tree()
->root()
->current_frame_host()
->last_navigation_lofi_state();
} else if (reload_type == ReloadType::DISABLE_LOFI_MODE) {
lofi_state = LOFI_OFF;
}
if (IsBrowserSideNavigationEnabled()) {
navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
entry.restore_type()));
RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry,
entry, reload_type, lofi_state,
is_same_document_history_load,
is_history_navigation_in_new_child, navigation_start);
if (frame_tree_node->IsMainFrame() &&
frame_tree_node->navigation_request()) {
TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1(
"navigation", "Navigation timeToNetworkStack",
frame_tree_node->navigation_request()->navigation_handle(),
navigation_start,
"FrameTreeNode id", frame_tree_node->frame_tree_node_id());
}
} else {
RenderFrameHostImpl* dest_render_frame_host =
frame_tree_node->render_manager()->Navigate(
dest_url, frame_entry, entry, reload_type != ReloadType::NONE);
if (!dest_render_frame_host)
return false; // Unable to create the desired RenderFrameHost.
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url);
bool is_transfer = entry.transferred_global_request_id().child_id != -1;
if (is_transfer)
dest_render_frame_host->set_is_loading(true);
if (is_pending_entry && controller_->GetPendingEntryIndex() != -1)
DCHECK(frame_entry.page_state().IsValid());
bool is_transfer_to_same =
is_transfer &&
entry.transferred_global_request_id().child_id ==
dest_render_frame_host->GetProcess()->GetID();
if (!is_transfer_to_same) {
navigation_data_.reset(new NavigationMetricsData(
navigation_start, dest_url, entry.restore_type()));
FrameMsg_Navigate_Type::Value navigation_type = GetNavigationType(
controller_->GetBrowserContext(), entry, reload_type);
dest_render_frame_host->Navigate(
entry.ConstructCommonNavigationParams(
frame_entry, post_body, dest_url, dest_referrer, navigation_type,
lofi_state, navigation_start),
entry.ConstructStartNavigationParams(),
entry.ConstructRequestNavigationParams(
frame_entry, is_same_document_history_load,
is_history_navigation_in_new_child,
entry.GetSubframeUniqueNames(frame_tree_node),
frame_tree_node->has_committed_real_load(),
controller_->GetPendingEntryIndex() == -1,
controller_->GetIndexOfEntry(&entry),
controller_->GetLastCommittedEntryIndex(),
controller_->GetEntryCount()));
}
}
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
if (controller_->GetPendingEntryIndex() == -1 &&
dest_url.SchemeIs(url::kJavaScriptScheme)) {
return false;
}
if (delegate_ && is_pending_entry)
delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
return true;
}
Commit Message: Drop navigations to NavigationEntry with invalid virtual URLs.
BUG=657720
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2452443002
Cr-Commit-Position: refs/heads/master@{#428056}
CWE ID: CWE-20 | bool NavigatorImpl::NavigateToEntry(
FrameTreeNode* frame_tree_node,
const FrameNavigationEntry& frame_entry,
const NavigationEntryImpl& entry,
ReloadType reload_type,
bool is_same_document_history_load,
bool is_history_navigation_in_new_child,
bool is_pending_entry,
const scoped_refptr<ResourceRequestBodyImpl>& post_body) {
TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
GURL dest_url = frame_entry.url();
Referrer dest_referrer = frame_entry.referrer();
if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
dest_url = entry.GetOriginalRequestURL();
dest_referrer = Referrer();
}
// Don't attempt to navigate if the virtual URL is non-empty and invalid.
if (frame_tree_node->IsMainFrame()) {
const GURL& virtual_url = entry.GetVirtualURL();
if (!virtual_url.is_valid() && !virtual_url.is_empty()) {
LOG(WARNING) << "Refusing to load for invalid virtual URL: "
<< virtual_url.possibly_invalid_spec();
return false;
}
}
if (!dest_url.is_valid() && !dest_url.is_empty()) {
LOG(WARNING) << "Refusing to load invalid URL: "
<< dest_url.possibly_invalid_spec();
return false;
}
if (dest_url.spec().size() > url::kMaxURLChars) {
LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
<< " characters.";
return false;
}
base::TimeTicks navigation_start = base::TimeTicks::Now();
TRACE_EVENT_INSTANT_WITH_TIMESTAMP0(
"navigation,rail", "NavigationTiming navigationStart",
TRACE_EVENT_SCOPE_GLOBAL, navigation_start);
LoFiState lofi_state = LOFI_UNSPECIFIED;
if (!frame_tree_node->IsMainFrame()) {
lofi_state = frame_tree_node->frame_tree()
->root()
->current_frame_host()
->last_navigation_lofi_state();
} else if (reload_type == ReloadType::DISABLE_LOFI_MODE) {
lofi_state = LOFI_OFF;
}
if (IsBrowserSideNavigationEnabled()) {
navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
entry.restore_type()));
RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry,
entry, reload_type, lofi_state,
is_same_document_history_load,
is_history_navigation_in_new_child, navigation_start);
if (frame_tree_node->IsMainFrame() &&
frame_tree_node->navigation_request()) {
TRACE_EVENT_ASYNC_BEGIN_WITH_TIMESTAMP1(
"navigation", "Navigation timeToNetworkStack",
frame_tree_node->navigation_request()->navigation_handle(),
navigation_start,
"FrameTreeNode id", frame_tree_node->frame_tree_node_id());
}
} else {
RenderFrameHostImpl* dest_render_frame_host =
frame_tree_node->render_manager()->Navigate(
dest_url, frame_entry, entry, reload_type != ReloadType::NONE);
if (!dest_render_frame_host)
return false; // Unable to create the desired RenderFrameHost.
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url);
bool is_transfer = entry.transferred_global_request_id().child_id != -1;
if (is_transfer)
dest_render_frame_host->set_is_loading(true);
if (is_pending_entry && controller_->GetPendingEntryIndex() != -1)
DCHECK(frame_entry.page_state().IsValid());
bool is_transfer_to_same =
is_transfer &&
entry.transferred_global_request_id().child_id ==
dest_render_frame_host->GetProcess()->GetID();
if (!is_transfer_to_same) {
navigation_data_.reset(new NavigationMetricsData(
navigation_start, dest_url, entry.restore_type()));
FrameMsg_Navigate_Type::Value navigation_type = GetNavigationType(
controller_->GetBrowserContext(), entry, reload_type);
dest_render_frame_host->Navigate(
entry.ConstructCommonNavigationParams(
frame_entry, post_body, dest_url, dest_referrer, navigation_type,
lofi_state, navigation_start),
entry.ConstructStartNavigationParams(),
entry.ConstructRequestNavigationParams(
frame_entry, is_same_document_history_load,
is_history_navigation_in_new_child,
entry.GetSubframeUniqueNames(frame_tree_node),
frame_tree_node->has_committed_real_load(),
controller_->GetPendingEntryIndex() == -1,
controller_->GetIndexOfEntry(&entry),
controller_->GetLastCommittedEntryIndex(),
controller_->GetEntryCount()));
}
}
if (is_pending_entry)
CHECK_EQ(controller_->GetPendingEntry(), &entry);
if (controller_->GetPendingEntryIndex() == -1 &&
dest_url.SchemeIs(url::kJavaScriptScheme)) {
return false;
}
if (delegate_ && is_pending_entry)
delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
return true;
}
| 172,544 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RemoteFrame::Navigate(const FrameLoadRequest& passed_request) {
FrameLoadRequest frame_request(passed_request);
FrameLoader::SetReferrerForFrameRequest(frame_request);
FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(),
frame_request.OriginDocument());
frame_request.GetResourceRequest().SetHasUserGesture(
Frame::HasTransientUserActivation(this));
Client()->Navigate(frame_request.GetResourceRequest(),
frame_request.ReplacesCurrentItem());
}
Commit Message: Move user activation check to RemoteFrame::Navigate's callers.
Currently RemoteFrame::Navigate is the user of
Frame::HasTransientUserActivation that passes a RemoteFrame*, and
it seems wrong because the user activation (user gesture) needed by
the navigation should belong to the LocalFrame that initiated the
navigation.
Follow-up CLs after this one will update UserActivation code in
Frame to take a LocalFrame* instead of a Frame*, and get rid of
redundant IPCs.
Bug: 811414
Change-Id: I771c1694043edb54374a44213d16715d9c7da704
Reviewed-on: https://chromium-review.googlesource.com/914736
Commit-Queue: Mustaq Ahmed <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#536728}
CWE ID: CWE-190 | void RemoteFrame::Navigate(const FrameLoadRequest& passed_request) {
FrameLoadRequest frame_request(passed_request);
FrameLoader::SetReferrerForFrameRequest(frame_request);
FrameLoader::UpgradeInsecureRequest(frame_request.GetResourceRequest(),
frame_request.OriginDocument());
Client()->Navigate(frame_request.GetResourceRequest(),
frame_request.ReplacesCurrentItem());
}
| 173,031 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
Commit Message: Fix potential SQL Injection with postgis TIME filters (#4834)
CWE ID: CWE-89 | int msPostGISLayerSetTimeFilter(layerObj *lp, const char *timestring, const char *timefield)
{
char **atimes, **aranges = NULL;
int numtimes=0,i=0,numranges=0;
size_t buffer_size = 512;
char buffer[512], bufferTmp[512];
buffer[0] = '\0';
bufferTmp[0] = '\0';
if (!lp || !timestring || !timefield)
return MS_FALSE;
if( strchr(timestring,'\'') || strchr(timestring, '\\') ) {
msSetError(MS_MISCERR, "Invalid time filter.", "msPostGISLayerSetTimeFilter()");
return MS_FALSE;
}
/* discrete time */
if (strstr(timestring, ",") == NULL &&
strstr(timestring, "/") == NULL) { /* discrete time */
createPostgresTimeCompareSimple(timefield, timestring, buffer, buffer_size);
} else {
/* multiple times, or ranges */
atimes = msStringSplit (timestring, ',', &numtimes);
if (atimes == NULL || numtimes < 1)
return MS_FALSE;
strlcat(buffer, "(", buffer_size);
for(i=0; i<numtimes; i++) {
if(i!=0) {
strlcat(buffer, " OR ", buffer_size);
}
strlcat(buffer, "(", buffer_size);
aranges = msStringSplit(atimes[i], '/', &numranges);
if(!aranges) return MS_FALSE;
if(numranges == 1) {
/* we don't have range, just a simple time */
createPostgresTimeCompareSimple(timefield, atimes[i], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else if(numranges == 2) {
/* we have a range */
createPostgresTimeCompareRange(timefield, aranges[0], aranges[1], bufferTmp, buffer_size);
strlcat(buffer, bufferTmp, buffer_size);
} else {
return MS_FALSE;
}
msFreeCharArray(aranges, numranges);
strlcat(buffer, ")", buffer_size);
}
strlcat(buffer, ")", buffer_size);
msFreeCharArray(atimes, numtimes);
}
if(!*buffer) {
return MS_FALSE;
}
if(lp->filteritem) free(lp->filteritem);
lp->filteritem = msStrdup(timefield);
if (&lp->filter) {
/* if the filter is set and it's a string type, concatenate it with
the time. If not just free it */
if (lp->filter.type == MS_EXPRESSION) {
snprintf(bufferTmp, buffer_size, "(%s) and %s", lp->filter.string, buffer);
loadExpressionString(&lp->filter, bufferTmp);
} else {
freeExpression(&lp->filter);
loadExpressionString(&lp->filter, buffer);
}
}
return MS_TRUE;
}
| 166,525 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)
{
struct cm_id_private *cm_id_priv;
cm_id_priv = container_of(id, struct cm_id_private, id);
if (smac != NULL)
memcpy(cm_id_priv->av.smac, smac, sizeof(cm_id_priv->av.smac));
if (alt_smac != NULL)
memcpy(cm_id_priv->alt_av.smac, alt_smac,
sizeof(cm_id_priv->alt_av.smac));
return 0;
}
Commit Message: IB/core: Don't resolve passive side RoCE L2 address in CMA REQ handler
The code that resolves the passive side source MAC within the rdma_cm
connection request handler was both redundant and buggy, so remove it.
It was redundant since later, when an RC QP is modified to RTR state,
the resolution will take place in the ib_core module. It was buggy
because this callback also deals with UD SIDR exchange, for which we
incorrectly looked at the REQ member of the CM event and dereferenced
a random value.
Fixes: dd5f03beb4f7 ("IB/core: Ethernet L2 attributes in verbs/cm structures")
Signed-off-by: Moni Shoua <[email protected]>
Signed-off-by: Or Gerlitz <[email protected]>
Signed-off-by: Roland Dreier <[email protected]>
CWE ID: CWE-20 | int ib_update_cm_av(struct ib_cm_id *id, const u8 *smac, const u8 *alt_smac)
| 166,389 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ProfileChooserView::RemoveAccount() {
DCHECK(!account_id_to_remove_.empty());
ProfileOAuth2TokenService* oauth2_token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile());
if (oauth2_token_service) {
oauth2_token_service->RevokeCredentials(account_id_to_remove_);
PostActionPerformed(ProfileMetrics::PROFILE_DESKTOP_MENU_REMOVE_ACCT);
}
account_id_to_remove_.clear();
ShowViewFromMode(profiles::BUBBLE_VIEW_MODE_ACCOUNT_MANAGEMENT);
}
Commit Message: [signin] Add metrics to track the source for refresh token updated events
This CL add a source for update and revoke credentials operations. It then
surfaces the source in the chrome://signin-internals page.
This CL also records the following histograms that track refresh token events:
* Signin.RefreshTokenUpdated.ToValidToken.Source
* Signin.RefreshTokenUpdated.ToInvalidToken.Source
* Signin.RefreshTokenRevoked.Source
These histograms are needed to validate the assumptions of how often tokens
are revoked by the browser and the sources for the token revocations.
Bug: 896182
Change-Id: I2fcab80ee8e5699708e695bc3289fa6d34859a90
Reviewed-on: https://chromium-review.googlesource.com/c/1286464
Reviewed-by: Jochen Eisinger <[email protected]>
Reviewed-by: David Roger <[email protected]>
Reviewed-by: Ilya Sherman <[email protected]>
Commit-Queue: Mihai Sardarescu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#606181}
CWE ID: CWE-20 | void ProfileChooserView::RemoveAccount() {
DCHECK(!account_id_to_remove_.empty());
ProfileOAuth2TokenService* oauth2_token_service =
ProfileOAuth2TokenServiceFactory::GetForProfile(browser_->profile());
if (oauth2_token_service) {
oauth2_token_service->RevokeCredentials(
account_id_to_remove_, signin_metrics::SourceForRefreshTokenOperation::
kUserMenu_RemoveAccount);
PostActionPerformed(ProfileMetrics::PROFILE_DESKTOP_MENU_REMOVE_ACCT);
}
account_id_to_remove_.clear();
ShowViewFromMode(profiles::BUBBLE_VIEW_MODE_ACCOUNT_MANAGEMENT);
}
| 172,570 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: DidFinishNavigation(NavigationHandle* handle) {
if (handle->GetFrameTreeNodeId() != frame_tree_node_id_)
return;
if (!handle->HasCommitted())
return;
if (handle->GetRenderFrameHost()->GetSiteInstance() != parent_site_instance_)
return;
if (!handle->GetURL().IsAboutBlank())
return;
if (!handle->GetRenderFrameHost()->PrepareForInnerWebContentsAttach()) {
filter_->ResumeAttachOrDestroy(element_instance_id_,
MSG_ROUTING_NONE /* no plugin frame */);
}
base::PostTaskWithTraits(
FROM_HERE, {BrowserThread::UI},
base::BindOnce(&ExtensionsGuestViewMessageFilter::ResumeAttachOrDestroy,
filter_, element_instance_id_,
handle->GetRenderFrameHost()->GetRoutingID()));
}
Commit Message: [GuestView] - Introduce MimeHandlerViewAttachHelper
This CL is for the most part a mechanical change which extracts almost
all the frame-based MimeHandlerView code out of
ExtensionsGuestViewMessageFilter. This change both removes the current
clutter form EGVMF as well as fixesa race introduced when the
frame-based logic was added to EGVMF. The reason for the race was that
EGVMF is destroyed on IO thread but all the access to it (for
frame-based MHV) are from UI.
[email protected],[email protected]
Bug: 659750, 896679, 911161, 918861
Change-Id: I6474b870e4d56daa68be03637bb633665d9f9dda
Reviewed-on: https://chromium-review.googlesource.com/c/1401451
Commit-Queue: Ehsan Karamad <[email protected]>
Reviewed-by: James MacLean <[email protected]>
Reviewed-by: Ehsan Karamad <[email protected]>
Cr-Commit-Position: refs/heads/master@{#621155}
CWE ID: CWE-362 | DidFinishNavigation(NavigationHandle* handle) {
| 173,038 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if (g->sect <= 0 ||
g->head <= 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
Commit Message: floppy: fix div-by-zero in setup_format_params
This fixes a divide by zero error in the setup_format_params function of
the floppy driver.
Two consecutive ioctls can trigger the bug: The first one should set the
drive geometry with such .sect and .rate values for the F_SECT_PER_TRACK
to become zero. Next, the floppy format operation should be called.
A floppy disk is not required to be inserted. An unprivileged user
could trigger the bug if the device is accessible.
The patch checks F_SECT_PER_TRACK for a non-zero value in the
set_geometry function. The proper check should involve a reasonable
upper limit for the .sect and .rate fields, but it could change the
UAPI.
The patch also checks F_SECT_PER_TRACK in the setup_format_params, and
cancels the formatting operation in case of zero.
The bug was found by syzkaller.
Signed-off-by: Denis Efremov <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-369 | static int set_geometry(unsigned int cmd, struct floppy_struct *g,
int drive, int type, struct block_device *bdev)
{
int cnt;
/* sanity checking for parameters. */
if (g->sect <= 0 ||
g->head <= 0 ||
/* check for zero in F_SECT_PER_TRACK */
(unsigned char)((g->sect << 2) >> FD_SIZECODE(g)) == 0 ||
g->track <= 0 || g->track > UDP->tracks >> STRETCH(g) ||
/* check if reserved bits are set */
(g->stretch & ~(FD_STRETCH | FD_SWAPSIDES | FD_SECTBASEMASK)) != 0)
return -EINVAL;
if (type) {
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
mutex_lock(&open_lock);
if (lock_fdc(drive)) {
mutex_unlock(&open_lock);
return -EINTR;
}
floppy_type[type] = *g;
floppy_type[type].name = "user format";
for (cnt = type << 2; cnt < (type << 2) + 4; cnt++)
floppy_sizes[cnt] = floppy_sizes[cnt + 0x80] =
floppy_type[type].size + 1;
process_fd_request();
for (cnt = 0; cnt < N_DRIVE; cnt++) {
struct block_device *bdev = opened_bdev[cnt];
if (!bdev || ITYPE(drive_state[cnt].fd_device) != type)
continue;
__invalidate_device(bdev, true);
}
mutex_unlock(&open_lock);
} else {
int oldStretch;
if (lock_fdc(drive))
return -EINTR;
if (cmd != FDDEFPRM) {
/* notice a disk change immediately, else
* we lose our settings immediately*/
if (poll_drive(true, FD_RAW_NEED_DISK) == -EINTR)
return -EINTR;
}
oldStretch = g->stretch;
user_params[drive] = *g;
if (buffer_drive == drive)
SUPBOUND(buffer_max, user_params[drive].sect);
current_type[drive] = &user_params[drive];
floppy_sizes[drive] = user_params[drive].size;
if (cmd == FDDEFPRM)
DRS->keep_data = -1;
else
DRS->keep_data = 1;
/* invalidation. Invalidate only when needed, i.e.
* when there are already sectors in the buffer cache
* whose number will change. This is useful, because
* mtools often changes the geometry of the disk after
* looking at the boot block */
if (DRS->maxblock > user_params[drive].sect ||
DRS->maxtrack ||
((user_params[drive].sect ^ oldStretch) &
(FD_SWAPSIDES | FD_SECTBASEMASK)))
invalidate_drive(bdev);
else
process_fd_request();
}
return 0;
}
| 169,585 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)
{
KerndeintContext *kerndeint = inlink->dst->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *outpic;
const uint8_t *prvp; ///< Previous field's pixel line number n
const uint8_t *prvpp; ///< Previous field's pixel line number (n - 1)
const uint8_t *prvpn; ///< Previous field's pixel line number (n + 1)
const uint8_t *prvppp; ///< Previous field's pixel line number (n - 2)
const uint8_t *prvpnn; ///< Previous field's pixel line number (n + 2)
const uint8_t *prvp4p; ///< Previous field's pixel line number (n - 4)
const uint8_t *prvp4n; ///< Previous field's pixel line number (n + 4)
const uint8_t *srcp; ///< Current field's pixel line number n
const uint8_t *srcpp; ///< Current field's pixel line number (n - 1)
const uint8_t *srcpn; ///< Current field's pixel line number (n + 1)
const uint8_t *srcppp; ///< Current field's pixel line number (n - 2)
const uint8_t *srcpnn; ///< Current field's pixel line number (n + 2)
const uint8_t *srcp3p; ///< Current field's pixel line number (n - 3)
const uint8_t *srcp3n; ///< Current field's pixel line number (n + 3)
const uint8_t *srcp4p; ///< Current field's pixel line number (n - 4)
const uint8_t *srcp4n; ///< Current field's pixel line number (n + 4)
uint8_t *dstp, *dstp_saved;
const uint8_t *srcp_saved;
int src_linesize, psrc_linesize, dst_linesize, bwidth;
int x, y, plane, val, hi, lo, g, h, n = kerndeint->frame++;
double valf;
const int thresh = kerndeint->thresh;
const int order = kerndeint->order;
const int map = kerndeint->map;
const int sharp = kerndeint->sharp;
const int twoway = kerndeint->twoway;
const int is_packed_rgb = kerndeint->is_packed_rgb;
outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!outpic) {
av_frame_free(&inpic);
return AVERROR(ENOMEM);
}
av_frame_copy_props(outpic, inpic);
outpic->interlaced_frame = 0;
for (plane = 0; inpic->data[plane] && plane < 4; plane++) {
h = plane == 0 ? inlink->h : FF_CEIL_RSHIFT(inlink->h, kerndeint->vsub);
bwidth = kerndeint->tmp_bwidth[plane];
srcp = srcp_saved = inpic->data[plane];
src_linesize = inpic->linesize[plane];
psrc_linesize = kerndeint->tmp_linesize[plane];
dstp = dstp_saved = outpic->data[plane];
dst_linesize = outpic->linesize[plane];
srcp = srcp_saved + (1 - order) * src_linesize;
dstp = dstp_saved + (1 - order) * dst_linesize;
for (y = 0; y < h; y += 2) {
memcpy(dstp, srcp, bwidth);
srcp += 2 * src_linesize;
dstp += 2 * dst_linesize;
}
memcpy(dstp_saved + order * dst_linesize, srcp_saved + (1 - order) * src_linesize, bwidth);
memcpy(dstp_saved + (2 + order ) * dst_linesize, srcp_saved + (3 - order) * src_linesize, bwidth);
memcpy(dstp_saved + (h - 2 + order) * dst_linesize, srcp_saved + (h - 1 - order) * src_linesize, bwidth);
memcpy(dstp_saved + (h - 4 + order) * dst_linesize, srcp_saved + (h - 3 - order) * src_linesize, bwidth);
/* For the other field choose adaptively between using the previous field
or the interpolant from the current field. */
prvp = kerndeint->tmp_data[plane] + 5 * psrc_linesize - (1 - order) * psrc_linesize;
prvpp = prvp - psrc_linesize;
prvppp = prvp - 2 * psrc_linesize;
prvp4p = prvp - 4 * psrc_linesize;
prvpn = prvp + psrc_linesize;
prvpnn = prvp + 2 * psrc_linesize;
prvp4n = prvp + 4 * psrc_linesize;
srcp = srcp_saved + 5 * src_linesize - (1 - order) * src_linesize;
srcpp = srcp - src_linesize;
srcppp = srcp - 2 * src_linesize;
srcp3p = srcp - 3 * src_linesize;
srcp4p = srcp - 4 * src_linesize;
srcpn = srcp + src_linesize;
srcpnn = srcp + 2 * src_linesize;
srcp3n = srcp + 3 * src_linesize;
srcp4n = srcp + 4 * src_linesize;
dstp = dstp_saved + 5 * dst_linesize - (1 - order) * dst_linesize;
for (y = 5 - (1 - order); y <= h - 5 - (1 - order); y += 2) {
for (x = 0; x < bwidth; x++) {
if (thresh == 0 || n == 0 ||
(abs((int)prvp[x] - (int)srcp[x]) > thresh) ||
(abs((int)prvpp[x] - (int)srcpp[x]) > thresh) ||
(abs((int)prvpn[x] - (int)srcpn[x]) > thresh)) {
if (map) {
g = x & ~3;
if (is_packed_rgb) {
AV_WB32(dstp + g, 0xffffffff);
x = g + 3;
} else if (inlink->format == AV_PIX_FMT_YUYV422) {
AV_WB32(dstp + g, 0xeb80eb80);
x = g + 3;
} else {
dstp[x] = plane == 0 ? 235 : 128;
}
} else {
if (is_packed_rgb) {
hi = 255;
lo = 0;
} else if (inlink->format == AV_PIX_FMT_YUYV422) {
hi = x & 1 ? 240 : 235;
lo = 16;
} else {
hi = plane == 0 ? 235 : 240;
lo = 16;
}
if (sharp) {
if (twoway) {
valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x])
+ 0.170 * ((int)srcp[x] + (int)prvp[x])
- 0.116 * ((int)srcppp[x] + (int)srcpnn[x] + (int)prvppp[x] + (int)prvpnn[x])
- 0.026 * ((int)srcp3p[x] + (int)srcp3n[x])
+ 0.031 * ((int)srcp4p[x] + (int)srcp4n[x] + (int)prvp4p[x] + (int)prvp4n[x]);
} else {
valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x])
+ 0.170 * ((int)prvp[x])
- 0.116 * ((int)prvppp[x] + (int)prvpnn[x])
- 0.026 * ((int)srcp3p[x] + (int)srcp3n[x])
+ 0.031 * ((int)prvp4p[x] + (int)prvp4p[x]);
}
dstp[x] = av_clip(valf, lo, hi);
} else {
if (twoway) {
val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)srcp[x] + (int)prvp[x])
- (int)(srcppp[x]) - (int)(srcpnn[x])
- (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4;
} else {
val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)prvp[x])
- (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4;
}
dstp[x] = av_clip(val, lo, hi);
}
}
} else {
dstp[x] = srcp[x];
}
}
prvp += 2 * psrc_linesize;
prvpp += 2 * psrc_linesize;
prvppp += 2 * psrc_linesize;
prvpn += 2 * psrc_linesize;
prvpnn += 2 * psrc_linesize;
prvp4p += 2 * psrc_linesize;
prvp4n += 2 * psrc_linesize;
srcp += 2 * src_linesize;
srcpp += 2 * src_linesize;
srcppp += 2 * src_linesize;
srcp3p += 2 * src_linesize;
srcp4p += 2 * src_linesize;
srcpn += 2 * src_linesize;
srcpnn += 2 * src_linesize;
srcp3n += 2 * src_linesize;
srcp4n += 2 * src_linesize;
dstp += 2 * dst_linesize;
}
srcp = inpic->data[plane];
dstp = kerndeint->tmp_data[plane];
av_image_copy_plane(dstp, psrc_linesize, srcp, src_linesize, bwidth, h);
}
av_frame_free(&inpic);
return ff_filter_frame(outlink, outpic);
}
Commit Message: avfilter: fix plane validity checks
Fixes out of array accesses
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-119 | static int filter_frame(AVFilterLink *inlink, AVFrame *inpic)
{
KerndeintContext *kerndeint = inlink->dst->priv;
AVFilterLink *outlink = inlink->dst->outputs[0];
AVFrame *outpic;
const uint8_t *prvp; ///< Previous field's pixel line number n
const uint8_t *prvpp; ///< Previous field's pixel line number (n - 1)
const uint8_t *prvpn; ///< Previous field's pixel line number (n + 1)
const uint8_t *prvppp; ///< Previous field's pixel line number (n - 2)
const uint8_t *prvpnn; ///< Previous field's pixel line number (n + 2)
const uint8_t *prvp4p; ///< Previous field's pixel line number (n - 4)
const uint8_t *prvp4n; ///< Previous field's pixel line number (n + 4)
const uint8_t *srcp; ///< Current field's pixel line number n
const uint8_t *srcpp; ///< Current field's pixel line number (n - 1)
const uint8_t *srcpn; ///< Current field's pixel line number (n + 1)
const uint8_t *srcppp; ///< Current field's pixel line number (n - 2)
const uint8_t *srcpnn; ///< Current field's pixel line number (n + 2)
const uint8_t *srcp3p; ///< Current field's pixel line number (n - 3)
const uint8_t *srcp3n; ///< Current field's pixel line number (n + 3)
const uint8_t *srcp4p; ///< Current field's pixel line number (n - 4)
const uint8_t *srcp4n; ///< Current field's pixel line number (n + 4)
uint8_t *dstp, *dstp_saved;
const uint8_t *srcp_saved;
int src_linesize, psrc_linesize, dst_linesize, bwidth;
int x, y, plane, val, hi, lo, g, h, n = kerndeint->frame++;
double valf;
const int thresh = kerndeint->thresh;
const int order = kerndeint->order;
const int map = kerndeint->map;
const int sharp = kerndeint->sharp;
const int twoway = kerndeint->twoway;
const int is_packed_rgb = kerndeint->is_packed_rgb;
outpic = ff_get_video_buffer(outlink, outlink->w, outlink->h);
if (!outpic) {
av_frame_free(&inpic);
return AVERROR(ENOMEM);
}
av_frame_copy_props(outpic, inpic);
outpic->interlaced_frame = 0;
for (plane = 0; plane < 4 && inpic->data[plane] && inpic->linesize[plane]; plane++) {
h = plane == 0 ? inlink->h : FF_CEIL_RSHIFT(inlink->h, kerndeint->vsub);
bwidth = kerndeint->tmp_bwidth[plane];
srcp = srcp_saved = inpic->data[plane];
src_linesize = inpic->linesize[plane];
psrc_linesize = kerndeint->tmp_linesize[plane];
dstp = dstp_saved = outpic->data[plane];
dst_linesize = outpic->linesize[plane];
srcp = srcp_saved + (1 - order) * src_linesize;
dstp = dstp_saved + (1 - order) * dst_linesize;
for (y = 0; y < h; y += 2) {
memcpy(dstp, srcp, bwidth);
srcp += 2 * src_linesize;
dstp += 2 * dst_linesize;
}
memcpy(dstp_saved + order * dst_linesize, srcp_saved + (1 - order) * src_linesize, bwidth);
memcpy(dstp_saved + (2 + order ) * dst_linesize, srcp_saved + (3 - order) * src_linesize, bwidth);
memcpy(dstp_saved + (h - 2 + order) * dst_linesize, srcp_saved + (h - 1 - order) * src_linesize, bwidth);
memcpy(dstp_saved + (h - 4 + order) * dst_linesize, srcp_saved + (h - 3 - order) * src_linesize, bwidth);
/* For the other field choose adaptively between using the previous field
or the interpolant from the current field. */
prvp = kerndeint->tmp_data[plane] + 5 * psrc_linesize - (1 - order) * psrc_linesize;
prvpp = prvp - psrc_linesize;
prvppp = prvp - 2 * psrc_linesize;
prvp4p = prvp - 4 * psrc_linesize;
prvpn = prvp + psrc_linesize;
prvpnn = prvp + 2 * psrc_linesize;
prvp4n = prvp + 4 * psrc_linesize;
srcp = srcp_saved + 5 * src_linesize - (1 - order) * src_linesize;
srcpp = srcp - src_linesize;
srcppp = srcp - 2 * src_linesize;
srcp3p = srcp - 3 * src_linesize;
srcp4p = srcp - 4 * src_linesize;
srcpn = srcp + src_linesize;
srcpnn = srcp + 2 * src_linesize;
srcp3n = srcp + 3 * src_linesize;
srcp4n = srcp + 4 * src_linesize;
dstp = dstp_saved + 5 * dst_linesize - (1 - order) * dst_linesize;
for (y = 5 - (1 - order); y <= h - 5 - (1 - order); y += 2) {
for (x = 0; x < bwidth; x++) {
if (thresh == 0 || n == 0 ||
(abs((int)prvp[x] - (int)srcp[x]) > thresh) ||
(abs((int)prvpp[x] - (int)srcpp[x]) > thresh) ||
(abs((int)prvpn[x] - (int)srcpn[x]) > thresh)) {
if (map) {
g = x & ~3;
if (is_packed_rgb) {
AV_WB32(dstp + g, 0xffffffff);
x = g + 3;
} else if (inlink->format == AV_PIX_FMT_YUYV422) {
AV_WB32(dstp + g, 0xeb80eb80);
x = g + 3;
} else {
dstp[x] = plane == 0 ? 235 : 128;
}
} else {
if (is_packed_rgb) {
hi = 255;
lo = 0;
} else if (inlink->format == AV_PIX_FMT_YUYV422) {
hi = x & 1 ? 240 : 235;
lo = 16;
} else {
hi = plane == 0 ? 235 : 240;
lo = 16;
}
if (sharp) {
if (twoway) {
valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x])
+ 0.170 * ((int)srcp[x] + (int)prvp[x])
- 0.116 * ((int)srcppp[x] + (int)srcpnn[x] + (int)prvppp[x] + (int)prvpnn[x])
- 0.026 * ((int)srcp3p[x] + (int)srcp3n[x])
+ 0.031 * ((int)srcp4p[x] + (int)srcp4n[x] + (int)prvp4p[x] + (int)prvp4n[x]);
} else {
valf = + 0.526 * ((int)srcpp[x] + (int)srcpn[x])
+ 0.170 * ((int)prvp[x])
- 0.116 * ((int)prvppp[x] + (int)prvpnn[x])
- 0.026 * ((int)srcp3p[x] + (int)srcp3n[x])
+ 0.031 * ((int)prvp4p[x] + (int)prvp4p[x]);
}
dstp[x] = av_clip(valf, lo, hi);
} else {
if (twoway) {
val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)srcp[x] + (int)prvp[x])
- (int)(srcppp[x]) - (int)(srcpnn[x])
- (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4;
} else {
val = (8 * ((int)srcpp[x] + (int)srcpn[x]) + 2 * ((int)prvp[x])
- (int)(prvppp[x]) - (int)(prvpnn[x])) >> 4;
}
dstp[x] = av_clip(val, lo, hi);
}
}
} else {
dstp[x] = srcp[x];
}
}
prvp += 2 * psrc_linesize;
prvpp += 2 * psrc_linesize;
prvppp += 2 * psrc_linesize;
prvpn += 2 * psrc_linesize;
prvpnn += 2 * psrc_linesize;
prvp4p += 2 * psrc_linesize;
prvp4n += 2 * psrc_linesize;
srcp += 2 * src_linesize;
srcpp += 2 * src_linesize;
srcppp += 2 * src_linesize;
srcp3p += 2 * src_linesize;
srcp4p += 2 * src_linesize;
srcpn += 2 * src_linesize;
srcpnn += 2 * src_linesize;
srcp3n += 2 * src_linesize;
srcp4n += 2 * src_linesize;
dstp += 2 * dst_linesize;
}
srcp = inpic->data[plane];
dstp = kerndeint->tmp_data[plane];
av_image_copy_plane(dstp, psrc_linesize, srcp, src_linesize, bwidth, h);
}
av_frame_free(&inpic);
return ff_filter_frame(outlink, outpic);
}
| 166,003 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int ssl3_accept(SSL *s)
{
BUF_MEM *buf;
unsigned long alg_k,Time=(unsigned long)time(NULL);
void (*cb)(const SSL *ssl,int type,int val)=NULL;
int ret= -1;
int new_state,state,skip=0;
RAND_add(&Time,sizeof(Time),0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
/* init things to blank */
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
if (s->cert == NULL)
{
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
return(-1);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* If we're awaiting a HeartbeatResponse, pretend we
* already got and don't await it anymore, because
* Heartbeats don't make sense during handshakes anyway.
*/
if (s->tlsext_hb_pending)
{
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;)
{
state=s->state;
switch (s->state)
{
case SSL_ST_RENEGOTIATE:
s->renegotiate=1;
/* s->state=SSL_ST_ACCEPT; */
case SSL_ST_BEFORE:
case SSL_ST_ACCEPT:
case SSL_ST_BEFORE|SSL_ST_ACCEPT:
case SSL_ST_OK|SSL_ST_ACCEPT:
s->server=1;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
if ((s->version>>8) != 3)
{
SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
return -1;
}
s->type=SSL_ST_ACCEPT;
if (s->init_buf == NULL)
{
if ((buf=BUF_MEM_new()) == NULL)
{
ret= -1;
goto end;
}
if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
{
ret= -1;
goto end;
}
s->init_buf=buf;
}
if (!ssl3_setup_buffers(s))
{
ret= -1;
goto end;
}
s->init_num=0;
s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
if (s->state != SSL_ST_RENEGOTIATE)
{
/* Ok, we now need to push on a buffering BIO so that
* the output is sent in a way that TCP likes :-)
*/
if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
ssl3_init_finished_mac(s);
s->state=SSL3_ST_SR_CLNT_HELLO_A;
s->ctx->stats.sess_accept++;
}
else if (!s->s3->send_connection_binding &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
{
/* Server attempting to renegotiate with
* client that doesn't support secure
* renegotiation.
*/
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
ret = -1;
goto end;
}
else
{
/* s->state == SSL_ST_RENEGOTIATE,
* we will just send a HelloRequest */
s->ctx->stats.sess_accept_renegotiate++;
s->state=SSL3_ST_SW_HELLO_REQ_A;
}
break;
case SSL3_ST_SW_HELLO_REQ_A:
case SSL3_ST_SW_HELLO_REQ_B:
s->shutdown=0;
ret=ssl3_send_hello_request(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
ssl3_init_finished_mac(s);
break;
case SSL3_ST_SW_HELLO_REQ_C:
s->state=SSL_ST_OK;
break;
case SSL3_ST_SR_CLNT_HELLO_A:
case SSL3_ST_SR_CLNT_HELLO_B:
case SSL3_ST_SR_CLNT_HELLO_C:
s->shutdown=0;
if (s->rwstate != SSL_X509_LOOKUP)
{
ret=ssl3_get_client_hello(s);
if (ret <= 0) goto end;
}
#ifndef OPENSSL_NO_SRP
{
int al;
if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)
{
/* callback indicates firther work to be done */
s->rwstate=SSL_X509_LOOKUP;
goto end;
}
if (ret != SSL_ERROR_NONE)
{
ssl3_send_alert(s,SSL3_AL_FATAL,al);
/* This is not really an error but the only means to
for a client to detect whether srp is supported. */
if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
ret= -1;
goto end;
}
}
#endif
s->renegotiate = 2;
s->state=SSL3_ST_SW_SRVR_HELLO_A;
s->init_num=0;
break;
case SSL3_ST_SW_SRVR_HELLO_A:
case SSL3_ST_SW_SRVR_HELLO_B:
ret=ssl3_send_server_hello(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->hit)
{
if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
else
s->state=SSL3_ST_SW_CHANGE_A;
}
#else
if (s->hit)
s->state=SSL3_ST_SW_CHANGE_A;
#endif
else
s->state=SSL3_ST_SW_CERT_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_A:
case SSL3_ST_SW_CERT_B:
/* Check if it is anon DH or anon ECDH, */
/* normal PSK or KRB5 or SRP */
if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
&& !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
{
ret=ssl3_send_server_certificate(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state=SSL3_ST_SW_CERT_STATUS_A;
else
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
else
{
skip = 1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
#else
}
else
skip=1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
#endif
s->init_num=0;
break;
case SSL3_ST_SW_KEY_EXCH_A:
case SSL3_ST_SW_KEY_EXCH_B:
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
/* clear this, it may get reset by
* send_server_key_exchange */
if ((s->options & SSL_OP_EPHEMERAL_RSA)
#ifndef OPENSSL_NO_KRB5
&& !(alg_k & SSL_kKRB5)
#endif /* OPENSSL_NO_KRB5 */
)
/* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
* even when forbidden by protocol specs
* (handshake may fail as clients are not required to
* be able to handle this) */
s->s3->tmp.use_rsa_tmp=1;
else
s->s3->tmp.use_rsa_tmp=0;
/* only send if a DH key exchange, fortezza or
* RSA but we have a sign only certificate
*
* PSK: may send PSK identity hints
*
* For ECC ciphersuites, we send a serverKeyExchange
* message only if the cipher suite is either
* ECDH-anon or ECDHE. In other cases, the
* server certificate contains the server's
* public key for key exchange.
*/
if (s->s3->tmp.use_rsa_tmp
/* PSK: send ServerKeyExchange if PSK identity
* hint if provided */
#ifndef OPENSSL_NO_PSK
|| ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
#endif
#ifndef OPENSSL_NO_SRP
/* SRP: send ServerKeyExchange */
|| (alg_k & SSL_kSRP)
#endif
|| (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH))
|| (alg_k & SSL_kEECDH)
|| ((alg_k & SSL_kRSA)
&& (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
|| (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
&& EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
)
)
)
)
{
ret=ssl3_send_server_key_exchange(s);
if (ret <= 0) goto end;
}
else
skip=1;
s->state=SSL3_ST_SW_CERT_REQ_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_REQ_A:
case SSL3_ST_SW_CERT_REQ_B:
if (/* don't request cert unless asked for it: */
!(s->verify_mode & SSL_VERIFY_PEER) ||
/* if SSL_VERIFY_CLIENT_ONCE is set,
* don't request cert during re-negotiation: */
((s->session->peer != NULL) &&
(s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
/* never request cert in anonymous ciphersuites
* (see section "Certificate request" in SSL 3 drafts
* and in RFC 2246): */
((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
/* ... except when the application insists on verification
* (against the specs, but s3_clnt.c accepts this for SSL 3) */
!(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
/* never request cert in Kerberos ciphersuites */
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)
/* With normal PSK Certificates and
* Certificate Requests are omitted */
|| (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
/* no cert request */
skip=1;
s->s3->tmp.cert_request=0;
s->state=SSL3_ST_SW_SRVR_DONE_A;
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
s->s3->tmp.cert_request=1;
ret=ssl3_send_certificate_request(s);
if (ret <= 0) goto end;
#ifndef NETSCAPE_HANG_BUG
s->state=SSL3_ST_SW_SRVR_DONE_A;
#else
s->state=SSL3_ST_SW_FLUSH;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
#endif
s->init_num=0;
}
break;
case SSL3_ST_SW_SRVR_DONE_A:
case SSL3_ST_SW_SRVR_DONE_B:
ret=ssl3_send_server_done(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
break;
case SSL3_ST_SW_FLUSH:
/* This code originally checked to see if
* any data was pending using BIO_CTRL_INFO
* and then flushed. This caused problems
* as documented in PR#1939. The proposed
* fix doesn't completely resolve this issue
* as buggy implementations of BIO_CTRL_PENDING
* still exist. So instead we just flush
* unconditionally.
*/
s->rwstate=SSL_WRITING;
if (BIO_flush(s->wbio) <= 0)
{
ret= -1;
goto end;
}
s->rwstate=SSL_NOTHING;
s->state=s->s3->tmp.next_state;
break;
case SSL3_ST_SR_CERT_A:
case SSL3_ST_SR_CERT_B:
/* Check for second client hello (MS SGC) */
ret = ssl3_check_client_hello(s);
if (ret <= 0)
goto end;
if (ret == 2)
s->state = SSL3_ST_SR_CLNT_HELLO_C;
else {
if (s->s3->tmp.cert_request)
{
ret=ssl3_get_client_certificate(s);
if (ret <= 0) goto end;
}
s->init_num=0;
s->state=SSL3_ST_SR_KEY_EXCH_A;
}
break;
case SSL3_ST_SR_KEY_EXCH_A:
case SSL3_ST_SR_KEY_EXCH_B:
ret=ssl3_get_client_key_exchange(s);
if (ret <= 0)
goto end;
if (ret == 2)
{
/* For the ECDH ciphersuites when
* the client sends its ECDH pub key in
* a certificate, the CertificateVerify
* message is not sent.
* Also for GOST ciphersuites when
* the client uses its key from the certificate
* for key exchange.
*/
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num = 0;
}
else if (TLS1_get_version(s) >= TLS1_2_VERSION)
{
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
if (!s->session->peer)
break;
/* For TLS v1.2 freeze the handshake buffer
* at this point and digest cached records.
*/
if (!s->s3->handshake_buffer)
{
SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
return -1;
}
s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
int offset=0;
int dgst_num;
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
/* We need to get hashes here so if there is
* a client cert, it can be verified
* FIXME - digest processing for CertificateVerify
* should be generalized. But it is next step
*/
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
if (s->s3->handshake_dgst[dgst_num])
{
int dgst_size;
s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
if (dgst_size < 0)
{
ret = -1;
goto end;
}
offset+=dgst_size;
}
}
break;
case SSL3_ST_SR_CERT_VRFY_A:
case SSL3_ST_SR_CERT_VRFY_B:
/* we should decide if we expected this one */
ret=ssl3_get_cert_verify(s);
if (ret <= 0) goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num=0;
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_SR_NEXT_PROTO_A:
case SSL3_ST_SR_NEXT_PROTO_B:
ret=ssl3_get_next_proto(s);
if (ret <= 0) goto end;
s->init_num = 0;
s->state=SSL3_ST_SR_FINISHED_A;
break;
#endif
case SSL3_ST_SR_FINISHED_A:
case SSL3_ST_SR_FINISHED_B:
ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
SSL3_ST_SR_FINISHED_B);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
else if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
#endif
else
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_SW_SESSION_TICKET_A:
case SSL3_ST_SW_SESSION_TICKET_B:
ret=ssl3_send_newsession_ticket(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_STATUS_A:
case SSL3_ST_SW_CERT_STATUS_B:
ret=ssl3_send_cert_status(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_KEY_EXCH_A;
s->init_num=0;
break;
#endif
case SSL3_ST_SW_CHANGE_A:
case SSL3_ST_SW_CHANGE_B:
s->session->cipher=s->s3->tmp.new_cipher;
if (!s->method->ssl3_enc->setup_key_block(s))
{ ret= -1; goto end; }
ret=ssl3_send_change_cipher_spec(s,
SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FINISHED_A;
s->init_num=0;
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_SERVER_WRITE))
{
ret= -1;
goto end;
}
break;
case SSL3_ST_SW_FINISHED_A:
case SSL3_ST_SW_FINISHED_B:
ret=ssl3_send_finished(s,
SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
s->method->ssl3_enc->server_finished_label,
s->method->ssl3_enc->server_finished_label_len);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FLUSH;
if (s->hit)
{
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#else
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#endif
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
BUF_MEM_free(s->init_buf);
s->init_buf=NULL;
/* remove buffering on output */
ssl_free_wbio_buffer(s);
s->init_num=0;
if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
{
s->renegotiate=0;
s->new_session=0;
ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
s->ctx->stats.sess_accept_good++;
/* s->server=1; */
s->handshake_func=ssl3_accept;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
}
ret = 1;
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
ret= -1;
goto end;
/* break; */
}
if (!s->s3->tmp.reuse_message && !skip)
{
if (s->debug)
{
if ((ret=BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state))
{
new_state=s->state;
s->state=state;
cb(s,SSL_CB_ACCEPT_LOOP,1);
s->state=new_state;
}
}
skip=0;
}
end:
/* BIO_flush(s->wbio); */
s->in_handshake--;
if (cb != NULL)
cb(s,SSL_CB_ACCEPT_EXIT,ret);
return(ret);
}
Commit Message:
CWE ID: CWE-310 | int ssl3_accept(SSL *s)
{
BUF_MEM *buf;
unsigned long alg_k,Time=(unsigned long)time(NULL);
void (*cb)(const SSL *ssl,int type,int val)=NULL;
int ret= -1;
int new_state,state,skip=0;
RAND_add(&Time,sizeof(Time),0);
ERR_clear_error();
clear_sys_error();
if (s->info_callback != NULL)
cb=s->info_callback;
else if (s->ctx->info_callback != NULL)
cb=s->ctx->info_callback;
/* init things to blank */
s->in_handshake++;
if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
if (s->cert == NULL)
{
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
return(-1);
}
#ifndef OPENSSL_NO_HEARTBEATS
/* If we're awaiting a HeartbeatResponse, pretend we
* already got and don't await it anymore, because
* Heartbeats don't make sense during handshakes anyway.
*/
if (s->tlsext_hb_pending)
{
s->tlsext_hb_pending = 0;
s->tlsext_hb_seq++;
}
#endif
for (;;)
{
state=s->state;
switch (s->state)
{
case SSL_ST_RENEGOTIATE:
s->renegotiate=1;
/* s->state=SSL_ST_ACCEPT; */
case SSL_ST_BEFORE:
case SSL_ST_ACCEPT:
case SSL_ST_BEFORE|SSL_ST_ACCEPT:
case SSL_ST_OK|SSL_ST_ACCEPT:
s->server=1;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
if ((s->version>>8) != 3)
{
SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
return -1;
}
s->type=SSL_ST_ACCEPT;
if (s->init_buf == NULL)
{
if ((buf=BUF_MEM_new()) == NULL)
{
ret= -1;
goto end;
}
if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
{
ret= -1;
goto end;
}
s->init_buf=buf;
}
if (!ssl3_setup_buffers(s))
{
ret= -1;
goto end;
}
s->init_num=0;
s->s3->flags &= ~SSL3_FLAGS_SGC_RESTART_DONE;
if (s->state != SSL_ST_RENEGOTIATE)
{
/* Ok, we now need to push on a buffering BIO so that
* the output is sent in a way that TCP likes :-)
*/
if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
ssl3_init_finished_mac(s);
s->state=SSL3_ST_SR_CLNT_HELLO_A;
s->ctx->stats.sess_accept++;
}
else if (!s->s3->send_connection_binding &&
!(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
{
/* Server attempting to renegotiate with
* client that doesn't support secure
* renegotiation.
*/
SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
ret = -1;
goto end;
}
else
{
/* s->state == SSL_ST_RENEGOTIATE,
* we will just send a HelloRequest */
s->ctx->stats.sess_accept_renegotiate++;
s->state=SSL3_ST_SW_HELLO_REQ_A;
}
break;
case SSL3_ST_SW_HELLO_REQ_A:
case SSL3_ST_SW_HELLO_REQ_B:
s->shutdown=0;
ret=ssl3_send_hello_request(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
ssl3_init_finished_mac(s);
break;
case SSL3_ST_SW_HELLO_REQ_C:
s->state=SSL_ST_OK;
break;
case SSL3_ST_SR_CLNT_HELLO_A:
case SSL3_ST_SR_CLNT_HELLO_B:
case SSL3_ST_SR_CLNT_HELLO_C:
s->shutdown=0;
if (s->rwstate != SSL_X509_LOOKUP)
{
ret=ssl3_get_client_hello(s);
if (ret <= 0) goto end;
}
#ifndef OPENSSL_NO_SRP
{
int al;
if ((ret = ssl_check_srp_ext_ClientHello(s,&al)) < 0)
{
/* callback indicates firther work to be done */
s->rwstate=SSL_X509_LOOKUP;
goto end;
}
if (ret != SSL_ERROR_NONE)
{
ssl3_send_alert(s,SSL3_AL_FATAL,al);
/* This is not really an error but the only means to
for a client to detect whether srp is supported. */
if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
ret = SSL_TLSEXT_ERR_ALERT_FATAL;
ret= -1;
goto end;
}
}
#endif
s->renegotiate = 2;
s->state=SSL3_ST_SW_SRVR_HELLO_A;
s->init_num=0;
break;
case SSL3_ST_SW_SRVR_HELLO_A:
case SSL3_ST_SW_SRVR_HELLO_B:
ret=ssl3_send_server_hello(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->hit)
{
if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
else
s->state=SSL3_ST_SW_CHANGE_A;
}
#else
if (s->hit)
s->state=SSL3_ST_SW_CHANGE_A;
#endif
else
s->state=SSL3_ST_SW_CERT_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_A:
case SSL3_ST_SW_CERT_B:
/* Check if it is anon DH or anon ECDH, */
/* normal PSK or KRB5 or SRP */
if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
&& !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
&& !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
{
ret=ssl3_send_server_certificate(s);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
if (s->tlsext_status_expected)
s->state=SSL3_ST_SW_CERT_STATUS_A;
else
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
else
{
skip = 1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
}
#else
}
else
skip=1;
s->state=SSL3_ST_SW_KEY_EXCH_A;
#endif
s->init_num=0;
break;
case SSL3_ST_SW_KEY_EXCH_A:
case SSL3_ST_SW_KEY_EXCH_B:
alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
/* clear this, it may get reset by
* send_server_key_exchange */
if ((s->options & SSL_OP_EPHEMERAL_RSA)
#ifndef OPENSSL_NO_KRB5
&& !(alg_k & SSL_kKRB5)
#endif /* OPENSSL_NO_KRB5 */
)
/* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
* even when forbidden by protocol specs
* (handshake may fail as clients are not required to
* be able to handle this) */
s->s3->tmp.use_rsa_tmp=1;
else
s->s3->tmp.use_rsa_tmp=0;
/* only send if a DH key exchange, fortezza or
* RSA but we have a sign only certificate
*
* PSK: may send PSK identity hints
*
* For ECC ciphersuites, we send a serverKeyExchange
* message only if the cipher suite is either
* ECDH-anon or ECDHE. In other cases, the
* server certificate contains the server's
* public key for key exchange.
*/
if (s->s3->tmp.use_rsa_tmp
/* PSK: send ServerKeyExchange if PSK identity
* hint if provided */
#ifndef OPENSSL_NO_PSK
|| ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
#endif
#ifndef OPENSSL_NO_SRP
/* SRP: send ServerKeyExchange */
|| (alg_k & SSL_kSRP)
#endif
|| (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH))
|| (alg_k & SSL_kEECDH)
|| ((alg_k & SSL_kRSA)
&& (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
|| (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
&& EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
)
)
)
)
{
ret=ssl3_send_server_key_exchange(s);
if (ret <= 0) goto end;
}
else
skip=1;
s->state=SSL3_ST_SW_CERT_REQ_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_REQ_A:
case SSL3_ST_SW_CERT_REQ_B:
if (/* don't request cert unless asked for it: */
!(s->verify_mode & SSL_VERIFY_PEER) ||
/* if SSL_VERIFY_CLIENT_ONCE is set,
* don't request cert during re-negotiation: */
((s->session->peer != NULL) &&
(s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
/* never request cert in anonymous ciphersuites
* (see section "Certificate request" in SSL 3 drafts
* and in RFC 2246): */
((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
/* ... except when the application insists on verification
* (against the specs, but s3_clnt.c accepts this for SSL 3) */
!(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
/* never request cert in Kerberos ciphersuites */
(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)
/* With normal PSK Certificates and
* Certificate Requests are omitted */
|| (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
{
/* no cert request */
skip=1;
s->s3->tmp.cert_request=0;
s->state=SSL3_ST_SW_SRVR_DONE_A;
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
s->s3->tmp.cert_request=1;
ret=ssl3_send_certificate_request(s);
if (ret <= 0) goto end;
#ifndef NETSCAPE_HANG_BUG
s->state=SSL3_ST_SW_SRVR_DONE_A;
#else
s->state=SSL3_ST_SW_FLUSH;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
#endif
s->init_num=0;
}
break;
case SSL3_ST_SW_SRVR_DONE_A:
case SSL3_ST_SW_SRVR_DONE_B:
ret=ssl3_send_server_done(s);
if (ret <= 0) goto end;
s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
s->state=SSL3_ST_SW_FLUSH;
s->init_num=0;
break;
case SSL3_ST_SW_FLUSH:
/* This code originally checked to see if
* any data was pending using BIO_CTRL_INFO
* and then flushed. This caused problems
* as documented in PR#1939. The proposed
* fix doesn't completely resolve this issue
* as buggy implementations of BIO_CTRL_PENDING
* still exist. So instead we just flush
* unconditionally.
*/
s->rwstate=SSL_WRITING;
if (BIO_flush(s->wbio) <= 0)
{
ret= -1;
goto end;
}
s->rwstate=SSL_NOTHING;
s->state=s->s3->tmp.next_state;
break;
case SSL3_ST_SR_CERT_A:
case SSL3_ST_SR_CERT_B:
/* Check for second client hello (MS SGC) */
ret = ssl3_check_client_hello(s);
if (ret <= 0)
goto end;
if (ret == 2)
s->state = SSL3_ST_SR_CLNT_HELLO_C;
else {
if (s->s3->tmp.cert_request)
{
ret=ssl3_get_client_certificate(s);
if (ret <= 0) goto end;
}
s->init_num=0;
s->state=SSL3_ST_SR_KEY_EXCH_A;
}
break;
case SSL3_ST_SR_KEY_EXCH_A:
case SSL3_ST_SR_KEY_EXCH_B:
ret=ssl3_get_client_key_exchange(s);
if (ret <= 0)
goto end;
if (ret == 2)
{
/* For the ECDH ciphersuites when
* the client sends its ECDH pub key in
* a certificate, the CertificateVerify
* message is not sent.
* Also for GOST ciphersuites when
* the client uses its key from the certificate
* for key exchange.
*/
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num = 0;
}
else if (TLS1_get_version(s) >= TLS1_2_VERSION)
{
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
if (!s->session->peer)
break;
/* For TLS v1.2 freeze the handshake buffer
* at this point and digest cached records.
*/
if (!s->s3->handshake_buffer)
{
SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
return -1;
}
s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
if (!ssl3_digest_cached_records(s))
return -1;
}
else
{
int offset=0;
int dgst_num;
s->state=SSL3_ST_SR_CERT_VRFY_A;
s->init_num=0;
/* We need to get hashes here so if there is
* a client cert, it can be verified
* FIXME - digest processing for CertificateVerify
* should be generalized. But it is next step
*/
if (s->s3->handshake_buffer)
if (!ssl3_digest_cached_records(s))
return -1;
for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)
if (s->s3->handshake_dgst[dgst_num])
{
int dgst_size;
s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
if (dgst_size < 0)
{
ret = -1;
goto end;
}
offset+=dgst_size;
}
}
break;
case SSL3_ST_SR_CERT_VRFY_A:
case SSL3_ST_SR_CERT_VRFY_B:
s->s3->flags |= SSL3_FLAGS_CCS_OK;
/* we should decide if we expected this one */
ret=ssl3_get_cert_verify(s);
if (ret <= 0) goto end;
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
s->state=SSL3_ST_SR_NEXT_PROTO_A;
else
s->state=SSL3_ST_SR_FINISHED_A;
#endif
s->init_num=0;
break;
#if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
case SSL3_ST_SR_NEXT_PROTO_A:
case SSL3_ST_SR_NEXT_PROTO_B:
ret=ssl3_get_next_proto(s);
if (ret <= 0) goto end;
s->init_num = 0;
s->state=SSL3_ST_SR_FINISHED_A;
break;
#endif
case SSL3_ST_SR_FINISHED_A:
case SSL3_ST_SR_FINISHED_B:
s->s3->flags |= SSL3_FLAGS_CCS_OK;
ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
SSL3_ST_SR_FINISHED_B);
if (ret <= 0) goto end;
#ifndef OPENSSL_NO_TLSEXT
else if (s->tlsext_ticket_expected)
s->state=SSL3_ST_SW_SESSION_TICKET_A;
#endif
else
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
#ifndef OPENSSL_NO_TLSEXT
case SSL3_ST_SW_SESSION_TICKET_A:
case SSL3_ST_SW_SESSION_TICKET_B:
ret=ssl3_send_newsession_ticket(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_CHANGE_A;
s->init_num=0;
break;
case SSL3_ST_SW_CERT_STATUS_A:
case SSL3_ST_SW_CERT_STATUS_B:
ret=ssl3_send_cert_status(s);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_KEY_EXCH_A;
s->init_num=0;
break;
#endif
case SSL3_ST_SW_CHANGE_A:
case SSL3_ST_SW_CHANGE_B:
s->session->cipher=s->s3->tmp.new_cipher;
if (!s->method->ssl3_enc->setup_key_block(s))
{ ret= -1; goto end; }
ret=ssl3_send_change_cipher_spec(s,
SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FINISHED_A;
s->init_num=0;
if (!s->method->ssl3_enc->change_cipher_state(s,
SSL3_CHANGE_CIPHER_SERVER_WRITE))
{
ret= -1;
goto end;
}
break;
case SSL3_ST_SW_FINISHED_A:
case SSL3_ST_SW_FINISHED_B:
ret=ssl3_send_finished(s,
SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
s->method->ssl3_enc->server_finished_label,
s->method->ssl3_enc->server_finished_label_len);
if (ret <= 0) goto end;
s->state=SSL3_ST_SW_FLUSH;
if (s->hit)
{
#if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#else
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#else
if (s->s3->next_proto_neg_seen)
{
s->s3->flags |= SSL3_FLAGS_CCS_OK;
s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
}
else
s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
#endif
case SSL_ST_OK:
/* clean a few things up */
ssl3_cleanup_key_block(s);
BUF_MEM_free(s->init_buf);
s->init_buf=NULL;
/* remove buffering on output */
ssl_free_wbio_buffer(s);
s->init_num=0;
if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
{
s->renegotiate=0;
s->new_session=0;
ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
s->ctx->stats.sess_accept_good++;
/* s->server=1; */
s->handshake_func=ssl3_accept;
if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
}
ret = 1;
goto end;
/* break; */
default:
SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
ret= -1;
goto end;
/* break; */
}
if (!s->s3->tmp.reuse_message && !skip)
{
if (s->debug)
{
if ((ret=BIO_flush(s->wbio)) <= 0)
goto end;
}
if ((cb != NULL) && (s->state != state))
{
new_state=s->state;
s->state=state;
cb(s,SSL_CB_ACCEPT_LOOP,1);
s->state=new_state;
}
}
skip=0;
}
end:
/* BIO_flush(s->wbio); */
s->in_handshake--;
if (cb != NULL)
cb(s,SSL_CB_ACCEPT_EXIT,ret);
return(ret);
}
| 165,281 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(interstitial_page);
render_manager_.set_interstitial_page(interstitial_page);
FOR_EACH_OBSERVER(WebContentsObserver, observers_,
DidAttachInterstitialPage());
}
Commit Message: Cancel JavaScript dialogs when an interstitial appears.
BUG=295695
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/24360011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@225026 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void WebContentsImpl::AttachInterstitialPage(
InterstitialPageImpl* interstitial_page) {
DCHECK(interstitial_page);
render_manager_.set_interstitial_page(interstitial_page);
// Cancel any visible dialogs so that they don't interfere with the
// interstitial.
if (dialog_manager_)
dialog_manager_->CancelActiveAndPendingDialogs(this);
FOR_EACH_OBSERVER(WebContentsObserver, observers_,
DidAttachInterstitialPage());
}
| 171,160 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void mark_commit(struct commit *c, void *data)
{
mark_object(&c->object, NULL, NULL, data);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static void mark_commit(struct commit *c, void *data)
{
mark_object(&c->object, NULL, data);
}
| 167,424 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool do_write_pids(pid_t tpid, const char *contrl, const char *cg, const char *file, const char *buf)
{
int sock[2] = {-1, -1};
pid_t qpid, cpid = -1;
FILE *pids_file = NULL;
bool answer = false, fail = false;
pids_file = open_pids_file(contrl, cg);
if (!pids_file)
return false;
/*
* write the pids to a socket, have helper in writer's pidns
* call movepid for us
*/
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) {
perror("socketpair");
goto out;
}
cpid = fork();
if (cpid == -1)
goto out;
if (!cpid) { // child
fclose(pids_file);
pid_from_ns_wrapper(sock[1], tpid);
}
const char *ptr = buf;
while (sscanf(ptr, "%d", &qpid) == 1) {
struct ucred cred;
char v;
if (write(sock[0], &qpid, sizeof(qpid)) != sizeof(qpid)) {
fprintf(stderr, "%s: error writing pid to child: %s\n",
__func__, strerror(errno));
goto out;
}
if (recv_creds(sock[0], &cred, &v)) {
if (v == '0') {
if (fprintf(pids_file, "%d", (int) cred.pid) < 0)
fail = true;
}
}
ptr = strchr(ptr, '\n');
if (!ptr)
break;
ptr++;
}
/* All good, write the value */
qpid = -1;
if (write(sock[0], &qpid ,sizeof(qpid)) != sizeof(qpid))
fprintf(stderr, "Warning: failed to ask child to exit\n");
if (!fail)
answer = true;
out:
if (cpid != -1)
wait_for_pid(cpid);
if (sock[0] != -1) {
close(sock[0]);
close(sock[1]);
}
if (pids_file) {
if (fclose(pids_file) != 0)
answer = false;
}
return answer;
}
Commit Message: Implement privilege check when moving tasks
When writing pids to a tasks file in lxcfs, lxcfs was checking
for privilege over the tasks file but not over the pid being
moved. Since the cgm_movepid request is done as root on the host,
not with the requestor's credentials, we must copy the check which
cgmanager was doing to ensure that the requesting task is allowed
to change the victim task's cgroup membership.
This is CVE-2015-1344
https://bugs.launchpad.net/ubuntu/+source/lxcfs/+bug/1512854
Signed-off-by: Serge Hallyn <[email protected]>
CWE ID: CWE-264 | static bool do_write_pids(pid_t tpid, const char *contrl, const char *cg, const char *file, const char *buf)
/*
* Given host @uid, return the uid to which it maps in
* @pid's user namespace, or -1 if none.
*/
bool hostuid_to_ns(uid_t uid, pid_t pid, uid_t *answer)
{
FILE *f;
char line[400];
sprintf(line, "/proc/%d/uid_map", pid);
if ((f = fopen(line, "r")) == NULL) {
return false;
}
*answer = convert_id_to_ns(f, uid);
fclose(f);
if (*answer == -1)
return false;
return true;
}
/*
* get_pid_creds: get the real uid and gid of @pid from
* /proc/$$/status
* (XXX should we use euid here?)
*/
void get_pid_creds(pid_t pid, uid_t *uid, gid_t *gid)
{
char line[400];
uid_t u;
gid_t g;
FILE *f;
*uid = -1;
*gid = -1;
sprintf(line, "/proc/%d/status", pid);
if ((f = fopen(line, "r")) == NULL) {
fprintf(stderr, "Error opening %s: %s\n", line, strerror(errno));
return;
}
while (fgets(line, 400, f)) {
if (strncmp(line, "Uid:", 4) == 0) {
if (sscanf(line+4, "%u", &u) != 1) {
fprintf(stderr, "bad uid line for pid %u\n", pid);
fclose(f);
return;
}
*uid = u;
} else if (strncmp(line, "Gid:", 4) == 0) {
if (sscanf(line+4, "%u", &g) != 1) {
fprintf(stderr, "bad gid line for pid %u\n", pid);
fclose(f);
return;
}
*gid = g;
}
}
fclose(f);
}
/*
* May the requestor @r move victim @v to a new cgroup?
* This is allowed if
* . they are the same task
* . they are ownedy by the same uid
* . @r is root on the host, or
* . @v's uid is mapped into @r's where @r is root.
*/
bool may_move_pid(pid_t r, uid_t r_uid, pid_t v)
{
uid_t v_uid, tmpuid;
gid_t v_gid;
if (r == v)
return true;
if (r_uid == 0)
return true;
get_pid_creds(v, &v_uid, &v_gid);
if (r_uid == v_uid)
return true;
if (hostuid_to_ns(r_uid, r, &tmpuid) && tmpuid == 0
&& hostuid_to_ns(v_uid, r, &tmpuid))
return true;
return false;
}
static bool do_write_pids(pid_t tpid, uid_t tuid, const char *contrl, const char *cg,
const char *file, const char *buf)
{
int sock[2] = {-1, -1};
pid_t qpid, cpid = -1;
FILE *pids_file = NULL;
bool answer = false, fail = false;
pids_file = open_pids_file(contrl, cg);
if (!pids_file)
return false;
/*
* write the pids to a socket, have helper in writer's pidns
* call movepid for us
*/
if (socketpair(AF_UNIX, SOCK_DGRAM, 0, sock) < 0) {
perror("socketpair");
goto out;
}
cpid = fork();
if (cpid == -1)
goto out;
if (!cpid) { // child
fclose(pids_file);
pid_from_ns_wrapper(sock[1], tpid);
}
const char *ptr = buf;
while (sscanf(ptr, "%d", &qpid) == 1) {
struct ucred cred;
char v;
if (write(sock[0], &qpid, sizeof(qpid)) != sizeof(qpid)) {
fprintf(stderr, "%s: error writing pid to child: %s\n",
__func__, strerror(errno));
goto out;
}
if (recv_creds(sock[0], &cred, &v)) {
if (v == '0') {
if (!may_move_pid(tpid, tuid, cred.pid)) {
fail = true;
break;
}
if (fprintf(pids_file, "%d", (int) cred.pid) < 0)
fail = true;
}
}
ptr = strchr(ptr, '\n');
if (!ptr)
break;
ptr++;
}
/* All good, write the value */
qpid = -1;
if (write(sock[0], &qpid ,sizeof(qpid)) != sizeof(qpid))
fprintf(stderr, "Warning: failed to ask child to exit\n");
if (!fail)
answer = true;
out:
if (cpid != -1)
wait_for_pid(cpid);
if (sock[0] != -1) {
close(sock[0]);
close(sock[1]);
}
if (pids_file) {
if (fclose(pids_file) != 0)
answer = false;
}
return answer;
}
| 166,702 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
ContentViewCoreImpl* content_view_core)
: host_(widget_host),
is_layer_attached_(true),
content_view_core_(NULL),
ime_adapter_android_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
cached_background_color_(SK_ColorWHITE),
texture_id_in_layer_(0) {
if (CompositorImpl::UsesDirectGL()) {
surface_texture_transport_.reset(new SurfaceTextureTransportClient());
layer_ = surface_texture_transport_->Initialize();
} else {
texture_layer_ = cc::TextureLayer::create(0);
layer_ = texture_layer_;
}
layer_->setContentsOpaque(true);
layer_->setIsDrawable(true);
host_->SetView(this);
SetContentViewCore(content_view_core);
}
Commit Message: Implement TextureImageTransportSurface using texture mailbox
This has a couple of advantages:
- allow tearing down and recreating the UI parent context without
losing the renderer contexts
- do not require a context to be able to generate textures when
creating the GLSurfaceHandle
- clearer ownership semantics that potentially allows for more
robust and easier lost context handling/thumbnailing/etc., since a texture is at
any given time owned by either: UI parent, mailbox, or
TextureImageTransportSurface
- simplify frontbuffer protection logic;
the frontbuffer textures are now owned by RWHV where they are refcounted
The TextureImageTransportSurface informs RenderWidgetHostView of the
mailbox names for the front- and backbuffer textures by
associating them with a surface_handle (1 or 2) in the AcceleratedSurfaceNew message.
During SwapBuffers() or PostSubBuffer() cycles, it then uses
produceTextureCHROMIUM() and consumeTextureCHROMIUM()
to transfer ownership between renderer and browser compositor.
RWHV sends back the surface_handle of the buffer being returned with the Swap ACK
(or 0 if no buffer is being returned in which case TextureImageTransportSurface will
allocate a new texture - note that this could be used to
simply keep textures for thumbnailing).
BUG=154815,139616
[email protected]
Review URL: https://chromiumcodereview.appspot.com/11194042
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@171569 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | RenderWidgetHostViewAndroid::RenderWidgetHostViewAndroid(
RenderWidgetHostImpl* widget_host,
ContentViewCoreImpl* content_view_core)
: host_(widget_host),
is_layer_attached_(true),
content_view_core_(NULL),
ime_adapter_android_(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
cached_background_color_(SK_ColorWHITE),
texture_id_in_layer_(0),
current_buffer_id_(0) {
if (CompositorImpl::UsesDirectGL()) {
surface_texture_transport_.reset(new SurfaceTextureTransportClient());
layer_ = surface_texture_transport_->Initialize();
} else {
texture_layer_ = cc::TextureLayer::create(0);
layer_ = texture_layer_;
}
layer_->setContentsOpaque(true);
layer_->setIsDrawable(true);
host_->SetView(this);
SetContentViewCore(content_view_core);
}
| 171,370 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static bool IsManualFallbackForFillingEnabled() {
return base::FeatureList::IsEnabled(
password_manager::features::kEnableManualFallbacksFilling) &&
!IsPreLollipopAndroid();
}
Commit Message: Fixing names of password_manager kEnableManualFallbacksFilling feature.
Fixing names of password_manager kEnableManualFallbacksFilling feature
as per the naming convention.
Bug: 785953
Change-Id: I4a4baa1649fe9f02c3783a5e4c40bc75e717cc03
Reviewed-on: https://chromium-review.googlesource.com/900566
Reviewed-by: Vaclav Brozek <[email protected]>
Commit-Queue: NIKHIL SAHNI <[email protected]>
Cr-Commit-Position: refs/heads/master@{#534923}
CWE ID: CWE-264 | static bool IsManualFallbackForFillingEnabled() {
return base::FeatureList::IsEnabled(
password_manager::features::kManualFallbacksFilling) &&
!IsPreLollipopAndroid();
}
| 171,748 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ConnectPanelServiceSignals() {
if (!ibus_) {
return;
}
IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE(
g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey));
if (!ibus_panel_service) {
LOG(ERROR) << "IBusPanelService is NOT available.";
return;
}
g_signal_connect(ibus_panel_service,
"focus-in",
G_CALLBACK(FocusInCallback),
this);
g_signal_connect(ibus_panel_service,
"register-properties",
G_CALLBACK(RegisterPropertiesCallback),
this);
g_signal_connect(ibus_panel_service,
"update-property",
G_CALLBACK(UpdatePropertyCallback),
this);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void ConnectPanelServiceSignals() {
if (!ibus_) {
return;
}
IBusPanelService* ibus_panel_service = IBUS_PANEL_SERVICE(
g_object_get_data(G_OBJECT(ibus_), kPanelObjectKey));
if (!ibus_panel_service) {
LOG(ERROR) << "IBusPanelService is NOT available.";
return;
}
g_signal_connect(ibus_panel_service,
"focus-in",
G_CALLBACK(FocusInThunk),
this);
g_signal_connect(ibus_panel_service,
"register-properties",
G_CALLBACK(RegisterPropertiesThunk),
this);
g_signal_connect(ibus_panel_service,
"update-property",
G_CALLBACK(UpdatePropertyThunk),
this);
}
| 170,530 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host,
const base::string16& message,
const base::string16& default_prompt,
const GURL& frame_url,
JavaScriptDialogType dialog_type,
IPC::Message* reply_msg) {
bool suppress_this_message =
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (!suppress_this_message) {
is_showing_javascript_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunJavaScriptDialog(
this, frame_url, dialog_type, message, default_prompt,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg, false),
&suppress_this_message);
}
if (suppress_this_message) {
OnDialogClosed(render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
true, false, base::string16());
}
}
Commit Message: If JavaScript shows a dialog, cause the page to lose fullscreen.
BUG=670135, 550017, 726761, 728276
Review-Url: https://codereview.chromium.org/2906133004
Cr-Commit-Position: refs/heads/master@{#478884}
CWE ID: CWE-20 | void WebContentsImpl::RunJavaScriptDialog(RenderFrameHost* render_frame_host,
const base::string16& message,
const base::string16& default_prompt,
const GURL& frame_url,
JavaScriptDialogType dialog_type,
IPC::Message* reply_msg) {
// Running a dialog causes an exit to webpage-initiated fullscreen.
// http://crbug.com/728276
if (IsFullscreenForCurrentTab())
ExitFullscreen(true);
bool suppress_this_message =
ShowingInterstitialPage() || !delegate_ ||
delegate_->ShouldSuppressDialogs(this) ||
!delegate_->GetJavaScriptDialogManager(this);
if (!suppress_this_message) {
is_showing_javascript_dialog_ = true;
dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
dialog_manager_->RunJavaScriptDialog(
this, frame_url, dialog_type, message, default_prompt,
base::Bind(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg, false),
&suppress_this_message);
}
if (suppress_this_message) {
OnDialogClosed(render_frame_host->GetProcess()->GetID(),
render_frame_host->GetRoutingID(), reply_msg,
true, false, base::string16());
}
}
| 172,316 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int handle_ldf_stq(u32 insn, struct pt_regs *regs)
{
unsigned long addr = compute_effective_address(regs, insn, 0);
int freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
struct fpustate *f = FPUSTATE;
int asi = decode_asi(insn, regs);
int flag = (freg < 32) ? FPRS_DL : FPRS_DU;
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, 0, regs, 0);
save_and_clear_fpu();
current_thread_info()->xfsr[0] &= ~0x1c000;
if (freg & 3) {
current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */;
do_fpother(regs);
return 0;
}
if (insn & 0x200000) {
/* STQ */
u64 first = 0, second = 0;
if (current_thread_info()->fpsaved[0] & flag) {
first = *(u64 *)&f->regs[freg];
second = *(u64 *)&f->regs[freg+2];
}
if (asi < 0x80) {
do_privact(regs);
return 1;
}
switch (asi) {
case ASI_P:
case ASI_S: break;
case ASI_PL:
case ASI_SL:
{
/* Need to convert endians */
u64 tmp = __swab64p(&first);
first = __swab64p(&second);
second = tmp;
break;
}
default:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (put_user (first >> 32, (u32 __user *)addr) ||
__put_user ((u32)first, (u32 __user *)(addr + 4)) ||
__put_user (second >> 32, (u32 __user *)(addr + 8)) ||
__put_user ((u32)second, (u32 __user *)(addr + 12))) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
} else {
/* LDF, LDDF, LDQF */
u32 data[4] __attribute__ ((aligned(8)));
int size, i;
int err;
if (asi < 0x80) {
do_privact(regs);
return 1;
} else if (asi > ASI_SNFL) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
switch (insn & 0x180000) {
case 0x000000: size = 1; break;
case 0x100000: size = 4; break;
default: size = 2; break;
}
for (i = 0; i < size; i++)
data[i] = 0;
err = get_user (data[0], (u32 __user *) addr);
if (!err) {
for (i = 1; i < size; i++)
err |= __get_user (data[i], (u32 __user *)(addr + 4*i));
}
if (err && !(asi & 0x2 /* NF */)) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (asi & 0x8) /* Little */ {
u64 tmp;
switch (size) {
case 1: data[0] = le32_to_cpup(data + 0); break;
default:*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 0));
break;
case 4: tmp = le64_to_cpup((u64 *)(data + 0));
*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 2));
*(u64 *)(data + 2) = tmp;
break;
}
}
if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) {
current_thread_info()->fpsaved[0] = FPRS_FEF;
current_thread_info()->gsr[0] = 0;
}
if (!(current_thread_info()->fpsaved[0] & flag)) {
if (freg < 32)
memset(f->regs, 0, 32*sizeof(u32));
else
memset(f->regs+32, 0, 32*sizeof(u32));
}
memcpy(f->regs + freg, data, size * 4);
current_thread_info()->fpsaved[0] |= flag;
}
advance(regs);
return 1;
}
Commit Message: perf: Remove the nmi parameter from the swevent and overflow interface
The nmi parameter indicated if we could do wakeups from the current
context, if not, we would set some state and self-IPI and let the
resulting interrupt do the wakeup.
For the various event classes:
- hardware: nmi=0; PMI is in fact an NMI or we run irq_work_run from
the PMI-tail (ARM etc.)
- tracepoint: nmi=0; since tracepoint could be from NMI context.
- software: nmi=[0,1]; some, like the schedule thing cannot
perform wakeups, and hence need 0.
As one can see, there is very little nmi=1 usage, and the down-side of
not using it is that on some platforms some software events can have a
jiffy delay in wakeup (when arch_irq_work_raise isn't implemented).
The up-side however is that we can remove the nmi parameter and save a
bunch of conditionals in fast paths.
Signed-off-by: Peter Zijlstra <[email protected]>
Cc: Michael Cree <[email protected]>
Cc: Will Deacon <[email protected]>
Cc: Deng-Cheng Zhu <[email protected]>
Cc: Anton Blanchard <[email protected]>
Cc: Eric B Munson <[email protected]>
Cc: Heiko Carstens <[email protected]>
Cc: Paul Mundt <[email protected]>
Cc: David S. Miller <[email protected]>
Cc: Frederic Weisbecker <[email protected]>
Cc: Jason Wessel <[email protected]>
Cc: Don Zickus <[email protected]>
Link: http://lkml.kernel.org/n/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-399 | int handle_ldf_stq(u32 insn, struct pt_regs *regs)
{
unsigned long addr = compute_effective_address(regs, insn, 0);
int freg = ((insn >> 25) & 0x1e) | ((insn >> 20) & 0x20);
struct fpustate *f = FPUSTATE;
int asi = decode_asi(insn, regs);
int flag = (freg < 32) ? FPRS_DL : FPRS_DU;
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, 1, regs, 0);
save_and_clear_fpu();
current_thread_info()->xfsr[0] &= ~0x1c000;
if (freg & 3) {
current_thread_info()->xfsr[0] |= (6 << 14) /* invalid_fp_register */;
do_fpother(regs);
return 0;
}
if (insn & 0x200000) {
/* STQ */
u64 first = 0, second = 0;
if (current_thread_info()->fpsaved[0] & flag) {
first = *(u64 *)&f->regs[freg];
second = *(u64 *)&f->regs[freg+2];
}
if (asi < 0x80) {
do_privact(regs);
return 1;
}
switch (asi) {
case ASI_P:
case ASI_S: break;
case ASI_PL:
case ASI_SL:
{
/* Need to convert endians */
u64 tmp = __swab64p(&first);
first = __swab64p(&second);
second = tmp;
break;
}
default:
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (put_user (first >> 32, (u32 __user *)addr) ||
__put_user ((u32)first, (u32 __user *)(addr + 4)) ||
__put_user (second >> 32, (u32 __user *)(addr + 8)) ||
__put_user ((u32)second, (u32 __user *)(addr + 12))) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
} else {
/* LDF, LDDF, LDQF */
u32 data[4] __attribute__ ((aligned(8)));
int size, i;
int err;
if (asi < 0x80) {
do_privact(regs);
return 1;
} else if (asi > ASI_SNFL) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
switch (insn & 0x180000) {
case 0x000000: size = 1; break;
case 0x100000: size = 4; break;
default: size = 2; break;
}
for (i = 0; i < size; i++)
data[i] = 0;
err = get_user (data[0], (u32 __user *) addr);
if (!err) {
for (i = 1; i < size; i++)
err |= __get_user (data[i], (u32 __user *)(addr + 4*i));
}
if (err && !(asi & 0x2 /* NF */)) {
if (tlb_type == hypervisor)
sun4v_data_access_exception(regs, addr, 0);
else
spitfire_data_access_exception(regs, 0, addr);
return 1;
}
if (asi & 0x8) /* Little */ {
u64 tmp;
switch (size) {
case 1: data[0] = le32_to_cpup(data + 0); break;
default:*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 0));
break;
case 4: tmp = le64_to_cpup((u64 *)(data + 0));
*(u64 *)(data + 0) = le64_to_cpup((u64 *)(data + 2));
*(u64 *)(data + 2) = tmp;
break;
}
}
if (!(current_thread_info()->fpsaved[0] & FPRS_FEF)) {
current_thread_info()->fpsaved[0] = FPRS_FEF;
current_thread_info()->gsr[0] = 0;
}
if (!(current_thread_info()->fpsaved[0] & flag)) {
if (freg < 32)
memset(f->regs, 0, 32*sizeof(u32));
else
memset(f->regs+32, 0, 32*sizeof(u32));
}
memcpy(f->regs + freg, data, size * 4);
current_thread_info()->fpsaved[0] |= flag;
}
advance(regs);
return 1;
}
| 165,809 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static MagickBooleanType GetMagickModulePath(const char *filename,
MagickModuleType module_type,char *path,ExceptionInfo *exception)
{
char
*module_path;
assert(filename != (const char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
assert(path != (char *) NULL);
assert(exception != (ExceptionInfo *) NULL);
(void) CopyMagickString(path,filename,MaxTextExtent);
module_path=(char *) NULL;
switch (module_type)
{
case MagickImageCoderModule:
default:
{
(void) LogMagickEvent(ModuleEvent,GetMagickModule(),
"Searching for coder module file \"%s\" ...",filename);
module_path=GetEnvironmentValue("MAGICK_CODER_MODULE_PATH");
#if defined(MAGICKCORE_CODER_PATH)
if (module_path == (char *) NULL)
module_path=AcquireString(MAGICKCORE_CODER_PATH);
#endif
break;
}
case MagickImageFilterModule:
{
(void) LogMagickEvent(ModuleEvent,GetMagickModule(),
"Searching for filter module file \"%s\" ...",filename);
module_path=GetEnvironmentValue("MAGICK_CODER_FILTER_PATH");
#if defined(MAGICKCORE_FILTER_PATH)
if (module_path == (char *) NULL)
module_path=AcquireString(MAGICKCORE_FILTER_PATH);
#endif
break;
}
}
if (module_path != (char *) NULL)
{
register char
*p,
*q;
for (p=module_path-1; p != (char *) NULL; )
{
(void) CopyMagickString(path,p+1,MaxTextExtent);
q=strchr(path,DirectoryListSeparator);
if (q != (char *) NULL)
*q='\0';
q=path+strlen(path)-1;
if ((q >= path) && (*q != *DirectorySeparator))
(void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);
(void) ConcatenateMagickString(path,filename,MaxTextExtent);
if (IsPathAccessible(path) != MagickFalse)
{
module_path=DestroyString(module_path);
return(MagickTrue);
}
p=strchr(p+1,DirectoryListSeparator);
}
module_path=DestroyString(module_path);
}
#if defined(MAGICKCORE_INSTALLED_SUPPORT)
else
#if defined(MAGICKCORE_CODER_PATH)
{
const char
*directory;
/*
Search hard coded paths.
*/
switch (module_type)
{
case MagickImageCoderModule:
default:
{
directory=MAGICKCORE_CODER_PATH;
break;
}
case MagickImageFilterModule:
{
directory=MAGICKCORE_FILTER_PATH;
break;
}
}
(void) FormatLocaleString(path,MaxTextExtent,"%s%s",directory,filename);
if (IsPathAccessible(path) == MagickFalse)
{
ThrowFileException(exception,ConfigureWarning,
"UnableToOpenModuleFile",path);
return(MagickFalse);
}
return(MagickTrue);
}
#else
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
{
const char
*registery_key;
unsigned char
*key_value;
/*
Locate path via registry key.
*/
switch (module_type)
{
case MagickImageCoderModule:
default:
{
registery_key="CoderModulesPath";
break;
}
case MagickImageFilterModule:
{
registery_key="FilterModulesPath";
break;
}
}
key_value=NTRegistryKeyLookup(registery_key);
if (key_value == (unsigned char *) NULL)
{
ThrowMagickException(exception,GetMagickModule(),ConfigureError,
"RegistryKeyLookupFailed","`%s'",registery_key);
return(MagickFalse);
}
(void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",(char *) key_value,
DirectorySeparator,filename);
key_value=(unsigned char *) RelinquishMagickMemory(key_value);
if (IsPathAccessible(path) == MagickFalse)
{
ThrowFileException(exception,ConfigureWarning,
"UnableToOpenModuleFile",path);
return(MagickFalse);
}
return(MagickTrue);
}
#endif
#endif
#if !defined(MAGICKCORE_CODER_PATH) && !defined(MAGICKCORE_WINDOWS_SUPPORT)
# error MAGICKCORE_CODER_PATH or MAGICKCORE_WINDOWS_SUPPORT must be defined when MAGICKCORE_INSTALLED_SUPPORT is defined
#endif
#else
{
char
*home;
home=GetEnvironmentValue("MAGICK_HOME");
if (home != (char *) NULL)
{
/*
Search MAGICK_HOME.
*/
#if !defined(MAGICKCORE_POSIX_SUPPORT)
(void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",home,
DirectorySeparator,filename);
#else
const char
*directory;
switch (module_type)
{
case MagickImageCoderModule:
default:
{
directory=MAGICKCORE_CODER_RELATIVE_PATH;
break;
}
case MagickImageFilterModule:
{
directory=MAGICKCORE_FILTER_RELATIVE_PATH;
break;
}
}
(void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s",home,
directory,filename);
#endif
home=DestroyString(home);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
}
if (*GetClientPath() != '\0')
{
/*
Search based on executable directory.
*/
#if !defined(MAGICKCORE_POSIX_SUPPORT)
(void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",GetClientPath(),
DirectorySeparator,filename);
#else
char
prefix[MaxTextExtent];
const char
*directory;
switch (module_type)
{
case MagickImageCoderModule:
default:
{
directory="coders";
break;
}
case MagickImageFilterModule:
{
directory="filters";
break;
}
}
(void) CopyMagickString(prefix,GetClientPath(),MaxTextExtent);
ChopPathComponents(prefix,1);
(void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s/%s",prefix,
MAGICKCORE_MODULES_RELATIVE_PATH,directory,filename);
#endif
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
{
/*
Search module path.
*/
if ((NTGetModulePath("CORE_RL_magick_.dll",path) != MagickFalse) ||
(NTGetModulePath("CORE_DB_magick_.dll",path) != MagickFalse) ||
(NTGetModulePath("Magick.dll",path) != MagickFalse))
{
(void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);
(void) ConcatenateMagickString(path,filename,MaxTextExtent);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
}
#endif
{
char
*home;
home=GetEnvironmentValue("XDG_CONFIG_HOME");
if (home == (char *) NULL)
home=GetEnvironmentValue("LOCALAPPDATA");
if (home == (char *) NULL)
home=GetEnvironmentValue("APPDATA");
if (home == (char *) NULL)
home=GetEnvironmentValue("USERPROFILE");
if (home != (char *) NULL)
{
/*
Search $XDG_CONFIG_HOME/ImageMagick.
*/
(void) FormatLocaleString(path,MaxTextExtent,"%s%sImageMagick%s%s",
home,DirectorySeparator,DirectorySeparator,filename);
home=DestroyString(home);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
home=GetEnvironmentValue("HOME");
if (home != (char *) NULL)
{
/*
Search $HOME/.config/ImageMagick.
*/
(void) FormatLocaleString(path,MaxTextExtent,
"%s%s.config%sImageMagick%s%s",home,DirectorySeparator,
DirectorySeparator,DirectorySeparator,filename);
if (IsPathAccessible(path) != MagickFalse)
{
home=DestroyString(home);
return(MagickTrue);
}
/*
Search $HOME/.magick.
*/
(void) FormatLocaleString(path,MaxTextExtent,"%s%s.magick%s%s",home,
DirectorySeparator,DirectorySeparator,filename);
home=DestroyString(home);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
}
/*
Search current directory.
*/
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
if (exception->severity < ConfigureError)
ThrowFileException(exception,ConfigureWarning,"UnableToOpenModuleFile",
path);
#endif
return(MagickFalse);
}
Commit Message: Coder path traversal is not authorized, bug report provided by Masaaki Chida
CWE ID: CWE-22 | static MagickBooleanType GetMagickModulePath(const char *filename,
MagickModuleType module_type,char *path,ExceptionInfo *exception)
{
char
*module_path;
assert(filename != (const char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",filename);
assert(path != (char *) NULL);
assert(exception != (ExceptionInfo *) NULL);
(void) CopyMagickString(path,filename,MaxTextExtent);
#if defined(MAGICKCORE_INSTALLED_SUPPORT)
if (strstr(path,"../") != (char *) NULL)
{
errno=EPERM;
(void) ThrowMagickException(exception,GetMagickModule(),PolicyError,
"NotAuthorized","`%s'",path);
return(MagickFalse);
}
#endif
module_path=(char *) NULL;
switch (module_type)
{
case MagickImageCoderModule:
default:
{
(void) LogMagickEvent(ModuleEvent,GetMagickModule(),
"Searching for coder module file \"%s\" ...",filename);
module_path=GetEnvironmentValue("MAGICK_CODER_MODULE_PATH");
#if defined(MAGICKCORE_CODER_PATH)
if (module_path == (char *) NULL)
module_path=AcquireString(MAGICKCORE_CODER_PATH);
#endif
break;
}
case MagickImageFilterModule:
{
(void) LogMagickEvent(ModuleEvent,GetMagickModule(),
"Searching for filter module file \"%s\" ...",filename);
module_path=GetEnvironmentValue("MAGICK_CODER_FILTER_PATH");
#if defined(MAGICKCORE_FILTER_PATH)
if (module_path == (char *) NULL)
module_path=AcquireString(MAGICKCORE_FILTER_PATH);
#endif
break;
}
}
if (module_path != (char *) NULL)
{
register char
*p,
*q;
for (p=module_path-1; p != (char *) NULL; )
{
(void) CopyMagickString(path,p+1,MaxTextExtent);
q=strchr(path,DirectoryListSeparator);
if (q != (char *) NULL)
*q='\0';
q=path+strlen(path)-1;
if ((q >= path) && (*q != *DirectorySeparator))
(void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);
(void) ConcatenateMagickString(path,filename,MaxTextExtent);
if (IsPathAccessible(path) != MagickFalse)
{
module_path=DestroyString(module_path);
return(MagickTrue);
}
p=strchr(p+1,DirectoryListSeparator);
}
module_path=DestroyString(module_path);
}
#if defined(MAGICKCORE_INSTALLED_SUPPORT)
else
#if defined(MAGICKCORE_CODER_PATH)
{
const char
*directory;
/*
Search hard coded paths.
*/
switch (module_type)
{
case MagickImageCoderModule:
default:
{
directory=MAGICKCORE_CODER_PATH;
break;
}
case MagickImageFilterModule:
{
directory=MAGICKCORE_FILTER_PATH;
break;
}
}
(void) FormatLocaleString(path,MaxTextExtent,"%s%s",directory,filename);
if (IsPathAccessible(path) == MagickFalse)
{
ThrowFileException(exception,ConfigureWarning,
"UnableToOpenModuleFile",path);
return(MagickFalse);
}
return(MagickTrue);
}
#else
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
{
const char
*registery_key;
unsigned char
*key_value;
/*
Locate path via registry key.
*/
switch (module_type)
{
case MagickImageCoderModule:
default:
{
registery_key="CoderModulesPath";
break;
}
case MagickImageFilterModule:
{
registery_key="FilterModulesPath";
break;
}
}
key_value=NTRegistryKeyLookup(registery_key);
if (key_value == (unsigned char *) NULL)
{
ThrowMagickException(exception,GetMagickModule(),ConfigureError,
"RegistryKeyLookupFailed","`%s'",registery_key);
return(MagickFalse);
}
(void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",(char *) key_value,
DirectorySeparator,filename);
key_value=(unsigned char *) RelinquishMagickMemory(key_value);
if (IsPathAccessible(path) == MagickFalse)
{
ThrowFileException(exception,ConfigureWarning,
"UnableToOpenModuleFile",path);
return(MagickFalse);
}
return(MagickTrue);
}
#endif
#endif
#if !defined(MAGICKCORE_CODER_PATH) && !defined(MAGICKCORE_WINDOWS_SUPPORT)
# error MAGICKCORE_CODER_PATH or MAGICKCORE_WINDOWS_SUPPORT must be defined when MAGICKCORE_INSTALLED_SUPPORT is defined
#endif
#else
{
char
*home;
home=GetEnvironmentValue("MAGICK_HOME");
if (home != (char *) NULL)
{
/*
Search MAGICK_HOME.
*/
#if !defined(MAGICKCORE_POSIX_SUPPORT)
(void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",home,
DirectorySeparator,filename);
#else
const char
*directory;
switch (module_type)
{
case MagickImageCoderModule:
default:
{
directory=MAGICKCORE_CODER_RELATIVE_PATH;
break;
}
case MagickImageFilterModule:
{
directory=MAGICKCORE_FILTER_RELATIVE_PATH;
break;
}
}
(void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s",home,
directory,filename);
#endif
home=DestroyString(home);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
}
if (*GetClientPath() != '\0')
{
/*
Search based on executable directory.
*/
#if !defined(MAGICKCORE_POSIX_SUPPORT)
(void) FormatLocaleString(path,MaxTextExtent,"%s%s%s",GetClientPath(),
DirectorySeparator,filename);
#else
char
prefix[MaxTextExtent];
const char
*directory;
switch (module_type)
{
case MagickImageCoderModule:
default:
{
directory="coders";
break;
}
case MagickImageFilterModule:
{
directory="filters";
break;
}
}
(void) CopyMagickString(prefix,GetClientPath(),MaxTextExtent);
ChopPathComponents(prefix,1);
(void) FormatLocaleString(path,MaxTextExtent,"%s/lib/%s/%s/%s",prefix,
MAGICKCORE_MODULES_RELATIVE_PATH,directory,filename);
#endif
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
#if defined(MAGICKCORE_WINDOWS_SUPPORT)
{
/*
Search module path.
*/
if ((NTGetModulePath("CORE_RL_magick_.dll",path) != MagickFalse) ||
(NTGetModulePath("CORE_DB_magick_.dll",path) != MagickFalse) ||
(NTGetModulePath("Magick.dll",path) != MagickFalse))
{
(void) ConcatenateMagickString(path,DirectorySeparator,MaxTextExtent);
(void) ConcatenateMagickString(path,filename,MaxTextExtent);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
}
#endif
{
char
*home;
home=GetEnvironmentValue("XDG_CONFIG_HOME");
if (home == (char *) NULL)
home=GetEnvironmentValue("LOCALAPPDATA");
if (home == (char *) NULL)
home=GetEnvironmentValue("APPDATA");
if (home == (char *) NULL)
home=GetEnvironmentValue("USERPROFILE");
if (home != (char *) NULL)
{
/*
Search $XDG_CONFIG_HOME/ImageMagick.
*/
(void) FormatLocaleString(path,MaxTextExtent,"%s%sImageMagick%s%s",
home,DirectorySeparator,DirectorySeparator,filename);
home=DestroyString(home);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
home=GetEnvironmentValue("HOME");
if (home != (char *) NULL)
{
/*
Search $HOME/.config/ImageMagick.
*/
(void) FormatLocaleString(path,MaxTextExtent,
"%s%s.config%sImageMagick%s%s",home,DirectorySeparator,
DirectorySeparator,DirectorySeparator,filename);
if (IsPathAccessible(path) != MagickFalse)
{
home=DestroyString(home);
return(MagickTrue);
}
/*
Search $HOME/.magick.
*/
(void) FormatLocaleString(path,MaxTextExtent,"%s%s.magick%s%s",home,
DirectorySeparator,DirectorySeparator,filename);
home=DestroyString(home);
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
}
}
/*
Search current directory.
*/
if (IsPathAccessible(path) != MagickFalse)
return(MagickTrue);
if (exception->severity < ConfigureError)
ThrowFileException(exception,ConfigureWarning,"UnableToOpenModuleFile",
path);
#endif
return(MagickFalse);
}
| 168,642 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ProxyChannelDelegate::~ProxyChannelDelegate() {
}
Commit Message: Revert 143656 - Add an IPC channel between the NaCl loader process and the renderer.
BUG=116317
TEST=ppapi, nacl tests, manual testing for experimental IPC proxy.
Review URL: https://chromiumcodereview.appspot.com/10641016
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10625007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@143665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | ProxyChannelDelegate::~ProxyChannelDelegate() {
| 170,740 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck(
const KURL& current_src) {
DCHECK(IsMainThread());
return Context()->GetSecurityOrigin() &&
Context()->GetSecurityOrigin()->CanRequest(current_src);
}
Commit Message: Redirect should not circumvent same-origin restrictions
Check whether we have access to the audio data when the format is set.
At this point we have enough information to determine this. The old approach
based on when the src was changed was incorrect because at the point, we
only know the new src; none of the response headers have been read yet.
This new approach also removes the incorrect message reported in 619114.
Bug: 826552, 619114
Change-Id: I95119b3a1e399c05d0fbd2da71f87967978efff6
Reviewed-on: https://chromium-review.googlesource.com/1069540
Commit-Queue: Raymond Toy <[email protected]>
Reviewed-by: Yutaka Hirano <[email protected]>
Reviewed-by: Hongchan Choi <[email protected]>
Cr-Commit-Position: refs/heads/master@{#564313}
CWE ID: CWE-20 | bool MediaElementAudioSourceHandler::PassesCurrentSrcCORSAccessCheck(
// Test to see if the current media URL taint the origin of the audio context?
return Context()->WouldTaintOrigin(MediaElement()->currentSrc());
}
| 173,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppCache::ToDatabaseRecords(
const AppCacheGroup* group,
AppCacheDatabase::CacheRecord* cache_record,
std::vector<AppCacheDatabase::EntryRecord>* entries,
std::vector<AppCacheDatabase::NamespaceRecord>* intercepts,
std::vector<AppCacheDatabase::NamespaceRecord>* fallbacks,
std::vector<AppCacheDatabase::OnlineWhiteListRecord>* whitelists) {
DCHECK(group && cache_record && entries && fallbacks && whitelists);
DCHECK(entries->empty() && fallbacks->empty() && whitelists->empty());
cache_record->cache_id = cache_id_;
cache_record->group_id = group->group_id();
cache_record->online_wildcard = online_whitelist_all_;
cache_record->update_time = update_time_;
cache_record->cache_size = cache_size_;
for (const auto& pair : entries_) {
entries->push_back(AppCacheDatabase::EntryRecord());
AppCacheDatabase::EntryRecord& record = entries->back();
record.url = pair.first;
record.cache_id = cache_id_;
record.flags = pair.second.types();
record.response_id = pair.second.response_id();
record.response_size = pair.second.response_size();
}
const url::Origin origin = url::Origin::Create(group->manifest_url());
for (size_t i = 0; i < intercept_namespaces_.size(); ++i) {
intercepts->push_back(AppCacheDatabase::NamespaceRecord());
AppCacheDatabase::NamespaceRecord& record = intercepts->back();
record.cache_id = cache_id_;
record.origin = origin;
record.namespace_ = intercept_namespaces_[i];
}
for (size_t i = 0; i < fallback_namespaces_.size(); ++i) {
fallbacks->push_back(AppCacheDatabase::NamespaceRecord());
AppCacheDatabase::NamespaceRecord& record = fallbacks->back();
record.cache_id = cache_id_;
record.origin = origin;
record.namespace_ = fallback_namespaces_[i];
}
for (size_t i = 0; i < online_whitelist_namespaces_.size(); ++i) {
whitelists->push_back(AppCacheDatabase::OnlineWhiteListRecord());
AppCacheDatabase::OnlineWhiteListRecord& record = whitelists->back();
record.cache_id = cache_id_;
record.namespace_url = online_whitelist_namespaces_[i].namespace_url;
record.is_pattern = online_whitelist_namespaces_[i].is_pattern;
}
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void AppCache::ToDatabaseRecords(
const AppCacheGroup* group,
AppCacheDatabase::CacheRecord* cache_record,
std::vector<AppCacheDatabase::EntryRecord>* entries,
std::vector<AppCacheDatabase::NamespaceRecord>* intercepts,
std::vector<AppCacheDatabase::NamespaceRecord>* fallbacks,
std::vector<AppCacheDatabase::OnlineWhiteListRecord>* whitelists) {
DCHECK(group && cache_record && entries && fallbacks && whitelists);
DCHECK(entries->empty() && fallbacks->empty() && whitelists->empty());
cache_record->cache_id = cache_id_;
cache_record->group_id = group->group_id();
cache_record->online_wildcard = online_whitelist_all_;
cache_record->update_time = update_time_;
cache_record->cache_size = cache_size_;
cache_record->padding_size = padding_size_;
for (const auto& pair : entries_) {
entries->push_back(AppCacheDatabase::EntryRecord());
AppCacheDatabase::EntryRecord& record = entries->back();
record.url = pair.first;
record.cache_id = cache_id_;
record.flags = pair.second.types();
record.response_id = pair.second.response_id();
record.response_size = pair.second.response_size();
record.padding_size = pair.second.padding_size();
}
const url::Origin origin = url::Origin::Create(group->manifest_url());
for (size_t i = 0; i < intercept_namespaces_.size(); ++i) {
intercepts->push_back(AppCacheDatabase::NamespaceRecord());
AppCacheDatabase::NamespaceRecord& record = intercepts->back();
record.cache_id = cache_id_;
record.origin = origin;
record.namespace_ = intercept_namespaces_[i];
}
for (size_t i = 0; i < fallback_namespaces_.size(); ++i) {
fallbacks->push_back(AppCacheDatabase::NamespaceRecord());
AppCacheDatabase::NamespaceRecord& record = fallbacks->back();
record.cache_id = cache_id_;
record.origin = origin;
record.namespace_ = fallback_namespaces_[i];
}
for (size_t i = 0; i < online_whitelist_namespaces_.size(); ++i) {
whitelists->push_back(AppCacheDatabase::OnlineWhiteListRecord());
AppCacheDatabase::OnlineWhiteListRecord& record = whitelists->back();
record.cache_id = cache_id_;
record.namespace_url = online_whitelist_namespaces_[i].namespace_url;
record.is_pattern = online_whitelist_namespaces_[i].is_pattern;
}
}
| 172,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
{
int prev,i,j;
if (f->previous_length) {
int i,j, n = f->previous_length;
float *w = get_window(f, n);
for (i=0; i < f->channels; ++i) {
for (j=0; j < n; ++j)
f->channel_buffers[i][left+j] =
f->channel_buffers[i][left+j]*w[ j] +
f->previous_window[i][ j]*w[n-1-j];
}
}
prev = f->previous_length;
f->previous_length = len - right;
for (i=0; i < f->channels; ++i)
for (j=0; right+j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right+j];
if (!prev)
return 0;
if (len < right) right = len;
f->samples_output += right-left;
return right - left;
}
Commit Message: Fix seven bugs discovered and fixed by ForAllSecure:
CVE-2019-13217: heap buffer overflow in start_decoder()
CVE-2019-13218: stack buffer overflow in compute_codewords()
CVE-2019-13219: uninitialized memory in vorbis_decode_packet_rest()
CVE-2019-13220: out-of-range read in draw_line()
CVE-2019-13221: issue with large 1D codebooks in lookup1_values()
CVE-2019-13222: unchecked NULL returned by get_window()
CVE-2019-13223: division by zero in predict_point()
CWE ID: CWE-20 | static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
{
int prev,i,j;
if (f->previous_length) {
int i,j, n = f->previous_length;
float *w = get_window(f, n);
if (w == NULL) return 0;
for (i=0; i < f->channels; ++i) {
for (j=0; j < n; ++j)
f->channel_buffers[i][left+j] =
f->channel_buffers[i][left+j]*w[ j] +
f->previous_window[i][ j]*w[n-1-j];
}
}
prev = f->previous_length;
f->previous_length = len - right;
for (i=0; i < f->channels; ++i)
for (j=0; right+j < len; ++j)
f->previous_window[i][j] = f->channel_buffers[i][right+j];
if (!prev)
return 0;
if (len < right) right = len;
f->samples_output += right-left;
return right - left;
}
| 169,618 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long long BlockGroup::GetDurationTimeCode() const
{
return m_duration;
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long long BlockGroup::GetDurationTimeCode() const
| 174,308 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_parse_inter_slice_data_cabac(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD32 uc_more_data_flag;
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2, u1_mb_idx;
UWORD32 u1_mbaff;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end = 0;
UWORD32 u1_tfr_n_mb = 0;
UWORD32 u1_decode_nmb = 0;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data = ps_dec->ps_parse_mb_data;
UWORD32 u1_inter_mb_skip_type;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD32 u1_mb_threshold;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
WORD32 ret = OK;
/******************************************************/
/* Initialisations specific to B or P slice */
/******************************************************/
if(ps_slice->u1_slice_type == P_SLICE)
{
u1_inter_mb_skip_type = CAB_P_SKIP;
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
u1_mb_threshold = 5;
}
else // B_SLICE
{
u1_inter_mb_skip_type = CAB_B_SKIP;
u1_inter_mb_type = B_MB;
u1_deblk_mb_type = D_B_SLICE;
u1_mb_threshold = 23;
}
/******************************************************/
/* Slice Level Initialisations */
/******************************************************/
i2_cur_mb_addr = u2_first_mb_in_slice;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
u1_num_mbsNby2 = 0;
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
uc_more_data_flag = 1;
/* Initialisations specific to cabac */
if(ps_bitstrm->u4_ofst & 0x07)
{
ps_bitstrm->u4_ofst += 8;
ps_bitstrm->u4_ofst &= 0xFFFFFFF8;
}
ret = ih264d_init_cabac_dec_envirnoment(&(ps_dec->s_cab_dec_env), ps_bitstrm);
if(ret != OK)
return ret;
ps_dec->i1_prev_mb_qp_delta = 0;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
UWORD32 u4_mb_skip;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
u4_mb_skip = ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 1);
/*********************************************************************/
/* initialize u1_tran_form8x8 to zero to aviod uninitialized accesses */
/*********************************************************************/
ps_cur_mb_info->u1_tran_form8x8 = 0;
ps_cur_mb_info->ps_curmb->u1_tran_form8x8 = 0;
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
if(u4_mb_skip)
{
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
memset(ps_dec->ps_curr_ctxt_mb_info, 0, sizeof(ctxt_inc_mb_info_t));
ps_dec->ps_curr_ctxt_mb_info->u1_mb_type = u1_inter_mb_skip_type;
MEMSET_16BYTES(&ps_dec->pu1_left_mv_ctxt_inc[0][0], 0);
*((UWORD32 *)ps_dec->pi1_left_ref_idx_ctxt_inc) = 0;
*(ps_dec->pu1_left_yuv_dc_csbp) = 0;
ps_dec->i1_prev_mb_qp_delta = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_cbp = 0;
{
/* Storing Skip partition info */
parse_part_params_t *ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
}
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CABAC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
else
{
/* Macroblock Layer Begins */
/* Decode the u1_mb_type */
u1_mb_type = ih264d_parse_mb_type_cabac(ps_dec);
ps_cur_mb_info->u1_mb_type = u1_mb_type;
if(u1_mb_type > (25 + u1_mb_threshold))
return ERROR_MB_TYPE;
/* Parse Macroblock Data */
if(u1_mb_type < u1_mb_threshold)
{
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
*(ps_dec->pu1_left_yuv_dc_csbp) &= 0x6;
ret = ps_dec->pf_parse_inter_mb(ps_dec, ps_cur_mb_info, u1_num_mbs,
u1_num_mbsNby2);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
}
else
{
/* Storing Intra partition info */
ps_parse_mb_data->u1_num_part = 0;
ps_parse_mb_data->u1_isI_mb = 1;
if((25 + u1_mb_threshold) == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
if(u1_mb_type == u1_mb_threshold)
ps_cur_mb_info->ps_curmb->u1_mb_type = I_4x4_MB;
else
ps_cur_mb_info->ps_curmb->u1_mb_type = I_16x16_MB;
ret = ih264d_parse_imb_cabac(
ps_dec, ps_cur_mb_info,
(UWORD8)(u1_mb_type - u1_mb_threshold));
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
ps_cur_deblk_mb->u1_mb_type |= D_INTRA_MB;
}
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/* Next macroblock information */
i2_cur_mb_addr++;
if(ps_cur_mb_info->u1_topmb && u1_mbaff)
uc_more_data_flag = 1;
else
{
uc_more_data_flag = ih264d_decode_terminate(&ps_dec->s_cab_dec_env,
ps_bitstrm);
uc_more_data_flag = !uc_more_data_flag;
COPYTHECONTEXT("Decode Sliceterm",!uc_more_data_flag);
}
u1_num_mbs++;
ps_dec->u2_total_mbs_coded++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = !uc_more_data_flag;
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
/*u1_dma_nby2mb = u1_decode_nmb ||
(u1_num_mbsNby2 == ps_dec->u1_recon_mb_grp_pair);*/
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
{
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
}
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_decode_nmb: %d, u1_num_mbs: %d", u1_decode_nmb, u1_num_mbs);*/
if(u1_decode_nmb)
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
Commit Message: Decoder Update mb count after mb map is set.
Bug: 25928803
Change-Id: Iccc58a7dd1c5c6ea656dfca332cfb8dddba4de37
CWE ID: CWE-119 | WORD32 ih264d_parse_inter_slice_data_cabac(dec_struct_t * ps_dec,
dec_slice_params_t * ps_slice,
UWORD16 u2_first_mb_in_slice)
{
UWORD32 uc_more_data_flag;
WORD32 i2_cur_mb_addr;
UWORD32 u1_num_mbs, u1_num_mbsNby2, u1_mb_idx;
UWORD32 u1_mbaff;
UWORD32 u1_num_mbs_next, u1_end_of_row;
const UWORD16 i2_pic_wdin_mbs = ps_dec->u2_frm_wd_in_mbs;
UWORD32 u1_slice_end = 0;
UWORD32 u1_tfr_n_mb = 0;
UWORD32 u1_decode_nmb = 0;
deblk_mb_t *ps_cur_deblk_mb;
dec_mb_info_t *ps_cur_mb_info;
parse_pmbarams_t *ps_parse_mb_data = ps_dec->ps_parse_mb_data;
UWORD32 u1_inter_mb_skip_type;
UWORD32 u1_inter_mb_type;
UWORD32 u1_deblk_mb_type;
UWORD32 u1_mb_threshold;
dec_bit_stream_t * const ps_bitstrm = ps_dec->ps_bitstrm;
WORD32 ret = OK;
/******************************************************/
/* Initialisations specific to B or P slice */
/******************************************************/
if(ps_slice->u1_slice_type == P_SLICE)
{
u1_inter_mb_skip_type = CAB_P_SKIP;
u1_inter_mb_type = P_MB;
u1_deblk_mb_type = D_INTER_MB;
u1_mb_threshold = 5;
}
else // B_SLICE
{
u1_inter_mb_skip_type = CAB_B_SKIP;
u1_inter_mb_type = B_MB;
u1_deblk_mb_type = D_B_SLICE;
u1_mb_threshold = 23;
}
/******************************************************/
/* Slice Level Initialisations */
/******************************************************/
i2_cur_mb_addr = u2_first_mb_in_slice;
ps_dec->u1_qp = ps_slice->u1_slice_qp;
ih264d_update_qp(ps_dec, 0);
u1_mb_idx = ps_dec->u1_mb_idx;
u1_num_mbs = u1_mb_idx;
u1_num_mbsNby2 = 0;
u1_mbaff = ps_slice->u1_mbaff_frame_flag;
i2_cur_mb_addr = u2_first_mb_in_slice << u1_mbaff;
uc_more_data_flag = 1;
/* Initialisations specific to cabac */
if(ps_bitstrm->u4_ofst & 0x07)
{
ps_bitstrm->u4_ofst += 8;
ps_bitstrm->u4_ofst &= 0xFFFFFFF8;
}
ret = ih264d_init_cabac_dec_envirnoment(&(ps_dec->s_cab_dec_env), ps_bitstrm);
if(ret != OK)
return ret;
ps_dec->i1_prev_mb_qp_delta = 0;
while(!u1_slice_end)
{
UWORD8 u1_mb_type;
UWORD32 u4_mb_skip;
ps_dec->pv_prev_mb_parse_tu_coeff_data = ps_dec->pv_parse_tu_coeff_data;
if(i2_cur_mb_addr > ps_dec->ps_cur_sps->u2_max_mb_addr)
{
ret = ERROR_MB_ADDRESS_T;
break;
}
ps_cur_mb_info = ps_dec->ps_nmb_info + u1_num_mbs;
ps_dec->u4_num_mbs_cur_nmb = u1_num_mbs;
ps_cur_mb_info->u1_Mux = 0;
ps_dec->u4_num_pmbair = (u1_num_mbs >> u1_mbaff);
ps_cur_deblk_mb = ps_dec->ps_deblk_mbn + u1_num_mbs;
ps_cur_mb_info->u1_end_of_slice = 0;
/* Storing Default partition info */
ps_parse_mb_data->u1_num_part = 1;
ps_parse_mb_data->u1_isI_mb = 0;
/***************************************************************/
/* Get the required information for decoding of MB */
/* mb_x, mb_y , neighbour availablity, */
/***************************************************************/
u4_mb_skip = ps_dec->pf_get_mb_info(ps_dec, i2_cur_mb_addr, ps_cur_mb_info, 1);
/*********************************************************************/
/* initialize u1_tran_form8x8 to zero to aviod uninitialized accesses */
/*********************************************************************/
ps_cur_mb_info->u1_tran_form8x8 = 0;
ps_cur_mb_info->ps_curmb->u1_tran_form8x8 = 0;
/***************************************************************/
/* Set the deblocking parameters for this MB */
/***************************************************************/
if(ps_dec->u4_app_disable_deblk_frm == 0)
ih264d_set_deblocking_parameters(ps_cur_deblk_mb, ps_slice,
ps_dec->u1_mb_ngbr_availablity,
ps_dec->u1_cur_mb_fld_dec_flag);
if(u4_mb_skip)
{
/* Set appropriate flags in ps_cur_mb_info and ps_dec */
memset(ps_dec->ps_curr_ctxt_mb_info, 0, sizeof(ctxt_inc_mb_info_t));
ps_dec->ps_curr_ctxt_mb_info->u1_mb_type = u1_inter_mb_skip_type;
MEMSET_16BYTES(&ps_dec->pu1_left_mv_ctxt_inc[0][0], 0);
*((UWORD32 *)ps_dec->pi1_left_ref_idx_ctxt_inc) = 0;
*(ps_dec->pu1_left_yuv_dc_csbp) = 0;
ps_dec->i1_prev_mb_qp_delta = 0;
ps_cur_mb_info->u1_mb_type = MB_SKIP;
ps_cur_mb_info->u1_cbp = 0;
{
/* Storing Skip partition info */
parse_part_params_t *ps_part_info = ps_dec->ps_part;
ps_part_info->u1_is_direct = PART_DIRECT_16x16;
ps_part_info->u1_sub_mb_num = 0;
ps_dec->ps_part++;
}
/* Update Nnzs */
ih264d_update_nnz_for_skipmb(ps_dec, ps_cur_mb_info, CABAC);
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
else
{
/* Macroblock Layer Begins */
/* Decode the u1_mb_type */
u1_mb_type = ih264d_parse_mb_type_cabac(ps_dec);
ps_cur_mb_info->u1_mb_type = u1_mb_type;
if(u1_mb_type > (25 + u1_mb_threshold))
return ERROR_MB_TYPE;
/* Parse Macroblock Data */
if(u1_mb_type < u1_mb_threshold)
{
ps_cur_mb_info->ps_curmb->u1_mb_type = u1_inter_mb_type;
*(ps_dec->pu1_left_yuv_dc_csbp) &= 0x6;
ret = ps_dec->pf_parse_inter_mb(ps_dec, ps_cur_mb_info, u1_num_mbs,
u1_num_mbsNby2);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
ps_cur_deblk_mb->u1_mb_type |= u1_deblk_mb_type;
}
else
{
/* Storing Intra partition info */
ps_parse_mb_data->u1_num_part = 0;
ps_parse_mb_data->u1_isI_mb = 1;
if((25 + u1_mb_threshold) == u1_mb_type)
{
/* I_PCM_MB */
ps_cur_mb_info->ps_curmb->u1_mb_type = I_PCM_MB;
ret = ih264d_parse_ipcm_mb(ps_dec, ps_cur_mb_info, u1_num_mbs);
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = 0;
}
else
{
if(u1_mb_type == u1_mb_threshold)
ps_cur_mb_info->ps_curmb->u1_mb_type = I_4x4_MB;
else
ps_cur_mb_info->ps_curmb->u1_mb_type = I_16x16_MB;
ret = ih264d_parse_imb_cabac(
ps_dec, ps_cur_mb_info,
(UWORD8)(u1_mb_type - u1_mb_threshold));
if(ret != OK)
return ret;
ps_cur_deblk_mb->u1_mb_qp = ps_dec->u1_qp;
}
ps_cur_deblk_mb->u1_mb_type |= D_INTRA_MB;
}
}
if(u1_mbaff)
{
ih264d_update_mbaff_left_nnz(ps_dec, ps_cur_mb_info);
}
/* Next macroblock information */
i2_cur_mb_addr++;
if(ps_cur_mb_info->u1_topmb && u1_mbaff)
uc_more_data_flag = 1;
else
{
uc_more_data_flag = ih264d_decode_terminate(&ps_dec->s_cab_dec_env,
ps_bitstrm);
uc_more_data_flag = !uc_more_data_flag;
COPYTHECONTEXT("Decode Sliceterm",!uc_more_data_flag);
}
u1_num_mbs++;
u1_num_mbsNby2++;
ps_parse_mb_data++;
/****************************************************************/
/* Check for End Of Row and other flags that determine when to */
/* do DMA setup for N/2-Mb, Decode for N-Mb, and Transfer for */
/* N-Mb */
/****************************************************************/
u1_num_mbs_next = i2_pic_wdin_mbs - ps_dec->u2_mbx - 1;
u1_end_of_row = (!u1_num_mbs_next) && (!(u1_mbaff && (u1_num_mbs & 0x01)));
u1_slice_end = !uc_more_data_flag;
u1_tfr_n_mb = (u1_num_mbs == ps_dec->u1_recon_mb_grp) || u1_end_of_row
|| u1_slice_end;
u1_decode_nmb = u1_tfr_n_mb || u1_slice_end;
ps_cur_mb_info->u1_end_of_slice = u1_slice_end;
/*u1_dma_nby2mb = u1_decode_nmb ||
(u1_num_mbsNby2 == ps_dec->u1_recon_mb_grp_pair);*/
if(u1_decode_nmb)
{
ps_dec->pf_mvpred_ref_tfr_nby2mb(ps_dec, u1_mb_idx, u1_num_mbs);
u1_num_mbsNby2 = 0;
{
ps_parse_mb_data = ps_dec->ps_parse_mb_data;
ps_dec->ps_part = ps_dec->ps_parse_part_params;
}
}
/*H264_DEC_DEBUG_PRINT("Pic: %d Mb_X=%d Mb_Y=%d",
ps_slice->i4_poc >> ps_slice->u1_field_pic_flag,
ps_dec->u2_mbx,ps_dec->u2_mby + (1 - ps_cur_mb_info->u1_topmb));
H264_DEC_DEBUG_PRINT("u1_decode_nmb: %d, u1_num_mbs: %d", u1_decode_nmb, u1_num_mbs);*/
if(u1_decode_nmb)
{
if(ps_dec->u1_separate_parse)
{
ih264d_parse_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb, u1_end_of_row);
ps_dec->ps_nmb_info += u1_num_mbs;
}
else
{
ih264d_decode_recon_tfr_nmb(ps_dec, u1_mb_idx, u1_num_mbs,
u1_num_mbs_next, u1_tfr_n_mb,
u1_end_of_row);
}
ps_dec->u2_total_mbs_coded += u1_num_mbs;
if(u1_tfr_n_mb)
u1_num_mbs = 0;
u1_mb_idx = u1_num_mbs;
ps_dec->u1_mb_idx = u1_num_mbs;
}
}
ps_dec->u4_num_mbs_cur_nmb = 0;
ps_dec->ps_cur_slice->u4_mbs_in_slice = i2_cur_mb_addr
- (u2_first_mb_in_slice << u1_mbaff);
return ret;
}
| 173,956 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int php_stream_temp_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
switch(option) {
case PHP_STREAM_OPTION_META_DATA_API:
if (ts->meta) {
zend_hash_copy(Z_ARRVAL_P((zval*)ptrparam), Z_ARRVAL_P(ts->meta), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*));
}
return PHP_STREAM_OPTION_RETURN_OK;
default:
if (ts->innerstream) {
return php_stream_set_option(ts->innerstream, option, value, ptrparam);
}
return PHP_STREAM_OPTION_RETURN_NOTIMPL;
}
}
/* }}} */
Commit Message:
CWE ID: CWE-20 | static int php_stream_temp_set_option(php_stream *stream, int option, int value, void *ptrparam TSRMLS_DC) /* {{{ */
{
php_stream_temp_data *ts = (php_stream_temp_data*)stream->abstract;
switch(option) {
case PHP_STREAM_OPTION_META_DATA_API:
if (ts->meta) {
zend_hash_copy(Z_ARRVAL_P((zval*)ptrparam), Z_ARRVAL_P(ts->meta), (copy_ctor_func_t) zval_add_ref, NULL, sizeof(zval*));
}
return PHP_STREAM_OPTION_RETURN_OK;
default:
if (ts->innerstream) {
return php_stream_set_option(ts->innerstream, option, value, ptrparam);
}
return PHP_STREAM_OPTION_RETURN_NOTIMPL;
}
}
/* }}} */
| 165,482 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: Chapters::Chapters(
Segment* pSegment,
long long payload_start,
long long payload_size,
long long element_start,
long long element_size) :
m_pSegment(pSegment),
m_start(payload_start),
m_size(payload_size),
m_element_start(element_start),
m_element_size(element_size),
m_editions(NULL),
m_editions_size(0),
m_editions_count(0)
{
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | Chapters::Chapters(
| 174,243 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ConvertProperty(IBusProperty* ibus_prop,
int selection_item_id,
ImePropertyList* out_prop_list) {
DCHECK(ibus_prop);
DCHECK(ibus_prop->key);
DCHECK(out_prop_list);
const bool has_sub_props = PropertyHasChildren(ibus_prop);
if (has_sub_props && (ibus_prop->type != PROP_TYPE_MENU)) {
LOG(ERROR) << "The property has sub properties, "
<< "but the type of the property is not PROP_TYPE_MENU";
return false;
}
if ((!has_sub_props) && (ibus_prop->type == PROP_TYPE_MENU)) {
DLOG(INFO) << "Property list is empty";
return false;
}
if (ibus_prop->type == PROP_TYPE_SEPARATOR ||
ibus_prop->type == PROP_TYPE_MENU) {
return true;
}
const bool is_selection_item = (ibus_prop->type == PROP_TYPE_RADIO);
selection_item_id = is_selection_item ?
selection_item_id : ImeProperty::kInvalidSelectionItemId;
bool is_selection_item_checked = false;
if (ibus_prop->state == PROP_STATE_INCONSISTENT) {
LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, "
<< "which is not supported.";
} else if ((!is_selection_item) && (ibus_prop->state == PROP_STATE_CHECKED)) {
LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is "
<< "PROP_TYPE_RADIO.";
} else {
is_selection_item_checked = (ibus_prop->state == PROP_STATE_CHECKED);
}
if (!ibus_prop->key) {
LOG(ERROR) << "key is NULL";
}
if (ibus_prop->tooltip && (!ibus_prop->tooltip->text)) {
LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
if (ibus_prop->label && (!ibus_prop->label->text)) {
LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
std::string label =
((ibus_prop->tooltip &&
ibus_prop->tooltip->text) ? ibus_prop->tooltip->text : "");
if (label.empty()) {
label = (ibus_prop->label && ibus_prop->label->text)
? ibus_prop->label->text : "";
}
if (label.empty()) {
label = Or(ibus_prop->key, "");
}
out_prop_list->push_back(ImeProperty(ibus_prop->key,
label,
is_selection_item,
is_selection_item_checked,
selection_item_id));
return true;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool ConvertProperty(IBusProperty* ibus_prop,
int selection_item_id,
ImePropertyList* out_prop_list) {
DCHECK(ibus_prop);
DCHECK(ibus_prop->key);
DCHECK(out_prop_list);
const bool has_sub_props = PropertyHasChildren(ibus_prop);
if (has_sub_props && (ibus_prop->type != PROP_TYPE_MENU)) {
LOG(ERROR) << "The property has sub properties, "
<< "but the type of the property is not PROP_TYPE_MENU";
return false;
}
if ((!has_sub_props) && (ibus_prop->type == PROP_TYPE_MENU)) {
VLOG(1) << "Property list is empty";
return false;
}
if (ibus_prop->type == PROP_TYPE_SEPARATOR ||
ibus_prop->type == PROP_TYPE_MENU) {
return true;
}
const bool is_selection_item = (ibus_prop->type == PROP_TYPE_RADIO);
selection_item_id = is_selection_item ?
selection_item_id : ImeProperty::kInvalidSelectionItemId;
bool is_selection_item_checked = false;
if (ibus_prop->state == PROP_STATE_INCONSISTENT) {
LOG(WARNING) << "The property is in PROP_STATE_INCONSISTENT, "
<< "which is not supported.";
} else if ((!is_selection_item) && (ibus_prop->state == PROP_STATE_CHECKED)) {
LOG(WARNING) << "PROP_STATE_CHECKED is meaningful only if the type is "
<< "PROP_TYPE_RADIO.";
} else {
is_selection_item_checked = (ibus_prop->state == PROP_STATE_CHECKED);
}
if (!ibus_prop->key) {
LOG(ERROR) << "key is NULL";
}
if (ibus_prop->tooltip && (!ibus_prop->tooltip->text)) {
LOG(ERROR) << "tooltip is NOT NULL, but tooltip->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
if (ibus_prop->label && (!ibus_prop->label->text)) {
LOG(ERROR) << "label is NOT NULL, but label->text IS NULL: key="
<< Or(ibus_prop->key, "");
}
std::string label =
((ibus_prop->tooltip &&
ibus_prop->tooltip->text) ? ibus_prop->tooltip->text : "");
if (label.empty()) {
label = (ibus_prop->label && ibus_prop->label->text)
? ibus_prop->label->text : "";
}
if (label.empty()) {
label = Or(ibus_prop->key, "");
}
out_prop_list->push_back(ImeProperty(ibus_prop->key,
label,
is_selection_item,
is_selection_item_checked,
selection_item_id));
return true;
}
| 170,531 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool CSSStyleSheet::CanAccessRules() const {
if (enable_rule_access_for_inspector_)
return true;
if (is_inline_stylesheet_)
return true;
KURL base_url = contents_->BaseURL();
if (base_url.IsEmpty())
return true;
Document* document = OwnerDocument();
if (!document)
return true;
if (document->GetSecurityOrigin()->CanReadContent(base_url))
return true;
if (allow_rule_access_from_origin_ &&
document->GetSecurityOrigin()->CanAccess(
allow_rule_access_from_origin_.get())) {
return true;
}
return false;
}
Commit Message: Disallow access to opaque CSS responses.
Bug: 848786
Change-Id: Ie53fbf644afdd76d7c65649a05c939c63d89b4ec
Reviewed-on: https://chromium-review.googlesource.com/1088335
Reviewed-by: Kouhei Ueno <[email protected]>
Commit-Queue: Matt Falkenhagen <[email protected]>
Cr-Commit-Position: refs/heads/master@{#565537}
CWE ID: CWE-200 | bool CSSStyleSheet::CanAccessRules() const {
if (enable_rule_access_for_inspector_)
return true;
// Opaque responses should never be accessible, mod DevTools. See comments for
// IsOpaqueResponseFromServiceWorker().
if (contents_->IsOpaqueResponseFromServiceWorker())
return false;
if (is_inline_stylesheet_)
return true;
KURL base_url = contents_->BaseURL();
if (base_url.IsEmpty())
return true;
Document* document = OwnerDocument();
if (!document)
return true;
if (document->GetSecurityOrigin()->CanReadContent(base_url))
return true;
if (allow_rule_access_from_origin_ &&
document->GetSecurityOrigin()->CanAccess(
allow_rule_access_from_origin_.get())) {
return true;
}
return false;
}
| 173,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long Cluster::Parse(long long& pos, long& len) const
{
long status = Load(pos, len);
if (status < 0)
return status;
assert(m_pos >= m_element_start);
assert(m_timecode >= 0);
const long long cluster_stop =
(m_element_size < 0) ? -1 : m_element_start + m_element_size;
if ((cluster_stop >= 0) && (m_pos >= cluster_stop))
return 1; //nothing else to do
IMkvReader* const pReader = m_pSegment->m_pReader;
long long total, avail;
status = pReader->Length(&total, &avail);
if (status < 0) //error
return status;
assert((total < 0) || (avail <= total));
pos = m_pos;
for (;;)
{
if ((cluster_stop >= 0) && (pos >= cluster_stop))
break;
if ((total >= 0) && (pos >= total))
{
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
long long result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long id = ReadUInt(pReader, pos, len);
if (id < 0) //error
return static_cast<long>(id);
if (id == 0) //weird
return E_FILE_FORMAT_INVALID;
if ((id == 0x0F43B675) || (id == 0x0C53BB6B)) //Cluster or Cues ID
{
if (m_element_size < 0)
m_element_size = pos - m_element_start;
break;
}
pos += len; //consume ID field
if ((pos + 1) > avail)
{
len = 1;
return E_BUFFER_NOT_FULL;
}
result = GetUIntLength(pReader, pos, len);
if (result < 0) //error
return static_cast<long>(result);
if (result > 0) //weird
return E_BUFFER_NOT_FULL;
if ((cluster_stop >= 0) && ((pos + len) > cluster_stop))
return E_FILE_FORMAT_INVALID;
if ((pos + len) > avail)
return E_BUFFER_NOT_FULL;
const long long size = ReadUInt(pReader, pos, len);
if (size < 0) //error
return static_cast<long>(size);
const long long unknown_size = (1LL << (7 * len)) - 1;
if (size == unknown_size)
return E_FILE_FORMAT_INVALID;
pos += len; //consume size field
if ((cluster_stop >= 0) && (pos > cluster_stop))
return E_FILE_FORMAT_INVALID;
if (size == 0) //weird
continue;
const long long block_stop = pos + size;
if (cluster_stop >= 0)
{
if (block_stop > cluster_stop)
{
if ((id == 0x20) || (id == 0x23))
return E_FILE_FORMAT_INVALID;
pos = cluster_stop;
break;
}
}
else if ((total >= 0) && (block_stop > total))
{
m_element_size = total - m_element_start;
pos = total;
break;
}
else if (block_stop > avail)
{
len = static_cast<long>(size);
return E_BUFFER_NOT_FULL;
}
Cluster* const this_ = const_cast<Cluster*>(this);
if (id == 0x20) //BlockGroup
return this_->ParseBlockGroup(size, pos, len);
if (id == 0x23) //SimpleBlock
return this_->ParseSimpleBlock(size, pos, len);
pos += size; //consume payload
assert((cluster_stop < 0) || (pos <= cluster_stop));
}
assert(m_element_size > 0);
m_pos = pos;
assert((cluster_stop < 0) || (m_pos <= cluster_stop));
if (m_entries_count > 0)
{
const long idx = m_entries_count - 1;
const BlockEntry* const pLast = m_entries[idx];
assert(pLast);
const Block* const pBlock = pLast->GetBlock();
assert(pBlock);
const long long start = pBlock->m_start;
if ((total >= 0) && (start > total))
return -1; //defend against trucated stream
const long long size = pBlock->m_size;
const long long stop = start + size;
assert((cluster_stop < 0) || (stop <= cluster_stop));
if ((total >= 0) && (stop > total))
return -1; //defend against trucated stream
}
return 1; //no more entries
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | long Cluster::Parse(long long& pos, long& len) const
| 174,409 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void AppListController::EnableAppList() {
PrefService* local_state = g_browser_process->local_state();
bool has_been_enabled = local_state->GetBoolean(
apps::prefs::kAppLauncherHasBeenEnabled);
if (!has_been_enabled) {
local_state->SetBoolean(apps::prefs::kAppLauncherHasBeenEnabled, true);
ShellIntegration::ShortcutLocations shortcut_locations;
shortcut_locations.on_desktop = true;
shortcut_locations.in_quick_launch_bar = true;
shortcut_locations.in_applications_menu = true;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
shortcut_locations.applications_menu_subdir = dist->GetAppShortCutName();
base::FilePath user_data_dir(
g_browser_process->profile_manager()->user_data_dir());
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&CreateAppListShortcuts,
user_data_dir, GetAppModelId(), shortcut_locations));
}
}
Commit Message: Upgrade old app host to new app launcher on startup
This patch is a continuation of https://codereview.chromium.org/16805002/.
BUG=248825
Review URL: https://chromiumcodereview.appspot.com/17022015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@209604 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void AppListController::EnableAppList() {
PrefService* local_state = g_browser_process->local_state();
local_state->SetBoolean(apps::prefs::kAppLauncherHasBeenEnabled, true);
ShellIntegration::ShortcutLocations shortcut_locations;
shortcut_locations.on_desktop = true;
shortcut_locations.in_quick_launch_bar = true;
shortcut_locations.in_applications_menu = true;
BrowserDistribution* dist = BrowserDistribution::GetDistribution();
shortcut_locations.applications_menu_subdir = dist->GetAppShortCutName();
base::FilePath user_data_dir(
g_browser_process->profile_manager()->user_data_dir());
content::BrowserThread::PostTask(
content::BrowserThread::FILE,
FROM_HERE,
base::Bind(&CreateAppListShortcuts,
user_data_dir, GetAppModelId(), shortcut_locations));
}
| 171,336 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MojoVideoEncodeAccelerator::UseOutputBitstreamBuffer(
const BitstreamBuffer& buffer) {
DVLOG(2) << __func__ << " buffer.id()= " << buffer.id()
<< " buffer.size()= " << buffer.size() << "B";
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(
buffer.handle().Duplicate(), buffer.size(), true /* read_only */);
vea_->UseOutputBitstreamBuffer(buffer.id(), std::move(buffer_handle));
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | void MojoVideoEncodeAccelerator::UseOutputBitstreamBuffer(
const BitstreamBuffer& buffer) {
DVLOG(2) << __func__ << " buffer.id()= " << buffer.id()
<< " buffer.size()= " << buffer.size() << "B";
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// TODO(https://crbug.com/793446): Only wrap read-only handles here and change
// the protection status to kReadOnly.
mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(
buffer.handle().Duplicate(), buffer.size(),
mojo::UnwrappedSharedMemoryHandleProtection::kReadWrite);
vea_->UseOutputBitstreamBuffer(buffer.id(), std::move(buffer_handle));
}
| 172,874 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WriteFromUrlOperation::Download(const base::Closure& continuation) {
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
if (IsCancelled()) {
return;
}
download_continuation_ = continuation;
SetStage(image_writer_api::STAGE_DOWNLOAD);
url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this);
url_fetcher_->SetRequestContext(request_context_);
url_fetcher_->SaveResponseToFileAtPath(
image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE));
AddCleanUpFunction(
base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this));
url_fetcher_->Start();
}
Commit Message: Network traffic annotation added to extensions::image_writer::WriteFromUrlOperation.
Network traffic annotation is added to network request of extensions::image_writer::WriteFromUrlOperation.
BUG=656607
Review-Url: https://codereview.chromium.org/2691963002
Cr-Commit-Position: refs/heads/master@{#451456}
CWE ID: | void WriteFromUrlOperation::Download(const base::Closure& continuation) {
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
if (IsCancelled()) {
return;
}
download_continuation_ = continuation;
SetStage(image_writer_api::STAGE_DOWNLOAD);
// Create traffic annotation tag.
net::NetworkTrafficAnnotationTag traffic_annotation =
net::DefineNetworkTrafficAnnotation("cros_recovery_image_download", R"(
semantics {
sender: "Chrome OS Recovery Utility"
description:
"The Google Chrome OS recovery utility downloads the recovery "
"image from Google Download Server."
trigger:
"User uses the Chrome OS Recovery Utility app/extension, selects "
"a Chrome OS recovery image, and clicks the Create button to write "
"the image to a USB or SD card."
data:
"URL of the image file to be downloaded. No other data or user "
"identifier is sent."
destination: GOOGLE_OWNED_SERVICE
}
policy {
cookies_allowed: true
cookies_store: "user"
setting:
"This feature cannot be disabled by settings, it can only be used "
"by whitelisted apps/extension."
policy_exception_justification:
"Not implemented, considered not useful."
})");
url_fetcher_ = net::URLFetcher::Create(url_, net::URLFetcher::GET, this,
traffic_annotation);
url_fetcher_->SetRequestContext(request_context_);
url_fetcher_->SaveResponseToFileAtPath(
image_path_, BrowserThread::GetTaskRunnerForThread(BrowserThread::FILE));
AddCleanUpFunction(
base::Bind(&WriteFromUrlOperation::DestroyUrlFetcher, this));
url_fetcher_->Start();
}
| 171,962 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: int btpan_tap_open()
{
struct ifreq ifr;
int fd, err;
const char *clonedev = "/dev/tun";
/* open the clone device */
if ((fd = open(clonedev, O_RDWR)) < 0)
{
BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
return fd;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
/* try to create the device */
if ((err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0)
{
BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
close(fd);
return err;
}
if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0)
{
int flags = fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
return fd;
}
BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME);
close(fd);
return INVALID_FD;
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | int btpan_tap_open()
{
struct ifreq ifr;
int fd, err;
const char *clonedev = "/dev/tun";
/* open the clone device */
if ((fd = TEMP_FAILURE_RETRY(open(clonedev, O_RDWR))) < 0)
{
BTIF_TRACE_DEBUG("could not open %s, err:%d", clonedev, errno);
return fd;
}
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
strncpy(ifr.ifr_name, TAP_IF_NAME, IFNAMSIZ);
/* try to create the device */
if ((err = TEMP_FAILURE_RETRY(ioctl(fd, TUNSETIFF, (void *) &ifr))) < 0)
{
BTIF_TRACE_DEBUG("ioctl error:%d, errno:%s", err, strerror(errno));
close(fd);
return err;
}
if (tap_if_up(TAP_IF_NAME, controller_get_interface()->get_address()) == 0)
{
int flags = TEMP_FAILURE_RETRY(fcntl(fd, F_GETFL, 0));
TEMP_FAILURE_RETRY(fcntl(fd, F_SETFL, flags | O_NONBLOCK));
return fd;
}
BTIF_TRACE_ERROR("can not bring up tap interface:%s", TAP_IF_NAME);
close(fd);
return INVALID_FD;
}
| 173,445 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
{
RefPtr<HTMLInputElement> protector(element());
element()->setFocus(false);
}
Commit Message: Fix reentrance of BaseMultipleFieldsDateAndTimeInputType::destroyShadowSubtree.
destroyShadowSubtree could dispatch 'blur' event unexpectedly because
element()->focused() had incorrect information. We make sure it has
correct information by checking if the UA shadow root contains the
focused element.
BUG=257353
Review URL: https://chromiumcodereview.appspot.com/19067004
git-svn-id: svn://svn.chromium.org/blink/trunk@154086 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | void BaseMultipleFieldsDateAndTimeInputType::didBlurFromControl()
{
if (containsFocusedShadowElement())
return;
RefPtr<HTMLInputElement> protector(element());
element()->setFocus(false);
}
| 171,211 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: my_object_throw_error (MyObject *obj, GError **error)
{
g_set_error (error,
MY_OBJECT_ERROR,
MY_OBJECT_ERROR_FOO,
"%s",
"this method always loses");
return FALSE;
}
Commit Message:
CWE ID: CWE-264 | my_object_throw_error (MyObject *obj, GError **error)
| 165,124 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int read_exceptions(struct pstore *ps,
int (*callback)(void *callback_context, chunk_t old,
chunk_t new),
void *callback_context)
{
int r, full = 1;
/*
* Keeping reading chunks and inserting exceptions until
* we find a partially full area.
*/
for (ps->current_area = 0; full; ps->current_area++) {
r = area_io(ps, READ);
if (r)
return r;
r = insert_exceptions(ps, callback, callback_context, &full);
if (r)
return r;
}
ps->current_area--;
return 0;
}
Commit Message: dm snapshot: fix data corruption
This patch fixes a particular type of data corruption that has been
encountered when loading a snapshot's metadata from disk.
When we allocate a new chunk in persistent_prepare, we increment
ps->next_free and we make sure that it doesn't point to a metadata area
by further incrementing it if necessary.
When we load metadata from disk on device activation, ps->next_free is
positioned after the last used data chunk. However, if this last used
data chunk is followed by a metadata area, ps->next_free is positioned
erroneously to the metadata area. A newly-allocated chunk is placed at
the same location as the metadata area, resulting in data or metadata
corruption.
This patch changes the code so that ps->next_free skips the metadata
area when metadata are loaded in function read_exceptions.
The patch also moves a piece of code from persistent_prepare_exception
to a separate function skip_metadata to avoid code duplication.
CVE-2013-4299
Signed-off-by: Mikulas Patocka <[email protected]>
Cc: [email protected]
Cc: Mike Snitzer <[email protected]>
Signed-off-by: Alasdair G Kergon <[email protected]>
CWE ID: CWE-264 | static int read_exceptions(struct pstore *ps,
int (*callback)(void *callback_context, chunk_t old,
chunk_t new),
void *callback_context)
{
int r, full = 1;
/*
* Keeping reading chunks and inserting exceptions until
* we find a partially full area.
*/
for (ps->current_area = 0; full; ps->current_area++) {
r = area_io(ps, READ);
if (r)
return r;
r = insert_exceptions(ps, callback, callback_context, &full);
if (r)
return r;
}
ps->current_area--;
skip_metadata(ps);
return 0;
}
| 165,993 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, setCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = ',', enclosure = '"', escape='\\';
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
intern->u.file.delimiter = delimiter;
intern->u.file.enclosure = enclosure;
intern->u.file.escape = escape;
}
}
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, setCsvControl)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
char delimiter = ',', enclosure = '"', escape='\\';
char *delim = NULL, *enclo = NULL, *esc = NULL;
int d_len = 0, e_len = 0, esc_len = 0;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "|sss", &delim, &d_len, &enclo, &e_len, &esc, &esc_len) == SUCCESS) {
switch(ZEND_NUM_ARGS())
{
case 3:
if (esc_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "escape must be a character");
RETURN_FALSE;
}
escape = esc[0];
/* no break */
case 2:
if (e_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "enclosure must be a character");
RETURN_FALSE;
}
enclosure = enclo[0];
/* no break */
case 1:
if (d_len != 1) {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "delimiter must be a character");
RETURN_FALSE;
}
delimiter = delim[0];
/* no break */
case 0:
break;
}
intern->u.file.delimiter = delimiter;
intern->u.file.enclosure = enclosure;
intern->u.file.escape = escape;
}
}
| 167,063 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void init_vmcb(struct vcpu_svm *svm)
{
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
svm->vcpu.fpu_active = 1;
svm->vcpu.arch.hflags = 0;
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR3_READ);
set_cr_intercept(svm, INTERCEPT_CR4_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
set_dr_intercepts(svm);
set_exception_intercept(svm, PF_VECTOR);
set_exception_intercept(svm, UD_VECTOR);
set_exception_intercept(svm, MC_VECTOR);
set_intercept(svm, INTERCEPT_INTR);
set_intercept(svm, INTERCEPT_NMI);
set_intercept(svm, INTERCEPT_SMI);
set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
set_intercept(svm, INTERCEPT_RDPMC);
set_intercept(svm, INTERCEPT_CPUID);
set_intercept(svm, INTERCEPT_INVD);
set_intercept(svm, INTERCEPT_HLT);
set_intercept(svm, INTERCEPT_INVLPG);
set_intercept(svm, INTERCEPT_INVLPGA);
set_intercept(svm, INTERCEPT_IOIO_PROT);
set_intercept(svm, INTERCEPT_MSR_PROT);
set_intercept(svm, INTERCEPT_TASK_SWITCH);
set_intercept(svm, INTERCEPT_SHUTDOWN);
set_intercept(svm, INTERCEPT_VMRUN);
set_intercept(svm, INTERCEPT_VMMCALL);
set_intercept(svm, INTERCEPT_VMLOAD);
set_intercept(svm, INTERCEPT_VMSAVE);
set_intercept(svm, INTERCEPT_STGI);
set_intercept(svm, INTERCEPT_CLGI);
set_intercept(svm, INTERCEPT_SKINIT);
set_intercept(svm, INTERCEPT_WBINVD);
set_intercept(svm, INTERCEPT_MONITOR);
set_intercept(svm, INTERCEPT_MWAIT);
set_intercept(svm, INTERCEPT_XSETBV);
control->iopm_base_pa = iopm_base;
control->msrpm_base_pa = __pa(svm->msrpm);
control->int_ctl = V_INTR_MASKING_MASK;
init_seg(&save->es);
init_seg(&save->ss);
init_seg(&save->ds);
init_seg(&save->fs);
init_seg(&save->gs);
save->cs.selector = 0xf000;
save->cs.base = 0xffff0000;
/* Executable/Readable Code Segment */
save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
save->cs.limit = 0xffff;
save->gdtr.limit = 0xffff;
save->idtr.limit = 0xffff;
init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
svm_set_efer(&svm->vcpu, 0);
save->dr6 = 0xffff0ff0;
kvm_set_rflags(&svm->vcpu, 2);
save->rip = 0x0000fff0;
svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
/*
* svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
* It also updates the guest-visible cr0 value.
*/
svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
kvm_mmu_reset_context(&svm->vcpu);
save->cr4 = X86_CR4_PAE;
/* rdx = ?? */
if (npt_enabled) {
/* Setup VMCB for Nested Paging */
control->nested_ctl = 1;
clr_intercept(svm, INTERCEPT_INVLPG);
clr_exception_intercept(svm, PF_VECTOR);
clr_cr_intercept(svm, INTERCEPT_CR3_READ);
clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
save->g_pat = svm->vcpu.arch.pat;
save->cr3 = 0;
save->cr4 = 0;
}
svm->asid_generation = 0;
svm->nested.vmcb = 0;
svm->vcpu.arch.hflags = 0;
if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
control->pause_filter_count = 3000;
set_intercept(svm, INTERCEPT_PAUSE);
}
mark_all_dirty(svm->vmcb);
enable_gif(svm);
}
Commit Message: KVM: x86: work around infinite loop in microcode when #AC is delivered
It was found that a guest can DoS a host by triggering an infinite
stream of "alignment check" (#AC) exceptions. This causes the
microcode to enter an infinite loop where the core never receives
another interrupt. The host kernel panics pretty quickly due to the
effects (CVE-2015-5307).
Signed-off-by: Eric Northup <[email protected]>
Cc: [email protected]
Signed-off-by: Paolo Bonzini <[email protected]>
CWE ID: CWE-399 | static void init_vmcb(struct vcpu_svm *svm)
{
struct vmcb_control_area *control = &svm->vmcb->control;
struct vmcb_save_area *save = &svm->vmcb->save;
svm->vcpu.fpu_active = 1;
svm->vcpu.arch.hflags = 0;
set_cr_intercept(svm, INTERCEPT_CR0_READ);
set_cr_intercept(svm, INTERCEPT_CR3_READ);
set_cr_intercept(svm, INTERCEPT_CR4_READ);
set_cr_intercept(svm, INTERCEPT_CR0_WRITE);
set_cr_intercept(svm, INTERCEPT_CR3_WRITE);
set_cr_intercept(svm, INTERCEPT_CR4_WRITE);
set_cr_intercept(svm, INTERCEPT_CR8_WRITE);
set_dr_intercepts(svm);
set_exception_intercept(svm, PF_VECTOR);
set_exception_intercept(svm, UD_VECTOR);
set_exception_intercept(svm, MC_VECTOR);
set_exception_intercept(svm, AC_VECTOR);
set_intercept(svm, INTERCEPT_INTR);
set_intercept(svm, INTERCEPT_NMI);
set_intercept(svm, INTERCEPT_SMI);
set_intercept(svm, INTERCEPT_SELECTIVE_CR0);
set_intercept(svm, INTERCEPT_RDPMC);
set_intercept(svm, INTERCEPT_CPUID);
set_intercept(svm, INTERCEPT_INVD);
set_intercept(svm, INTERCEPT_HLT);
set_intercept(svm, INTERCEPT_INVLPG);
set_intercept(svm, INTERCEPT_INVLPGA);
set_intercept(svm, INTERCEPT_IOIO_PROT);
set_intercept(svm, INTERCEPT_MSR_PROT);
set_intercept(svm, INTERCEPT_TASK_SWITCH);
set_intercept(svm, INTERCEPT_SHUTDOWN);
set_intercept(svm, INTERCEPT_VMRUN);
set_intercept(svm, INTERCEPT_VMMCALL);
set_intercept(svm, INTERCEPT_VMLOAD);
set_intercept(svm, INTERCEPT_VMSAVE);
set_intercept(svm, INTERCEPT_STGI);
set_intercept(svm, INTERCEPT_CLGI);
set_intercept(svm, INTERCEPT_SKINIT);
set_intercept(svm, INTERCEPT_WBINVD);
set_intercept(svm, INTERCEPT_MONITOR);
set_intercept(svm, INTERCEPT_MWAIT);
set_intercept(svm, INTERCEPT_XSETBV);
control->iopm_base_pa = iopm_base;
control->msrpm_base_pa = __pa(svm->msrpm);
control->int_ctl = V_INTR_MASKING_MASK;
init_seg(&save->es);
init_seg(&save->ss);
init_seg(&save->ds);
init_seg(&save->fs);
init_seg(&save->gs);
save->cs.selector = 0xf000;
save->cs.base = 0xffff0000;
/* Executable/Readable Code Segment */
save->cs.attrib = SVM_SELECTOR_READ_MASK | SVM_SELECTOR_P_MASK |
SVM_SELECTOR_S_MASK | SVM_SELECTOR_CODE_MASK;
save->cs.limit = 0xffff;
save->gdtr.limit = 0xffff;
save->idtr.limit = 0xffff;
init_sys_seg(&save->ldtr, SEG_TYPE_LDT);
init_sys_seg(&save->tr, SEG_TYPE_BUSY_TSS16);
svm_set_efer(&svm->vcpu, 0);
save->dr6 = 0xffff0ff0;
kvm_set_rflags(&svm->vcpu, 2);
save->rip = 0x0000fff0;
svm->vcpu.arch.regs[VCPU_REGS_RIP] = save->rip;
/*
* svm_set_cr0() sets PG and WP and clears NW and CD on save->cr0.
* It also updates the guest-visible cr0 value.
*/
svm_set_cr0(&svm->vcpu, X86_CR0_NW | X86_CR0_CD | X86_CR0_ET);
kvm_mmu_reset_context(&svm->vcpu);
save->cr4 = X86_CR4_PAE;
/* rdx = ?? */
if (npt_enabled) {
/* Setup VMCB for Nested Paging */
control->nested_ctl = 1;
clr_intercept(svm, INTERCEPT_INVLPG);
clr_exception_intercept(svm, PF_VECTOR);
clr_cr_intercept(svm, INTERCEPT_CR3_READ);
clr_cr_intercept(svm, INTERCEPT_CR3_WRITE);
save->g_pat = svm->vcpu.arch.pat;
save->cr3 = 0;
save->cr4 = 0;
}
svm->asid_generation = 0;
svm->nested.vmcb = 0;
svm->vcpu.arch.hflags = 0;
if (boot_cpu_has(X86_FEATURE_PAUSEFILTER)) {
control->pause_filter_count = 3000;
set_intercept(svm, INTERCEPT_PAUSE);
}
mark_all_dirty(svm->vmcb);
enable_gif(svm);
}
| 166,598 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
assert((cc%(4*stride))==0);
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
}
Commit Message: * libtiff/tif_predict.h, libtiff/tif_predict.c:
Replace assertions by runtime checks to avoid assertions in debug mode,
or buffer overflows in release mode. Can happen when dealing with
unusual tile size like YCbCr with subsampling. Reported as MSVR 35105
by Axel Souchet & Vishal Chauhan from the MSRC Vulnerabilities & Mitigations
team.
CWE ID: CWE-119 | horAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
{
tmsize_t stride = PredictorState(tif)->stride;
uint32* wp = (uint32*) cp0;
tmsize_t wc = cc / 4;
if((cc%(4*stride))!=0)
{
TIFFErrorExt(tif->tif_clientdata, "horAcc32",
"%s", "cc%(4*stride))!=0");
return 0;
}
if (wc > stride) {
wc -= stride;
do {
REPEAT4(stride, wp[stride] += wp[0]; wp++)
wc -= stride;
} while (wc > 0);
}
return 1;
}
| 166,883 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ElementsUploadDataStreamTest::FileChangedHelper(
const base::FilePath& file_path,
const base::Time& time,
bool error_expected) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(base::MakeUnique<UploadFileElementReader>(
base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time));
TestCompletionCallback init_callback;
std::unique_ptr<UploadDataStream> stream(
new ElementsUploadDataStream(std::move(element_readers), 0));
ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()),
IsError(ERR_IO_PENDING));
int error_code = init_callback.WaitForResult();
if (error_expected)
ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED));
else
ASSERT_THAT(error_code, IsOk());
}
Commit Message: Replace base::MakeUnique with std::make_unique in net/.
base/memory/ptr_util.h includes will be cleaned up later.
Bug: 755727
Change-Id: Ibaf46f05c9b02b76f9a91e819984b087a8c0d434
Reviewed-on: https://chromium-review.googlesource.com/627300
Commit-Queue: Jeremy Roman <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Bence Béky <[email protected]>
Cr-Commit-Position: refs/heads/master@{#498123}
CWE ID: CWE-311 | void ElementsUploadDataStreamTest::FileChangedHelper(
const base::FilePath& file_path,
const base::Time& time,
bool error_expected) {
std::vector<std::unique_ptr<UploadElementReader>> element_readers;
element_readers.push_back(std::make_unique<UploadFileElementReader>(
base::ThreadTaskRunnerHandle::Get().get(), file_path, 1, 2, time));
TestCompletionCallback init_callback;
std::unique_ptr<UploadDataStream> stream(
new ElementsUploadDataStream(std::move(element_readers), 0));
ASSERT_THAT(stream->Init(init_callback.callback(), NetLogWithSource()),
IsError(ERR_IO_PENDING));
int error_code = init_callback.WaitForResult();
if (error_expected)
ASSERT_THAT(error_code, IsError(ERR_UPLOAD_FILE_CHANGED));
else
ASSERT_THAT(error_code, IsOk());
}
| 173,261 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int msr_open(struct inode *inode, struct file *file)
{
unsigned int cpu;
struct cpuinfo_x86 *c;
cpu = iminor(file->f_path.dentry->d_inode);
if (cpu >= nr_cpu_ids || !cpu_online(cpu))
return -ENXIO; /* No such CPU */
c = &cpu_data(cpu);
if (!cpu_has(c, X86_FEATURE_MSR))
return -EIO; /* MSR not supported */
return 0;
}
Commit Message: x86/msr: Add capabilities check
At the moment the MSR driver only relies upon file system
checks. This means that anything as root with any capability set
can write to MSRs. Historically that wasn't very interesting but
on modern processors the MSRs are such that writing to them
provides several ways to execute arbitary code in kernel space.
Sample code and documentation on doing this is circulating and
MSR attacks are used on Windows 64bit rootkits already.
In the Linux case you still need to be able to open the device
file so the impact is fairly limited and reduces the security of
some capability and security model based systems down towards
that of a generic "root owns the box" setup.
Therefore they should require CAP_SYS_RAWIO to prevent an
elevation of capabilities. The impact of this is fairly minimal
on most setups because they don't have heavy use of
capabilities. Those using SELinux, SMACK or AppArmor rules might
want to consider if their rulesets on the MSR driver could be
tighter.
Signed-off-by: Alan Cox <[email protected]>
Cc: Linus Torvalds <[email protected]>
Cc: Andrew Morton <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Horses <[email protected]>
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-264 | static int msr_open(struct inode *inode, struct file *file)
{
unsigned int cpu;
struct cpuinfo_x86 *c;
if (!capable(CAP_SYS_RAWIO))
return -EPERM;
cpu = iminor(file->f_path.dentry->d_inode);
if (cpu >= nr_cpu_ids || !cpu_online(cpu))
return -ENXIO; /* No such CPU */
c = &cpu_data(cpu);
if (!cpu_has(c, X86_FEATURE_MSR))
return -EIO; /* MSR not supported */
return 0;
}
| 166,166 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: explicit HeaderTestDispatcherHostDelegate(const GURL& watch_url)
: watch_url_(watch_url) {}
Commit Message: Fix ChromeResourceDispatcherHostDelegateMirrorBrowserTest.MirrorRequestHeader with network service.
The functionality worked, as part of converting DICE, however the test code didn't work since it
depended on accessing the net objects directly. Switch the tests to use the EmbeddedTestServer, to
better match production, which removes the dependency on net/.
Also:
-make GetFilePathWithReplacements replace strings in the mock headers if they're present
-add a global to google_util to ignore ports; that way other tests can be converted without having
to modify each callsite to google_util
Bug: 881976
Change-Id: Ic52023495c1c98c1248025c11cdf37f433fef058
Reviewed-on: https://chromium-review.googlesource.com/c/1328142
Commit-Queue: John Abd-El-Malek <[email protected]>
Reviewed-by: Ramin Halavati <[email protected]>
Reviewed-by: Maks Orlovich <[email protected]>
Reviewed-by: Peter Kasting <[email protected]>
Cr-Commit-Position: refs/heads/master@{#607652}
CWE ID: | explicit HeaderTestDispatcherHostDelegate(const GURL& watch_url)
explicit ThrottleContentBrowserClient(const GURL& watch_url)
: watch_url_(watch_url) {}
| 172,576 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: pvscsi_ring_pop_req_descr(PVSCSIRingInfo *mgr)
{
uint32_t ready_ptr = RS_GET_FIELD(mgr, reqProdIdx);
if (ready_ptr != mgr->consumed_ptr) {
uint32_t next_ready_ptr =
mgr->consumed_ptr++ & mgr->txr_len_mask;
uint32_t next_ready_page =
return mgr->req_ring_pages_pa[next_ready_page] +
inpage_idx * sizeof(PVSCSIRingReqDesc);
} else {
return 0;
}
}
Commit Message:
CWE ID: CWE-399 | pvscsi_ring_pop_req_descr(PVSCSIRingInfo *mgr)
{
uint32_t ready_ptr = RS_GET_FIELD(mgr, reqProdIdx);
uint32_t ring_size = PVSCSI_MAX_NUM_PAGES_REQ_RING
* PVSCSI_MAX_NUM_REQ_ENTRIES_PER_PAGE;
if (ready_ptr != mgr->consumed_ptr
&& ready_ptr - mgr->consumed_ptr < ring_size) {
uint32_t next_ready_ptr =
mgr->consumed_ptr++ & mgr->txr_len_mask;
uint32_t next_ready_page =
return mgr->req_ring_pages_pa[next_ready_page] +
inpage_idx * sizeof(PVSCSIRingReqDesc);
} else {
return 0;
}
}
| 164,929 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftMPEG4Encoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
h263type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
h263type->eProfile = OMX_VIDEO_H263ProfileBaseline;
h263type->eLevel = OMX_VIDEO_H263Level45;
h263type->bPLUSPTYPEAllowed = OMX_FALSE;
h263type->bForceRoundingTypeToZero = OMX_FALSE;
h263type->nPictureHeaderRepetition = 0;
h263type->nGOBHeaderInterval = 0;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mpeg4type->eProfile = OMX_VIDEO_MPEG4ProfileCore;
mpeg4type->eLevel = OMX_VIDEO_MPEG4Level2;
mpeg4type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
mpeg4type->nBFrames = 0;
mpeg4type->nIDCVLCThreshold = 0;
mpeg4type->bACPred = OMX_TRUE;
mpeg4type->nMaxPacketSize = 256;
mpeg4type->nTimeIncRes = 1000;
mpeg4type->nHeaderExtension = 0;
mpeg4type->bReversibleVLC = OMX_FALSE;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftMPEG4Encoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoH263:
{
OMX_VIDEO_PARAM_H263TYPE *h263type =
(OMX_VIDEO_PARAM_H263TYPE *)params;
if (!isValidOMXParam(h263type)) {
return OMX_ErrorBadParameter;
}
if (h263type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
h263type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
h263type->eProfile = OMX_VIDEO_H263ProfileBaseline;
h263type->eLevel = OMX_VIDEO_H263Level45;
h263type->bPLUSPTYPEAllowed = OMX_FALSE;
h263type->bForceRoundingTypeToZero = OMX_FALSE;
h263type->nPictureHeaderRepetition = 0;
h263type->nGOBHeaderInterval = 0;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoMpeg4:
{
OMX_VIDEO_PARAM_MPEG4TYPE *mpeg4type =
(OMX_VIDEO_PARAM_MPEG4TYPE *)params;
if (!isValidOMXParam(mpeg4type)) {
return OMX_ErrorBadParameter;
}
if (mpeg4type->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
mpeg4type->eProfile = OMX_VIDEO_MPEG4ProfileCore;
mpeg4type->eLevel = OMX_VIDEO_MPEG4Level2;
mpeg4type->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
mpeg4type->nBFrames = 0;
mpeg4type->nIDCVLCThreshold = 0;
mpeg4type->bACPred = OMX_TRUE;
mpeg4type->nMaxPacketSize = 256;
mpeg4type->nTimeIncRes = 1000;
mpeg4type->nHeaderExtension = 0;
mpeg4type->bReversibleVLC = OMX_FALSE;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
| 174,209 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: virtual InputMethodDescriptor current_input_method() const {
return current_input_method_;
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | virtual InputMethodDescriptor current_input_method() const {
virtual input_method::InputMethodDescriptor current_input_method() const {
return current_input_method_;
}
| 170,513 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void update_blocked_averages(int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct cfs_rq *cfs_rq, *pos;
const struct sched_class *curr_class;
struct rq_flags rf;
bool done = true;
rq_lock_irqsave(rq, &rf);
update_rq_clock(rq);
/*
* Iterates the task_group tree in a bottom up fashion, see
* list_add_leaf_cfs_rq() for details.
*/
for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) {
struct sched_entity *se;
/* throttled entities do not contribute to load */
if (throttled_hierarchy(cfs_rq))
continue;
if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
update_tg_load_avg(cfs_rq, 0);
/* Propagate pending load changes to the parent, if any: */
se = cfs_rq->tg->se[cpu];
if (se && !skip_blocked_update(se))
update_load_avg(cfs_rq_of(se), se, 0);
/*
* There can be a lot of idle CPU cgroups. Don't let fully
* decayed cfs_rqs linger on the list.
*/
if (cfs_rq_is_decayed(cfs_rq))
list_del_leaf_cfs_rq(cfs_rq);
/* Don't need periodic decay once load/util_avg are null */
if (cfs_rq_has_blocked(cfs_rq))
done = false;
}
curr_class = rq->curr->sched_class;
update_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class);
update_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class);
update_irq_load_avg(rq, 0);
/* Don't need periodic decay once load/util_avg are null */
if (others_have_blocked(rq))
done = false;
#ifdef CONFIG_NO_HZ_COMMON
rq->last_blocked_load_update_tick = jiffies;
if (done)
rq->has_blocked_load = 0;
#endif
rq_unlock_irqrestore(rq, &rf);
}
Commit Message: sched/fair: Fix infinite loop in update_blocked_averages() by reverting a9e7f6544b9c
Zhipeng Xie, Xie XiuQi and Sargun Dhillon reported lockups in the
scheduler under high loads, starting at around the v4.18 time frame,
and Zhipeng Xie tracked it down to bugs in the rq->leaf_cfs_rq_list
manipulation.
Do a (manual) revert of:
a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
It turns out that the list_del_leaf_cfs_rq() introduced by this commit
is a surprising property that was not considered in followup commits
such as:
9c2791f936ef ("sched/fair: Fix hierarchical order in rq->leaf_cfs_rq_list")
As Vincent Guittot explains:
"I think that there is a bigger problem with commit a9e7f6544b9c and
cfs_rq throttling:
Let take the example of the following topology TG2 --> TG1 --> root:
1) The 1st time a task is enqueued, we will add TG2 cfs_rq then TG1
cfs_rq to leaf_cfs_rq_list and we are sure to do the whole branch in
one path because it has never been used and can't be throttled so
tmp_alone_branch will point to leaf_cfs_rq_list at the end.
2) Then TG1 is throttled
3) and we add TG3 as a new child of TG1.
4) The 1st enqueue of a task on TG3 will add TG3 cfs_rq just before TG1
cfs_rq and tmp_alone_branch will stay on rq->leaf_cfs_rq_list.
With commit a9e7f6544b9c, we can del a cfs_rq from rq->leaf_cfs_rq_list.
So if the load of TG1 cfs_rq becomes NULL before step 2) above, TG1
cfs_rq is removed from the list.
Then at step 4), TG3 cfs_rq is added at the beginning of rq->leaf_cfs_rq_list
but tmp_alone_branch still points to TG3 cfs_rq because its throttled
parent can't be enqueued when the lock is released.
tmp_alone_branch doesn't point to rq->leaf_cfs_rq_list whereas it should.
So if TG3 cfs_rq is removed or destroyed before tmp_alone_branch
points on another TG cfs_rq, the next TG cfs_rq that will be added,
will be linked outside rq->leaf_cfs_rq_list - which is bad.
In addition, we can break the ordering of the cfs_rq in
rq->leaf_cfs_rq_list but this ordering is used to update and
propagate the update from leaf down to root."
Instead of trying to work through all these cases and trying to reproduce
the very high loads that produced the lockup to begin with, simplify
the code temporarily by reverting a9e7f6544b9c - which change was clearly
not thought through completely.
This (hopefully) gives us a kernel that doesn't lock up so people
can continue to enjoy their holidays without worrying about regressions. ;-)
[ mingo: Wrote changelog, fixed weird spelling in code comment while at it. ]
Analyzed-by: Xie XiuQi <[email protected]>
Analyzed-by: Vincent Guittot <[email protected]>
Reported-by: Zhipeng Xie <[email protected]>
Reported-by: Sargun Dhillon <[email protected]>
Reported-by: Xie XiuQi <[email protected]>
Tested-by: Zhipeng Xie <[email protected]>
Tested-by: Sargun Dhillon <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
Acked-by: Vincent Guittot <[email protected]>
Cc: <[email protected]> # v4.13+
Cc: Bin Li <[email protected]>
Cc: Mike Galbraith <[email protected]>
Cc: Peter Zijlstra <[email protected]>
Cc: Tejun Heo <[email protected]>
Cc: Thomas Gleixner <[email protected]>
Fixes: a9e7f6544b9c ("sched/fair: Fix O(nr_cgroups) in load balance path")
Link: http://lkml.kernel.org/r/[email protected]
Signed-off-by: Ingo Molnar <[email protected]>
CWE ID: CWE-400 | static void update_blocked_averages(int cpu)
{
struct rq *rq = cpu_rq(cpu);
struct cfs_rq *cfs_rq;
const struct sched_class *curr_class;
struct rq_flags rf;
bool done = true;
rq_lock_irqsave(rq, &rf);
update_rq_clock(rq);
/*
* Iterates the task_group tree in a bottom up fashion, see
* list_add_leaf_cfs_rq() for details.
*/
for_each_leaf_cfs_rq(rq, cfs_rq) {
struct sched_entity *se;
/* throttled entities do not contribute to load */
if (throttled_hierarchy(cfs_rq))
continue;
if (update_cfs_rq_load_avg(cfs_rq_clock_task(cfs_rq), cfs_rq))
update_tg_load_avg(cfs_rq, 0);
/* Propagate pending load changes to the parent, if any: */
se = cfs_rq->tg->se[cpu];
if (se && !skip_blocked_update(se))
update_load_avg(cfs_rq_of(se), se, 0);
/* Don't need periodic decay once load/util_avg are null */
if (cfs_rq_has_blocked(cfs_rq))
done = false;
}
curr_class = rq->curr->sched_class;
update_rt_rq_load_avg(rq_clock_task(rq), rq, curr_class == &rt_sched_class);
update_dl_rq_load_avg(rq_clock_task(rq), rq, curr_class == &dl_sched_class);
update_irq_load_avg(rq, 0);
/* Don't need periodic decay once load/util_avg are null */
if (others_have_blocked(rq))
done = false;
#ifdef CONFIG_NO_HZ_COMMON
rq->last_blocked_load_update_tick = jiffies;
if (done)
rq->has_blocked_load = 0;
#endif
rq_unlock_irqrestore(rq, &rf);
}
| 169,786 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ModuleExport size_t RegisterPSImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("EPI");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(
"Encapsulated PostScript Interchange format");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("EPS");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Encapsulated PostScript");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("EPSF");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Encapsulated PostScript");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("EPSI");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(
"Encapsulated PostScript Interchange format");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PS");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("PostScript");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
Commit Message: https://github.com/ImageMagick/ImageMagick/issues/715
CWE ID: CWE-834 | ModuleExport size_t RegisterPSImage(void)
{
MagickInfo
*entry;
entry=SetMagickInfo("EPI");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->seekable_stream=MagickTrue;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(
"Encapsulated PostScript Interchange format");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("EPS");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->seekable_stream=MagickTrue;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Encapsulated PostScript");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("EPSF");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->seekable_stream=MagickTrue;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("Encapsulated PostScript");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("EPSI");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->seekable_stream=MagickTrue;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->adjoin=MagickFalse;
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString(
"Encapsulated PostScript Interchange format");
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
(void) RegisterMagickInfo(entry);
entry=SetMagickInfo("PS");
entry->decoder=(DecodeImageHandler *) ReadPSImage;
entry->encoder=(EncodeImageHandler *) WritePSImage;
entry->seekable_stream=MagickTrue;
entry->magick=(IsImageFormatHandler *) IsPS;
entry->mime_type=ConstantString("application/postscript");
entry->module=ConstantString("PS");
entry->blob_support=MagickFalse;
entry->seekable_stream=MagickTrue;
entry->description=ConstantString("PostScript");
(void) RegisterMagickInfo(entry);
return(MagickImageCoderSignature);
}
| 167,763 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DestroySkImageOnOriginalThread(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
std::unique_ptr<gpu::SyncToken> sync_token) {
if (context_provider_wrapper &&
image->isValid(
context_provider_wrapper->ContextProvider()->GetGrContext())) {
if (sync_token->HasData()) {
context_provider_wrapper->ContextProvider()
->ContextGL()
->WaitSyncTokenCHROMIUM(sync_token->GetData());
}
image->getTexture()->textureParamsModified();
}
}
Commit Message: Fix *StaticBitmapImage ThreadChecker and unaccelerated SkImage destroy
- AcceleratedStaticBitmapImage was misusing ThreadChecker by having its
own detach logic. Using proper DetachThread is simpler, cleaner and
correct.
- UnacceleratedStaticBitmapImage didn't destroy the SkImage in the
proper thread, leading to GrContext/SkSp problems.
Bug: 890576
Change-Id: Ic71e7f7322b0b851774628247aa5256664bc0723
Reviewed-on: https://chromium-review.googlesource.com/c/1307775
Reviewed-by: Gabriel Charette <[email protected]>
Reviewed-by: Jeremy Roman <[email protected]>
Commit-Queue: Fernando Serboncini <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604427}
CWE ID: CWE-119 | void DestroySkImageOnOriginalThread(
sk_sp<SkImage> image,
base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider_wrapper,
std::unique_ptr<gpu::SyncToken> sync_token) {
if (context_provider_wrapper &&
image->isValid(
context_provider_wrapper->ContextProvider()->GetGrContext())) {
if (sync_token->HasData()) {
context_provider_wrapper->ContextProvider()
->ContextGL()
->WaitSyncTokenCHROMIUM(sync_token->GetData());
}
image->getTexture()->textureParamsModified();
}
image.reset();
}
| 172,593 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: long mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos,
long long size_, double& result) {
assert(pReader);
assert(pos >= 0);
if ((size_ != 4) && (size_ != 8))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) // error
return status;
if (size == 4) {
union {
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;) {
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
} else {
assert(size == 8);
union {
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;) {
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
return 0;
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long mkvparser::UnserializeFloat(IMkvReader* pReader, long long pos,
long UnserializeFloat(IMkvReader* pReader, long long pos, long long size_,
double& result) {
if (!pReader || pos < 0 || ((size_ != 4) && (size_ != 8)))
return E_FILE_FORMAT_INVALID;
const long size = static_cast<long>(size_);
unsigned char buf[8];
const int status = pReader->Read(pos, size, buf);
if (status < 0) // error
return status;
if (size == 4) {
union {
float f;
unsigned long ff;
};
ff = 0;
for (int i = 0;;) {
ff |= buf[i];
if (++i >= 4)
break;
ff <<= 8;
}
result = f;
} else {
union {
double d;
unsigned long long dd;
};
dd = 0;
for (int i = 0;;) {
dd |= buf[i];
if (++i >= 8)
break;
dd <<= 8;
}
result = d;
}
if (std::isinf(result) || std::isnan(result))
return E_FILE_FORMAT_INVALID;
return 0;
}
| 173,865 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void print_maps(struct pid_info_t* info)
{
FILE *maps;
size_t offset;
char device[10];
long int inode;
char file[PATH_MAX];
strlcat(info->path, "maps", sizeof(info->path));
maps = fopen(info->path, "r");
if (!maps)
goto out;
while (fscanf(maps, "%*x-%*x %*s %zx %s %ld %s\n", &offset, device, &inode,
file) == 4) {
if (inode == 0 || !strcmp(device, "00:00"))
continue;
printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n",
info->cmdline, info->pid, info->user, "mem",
"???", device, offset, inode, file);
}
fclose(maps);
out:
info->path[info->parent_length] = '\0';
}
Commit Message: Fix scanf %s in lsof.
Bug: http://b/28175237
Change-Id: Ief0ba299b09693ad9afc0e3d17a8f664c2fbb8c2
CWE ID: CWE-20 | static void print_maps(struct pid_info_t* info)
{
FILE *maps;
size_t offset;
char device[10];
long int inode;
char file[1024];
strlcat(info->path, "maps", sizeof(info->path));
maps = fopen(info->path, "r");
if (!maps)
goto out;
while (fscanf(maps, "%*x-%*x %*s %zx %5s %ld %1023s\n",
&offset, device, &inode, file) == 4) {
if (inode == 0 || !strcmp(device, "00:00"))
continue;
printf("%-9s %5d %10s %4s %9s %18s %9zd %10ld %s\n",
info->cmdline, info->pid, info->user, "mem",
"???", device, offset, inode, file);
}
fclose(maps);
out:
info->path[info->parent_length] = '\0';
}
| 173,560 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)
{
return usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
RTL8150_REQ_GET_REGS, RTL8150_REQT_READ,
indx, 0, data, size, 500);
}
Commit Message: rtl8150: Use heap buffers for all register access
Allocating USB buffers on the stack is not portable, and no longer
works on x86_64 (with VMAP_STACK enabled as per default).
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Ben Hutchings <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | static int get_registers(rtl8150_t * dev, u16 indx, u16 size, void *data)
{
void *buf;
int ret;
buf = kmalloc(size, GFP_NOIO);
if (!buf)
return -ENOMEM;
ret = usb_control_msg(dev->udev, usb_rcvctrlpipe(dev->udev, 0),
RTL8150_REQ_GET_REGS, RTL8150_REQT_READ,
indx, 0, buf, size, 500);
if (ret > 0 && ret <= size)
memcpy(data, buf, ret);
kfree(buf);
return ret;
}
| 168,214 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void vp8_decoder_remove_threads(VP8D_COMP *pbi)
{
/* shutdown MB Decoding thread; */
if (pbi->b_multithreaded_rd)
{
int i;
pbi->b_multithreaded_rd = 0;
/* allow all threads to exit */
for (i = 0; i < pbi->allocated_decoding_thread_count; i++)
{
sem_post(&pbi->h_event_start_decoding[i]);
pthread_join(pbi->h_decoding_thread[i], NULL);
}
for (i = 0; i < pbi->allocated_decoding_thread_count; i++)
{
sem_destroy(&pbi->h_event_start_decoding[i]);
}
sem_destroy(&pbi->h_event_end_decoding);
vpx_free(pbi->h_decoding_thread);
pbi->h_decoding_thread = NULL;
vpx_free(pbi->h_event_start_decoding);
pbi->h_event_start_decoding = NULL;
vpx_free(pbi->mb_row_di);
pbi->mb_row_di = NULL ;
vpx_free(pbi->de_thread_data);
pbi->de_thread_data = NULL;
}
}
Commit Message: vp8:fix threading issues
1 - stops de allocating before threads are closed.
2 - limits threads to mb_rows when mb_rows < partitions
BUG=webm:851
Bug: 30436808
Change-Id: Ie017818ed28103ca9d26d57087f31361b642e09b
(cherry picked from commit 70cca742efa20617c70c3209aa614a70f282f90e)
CWE ID: | void vp8_decoder_remove_threads(VP8D_COMP *pbi)
void vp8_decoder_remove_threads(VP8D_COMP *pbi) {
/* shutdown MB Decoding thread; */
if (pbi->b_multithreaded_rd) {
int i;
pbi->b_multithreaded_rd = 0;
/* allow all threads to exit */
for (i = 0; i < pbi->allocated_decoding_thread_count; ++i) {
sem_post(&pbi->h_event_start_decoding[i]);
pthread_join(pbi->h_decoding_thread[i], NULL);
}
for (i = 0; i < pbi->allocated_decoding_thread_count; ++i) {
sem_destroy(&pbi->h_event_start_decoding[i]);
}
sem_destroy(&pbi->h_event_end_decoding);
vpx_free(pbi->h_decoding_thread);
pbi->h_decoding_thread = NULL;
vpx_free(pbi->h_event_start_decoding);
pbi->h_event_start_decoding = NULL;
vpx_free(pbi->mb_row_di);
pbi->mb_row_di = NULL;
vpx_free(pbi->de_thread_data);
pbi->de_thread_data = NULL;
vp8mt_de_alloc_temp_buffers(pbi, pbi->common.mb_rows);
}
}
| 174,067 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void SoftG711::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nFilledLen > kMaxNumSamplesPerFrame) {
ALOGE("input buffer too large (%d).", inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
}
const uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset;
if (mIsMLaw) {
DecodeMLaw(
reinterpret_cast<int16_t *>(outHeader->pBuffer),
inputptr, inHeader->nFilledLen);
} else {
DecodeALaw(
reinterpret_cast<int16_t *>(outHeader->pBuffer),
inputptr, inHeader->nFilledLen);
}
outHeader->nTimeStamp = inHeader->nTimeStamp;
outHeader->nOffset = 0;
outHeader->nFilledLen = inHeader->nFilledLen * sizeof(int16_t);
outHeader->nFlags = 0;
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
Commit Message: codecs: check OMX buffer size before use in (gsm|g711)dec
Bug: 27793163
Bug: 27793367
Change-Id: Iec3de8a237ee2379d87a8371c13e543878c6652c
CWE ID: CWE-119 | void SoftG711::onQueueFilled(OMX_U32 /* portIndex */) {
if (mSignalledError) {
return;
}
List<BufferInfo *> &inQueue = getPortQueue(0);
List<BufferInfo *> &outQueue = getPortQueue(1);
while (!inQueue.empty() && !outQueue.empty()) {
BufferInfo *inInfo = *inQueue.begin();
OMX_BUFFERHEADERTYPE *inHeader = inInfo->mHeader;
BufferInfo *outInfo = *outQueue.begin();
OMX_BUFFERHEADERTYPE *outHeader = outInfo->mHeader;
if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
outHeader->nFilledLen = 0;
outHeader->nFlags = OMX_BUFFERFLAG_EOS;
outQueue.erase(outQueue.begin());
outInfo->mOwnedByUs = false;
notifyFillBufferDone(outHeader);
return;
}
if (inHeader->nFilledLen > kMaxNumSamplesPerFrame) {
ALOGE("input buffer too large (%d).", inHeader->nFilledLen);
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
}
if (inHeader->nFilledLen * sizeof(int16_t) > outHeader->nAllocLen) {
ALOGE("output buffer too small (%d).", outHeader->nAllocLen);
android_errorWriteLog(0x534e4554, "27793163");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
const uint8_t *inputptr = inHeader->pBuffer + inHeader->nOffset;
if (mIsMLaw) {
DecodeMLaw(
reinterpret_cast<int16_t *>(outHeader->pBuffer),
inputptr, inHeader->nFilledLen);
} else {
DecodeALaw(
reinterpret_cast<int16_t *>(outHeader->pBuffer),
inputptr, inHeader->nFilledLen);
}
outHeader->nTimeStamp = inHeader->nTimeStamp;
outHeader->nOffset = 0;
outHeader->nFilledLen = inHeader->nFilledLen * sizeof(int16_t);
outHeader->nFlags = 0;
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
}
}
| 173,778 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void process_blob(struct rev_info *revs,
struct blob *blob,
show_object_fn show,
struct strbuf *path,
const char *name,
void *cb_data)
{
struct object *obj = &blob->object;
if (!revs->blob_objects)
return;
if (!obj)
die("bad blob object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
obj->flags |= SEEN;
show(obj, path, name, cb_data);
}
Commit Message: list-objects: pass full pathname to callbacks
When we find a blob at "a/b/c", we currently pass this to
our show_object_fn callbacks as two components: "a/b/" and
"c". Callbacks which want the full value then call
path_name(), which concatenates the two. But this is an
inefficient interface; the path is a strbuf, and we could
simply append "c" to it temporarily, then roll back the
length, without creating a new copy.
So we could improve this by teaching the callsites of
path_name() this trick (and there are only 3). But we can
also notice that no callback actually cares about the
broken-down representation, and simply pass each callback
the full path "a/b/c" as a string. The callback code becomes
even simpler, then, as we do not have to worry about freeing
an allocated buffer, nor rolling back our modification to
the strbuf.
This is theoretically less efficient, as some callbacks
would not bother to format the final path component. But in
practice this is not measurable. Since we use the same
strbuf over and over, our work to grow it is amortized, and
we really only pay to memcpy a few bytes.
Signed-off-by: Jeff King <[email protected]>
Signed-off-by: Junio C Hamano <[email protected]>
CWE ID: CWE-119 | static void process_blob(struct rev_info *revs,
struct blob *blob,
show_object_fn show,
struct strbuf *path,
const char *name,
void *cb_data)
{
struct object *obj = &blob->object;
size_t pathlen;
if (!revs->blob_objects)
return;
if (!obj)
die("bad blob object");
if (obj->flags & (UNINTERESTING | SEEN))
return;
obj->flags |= SEEN;
pathlen = path->len;
strbuf_addstr(path, name);
show(obj, path->buf, cb_data);
strbuf_setlen(path, pathlen);
}
| 167,418 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: SampleTable::SampleTable(const sp<DataSource> &source)
: mDataSource(source),
mChunkOffsetOffset(-1),
mChunkOffsetType(0),
mNumChunkOffsets(0),
mSampleToChunkOffset(-1),
mNumSampleToChunkOffsets(0),
mSampleSizeOffset(-1),
mSampleSizeFieldSize(0),
mDefaultSampleSize(0),
mNumSampleSizes(0),
mTimeToSampleCount(0),
mTimeToSample(),
mSampleTimeEntries(NULL),
mCompositionTimeDeltaEntries(NULL),
mNumCompositionTimeDeltaEntries(0),
mCompositionDeltaLookup(new CompositionDeltaLookup),
mSyncSampleOffset(-1),
mNumSyncSamples(0),
mSyncSamples(NULL),
mLastSyncSampleIndex(0),
mSampleToChunkEntries(NULL) {
mSampleIterator = new SampleIterator(this);
}
Commit Message: SampleTable.cpp: Fixed a regression caused by a fix for bug
28076789.
Detail: Before the original fix
(Id207f369ab7b27787d83f5d8fc48dc53ed9fcdc9) for 28076789, the
code allowed a time-to-sample table size to be 0. The change
made in that fix disallowed such situation, which in fact should
be allowed. This current patch allows it again while maintaining
the security of the previous fix.
Bug: 28288202
Bug: 28076789
Change-Id: I1c9a60c7f0cfcbd3d908f24998dde15d5136a295
CWE ID: CWE-20 | SampleTable::SampleTable(const sp<DataSource> &source)
: mDataSource(source),
mChunkOffsetOffset(-1),
mChunkOffsetType(0),
mNumChunkOffsets(0),
mSampleToChunkOffset(-1),
mNumSampleToChunkOffsets(0),
mSampleSizeOffset(-1),
mSampleSizeFieldSize(0),
mDefaultSampleSize(0),
mNumSampleSizes(0),
mHasTimeToSample(false),
mTimeToSampleCount(0),
mTimeToSample(),
mSampleTimeEntries(NULL),
mCompositionTimeDeltaEntries(NULL),
mNumCompositionTimeDeltaEntries(0),
mCompositionDeltaLookup(new CompositionDeltaLookup),
mSyncSampleOffset(-1),
mNumSyncSamples(0),
mSyncSamples(NULL),
mLastSyncSampleIndex(0),
mSampleToChunkEntries(NULL) {
mSampleIterator = new SampleIterator(this);
}
| 173,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int bochs_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVBochsState *s = bs->opaque;
uint32_t i;
struct bochs_header bochs;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs));
if (ret < 0) {
return ret;
}
if (strcmp(bochs.magic, HEADER_MAGIC) ||
strcmp(bochs.type, REDOLOG_TYPE) ||
strcmp(bochs.subtype, GROWING_TYPE) ||
((le32_to_cpu(bochs.version) != HEADER_VERSION) &&
(le32_to_cpu(bochs.version) != HEADER_V1))) {
error_setg(errp, "Image not in Bochs format");
return -EINVAL;
}
if (le32_to_cpu(bochs.version) == HEADER_V1) {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512;
} else {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;
}
s->catalog_size = le32_to_cpu(bochs.catalog);
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,
s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4);
s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512;
s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512;
s->extent_size = le32_to_cpu(bochs.extent);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
s->extent_size = le32_to_cpu(bochs.extent);
qemu_co_mutex_init(&s->lock);
return 0;
extent_index = offset / s->extent_size;
extent_offset = (offset % s->extent_size) / 512;
if (s->catalog_bitmap[extent_index] == 0xffffffff) {
return -1; /* not allocated */
}
bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] *
(s->extent_blocks + s->bitmap_blocks));
/* read in bitmap for current extent */
if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8),
&bitmap_entry, 1) != 1) {
return -1;
}
if (!((bitmap_entry >> (extent_offset % 8)) & 1)) {
return -1; /* not allocated */
}
return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset));
}
Commit Message:
CWE ID: CWE-190 | static int bochs_open(BlockDriverState *bs, QDict *options, int flags,
Error **errp)
{
BDRVBochsState *s = bs->opaque;
uint32_t i;
struct bochs_header bochs;
int ret;
bs->read_only = 1; // no write support yet
ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs));
if (ret < 0) {
return ret;
}
if (strcmp(bochs.magic, HEADER_MAGIC) ||
strcmp(bochs.type, REDOLOG_TYPE) ||
strcmp(bochs.subtype, GROWING_TYPE) ||
((le32_to_cpu(bochs.version) != HEADER_VERSION) &&
(le32_to_cpu(bochs.version) != HEADER_V1))) {
error_setg(errp, "Image not in Bochs format");
return -EINVAL;
}
if (le32_to_cpu(bochs.version) == HEADER_V1) {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512;
} else {
bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;
}
/* Limit to 1M entries to avoid unbounded allocation. This is what is
* needed for the largest image that bximage can create (~8 TB). */
s->catalog_size = le32_to_cpu(bochs.catalog);
if (s->catalog_size > 0x100000) {
error_setg(errp, "Catalog size is too large");
return -EFBIG;
}
s->catalog_bitmap = g_malloc(s->catalog_size * 4);
ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,
s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4);
s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512;
s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512;
s->extent_size = le32_to_cpu(bochs.extent);
qemu_co_mutex_init(&s->lock);
return 0;
fail:
s->extent_size = le32_to_cpu(bochs.extent);
if (s->catalog_size < bs->total_sectors / s->extent_size) {
error_setg(errp, "Catalog size is too small for this disk size");
ret = -EINVAL;
goto fail;
}
qemu_co_mutex_init(&s->lock);
return 0;
extent_index = offset / s->extent_size;
extent_offset = (offset % s->extent_size) / 512;
if (s->catalog_bitmap[extent_index] == 0xffffffff) {
return -1; /* not allocated */
}
bitmap_offset = s->data_offset + (512 * s->catalog_bitmap[extent_index] *
(s->extent_blocks + s->bitmap_blocks));
/* read in bitmap for current extent */
if (bdrv_pread(bs->file, bitmap_offset + (extent_offset / 8),
&bitmap_entry, 1) != 1) {
return -1;
}
if (!((bitmap_entry >> (extent_offset % 8)) & 1)) {
return -1; /* not allocated */
}
return bitmap_offset + (512 * (s->bitmap_blocks + extent_offset));
}
| 165,404 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WorkerProcessLauncher::Core::StopWorker() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
if (launch_success_timer_->IsRunning()) {
launch_success_timer_->Stop();
launch_backoff_.InformOfRequest(false);
}
self_ = this;
ipc_enabled_ = false;
if (process_watcher_.GetWatchedObject() != NULL) {
launcher_delegate_->KillProcess(CONTROL_C_EXIT);
return;
}
DCHECK(process_watcher_.GetWatchedObject() == NULL);
ipc_error_timer_->Stop();
process_exit_event_.Close();
if (stopping_) {
ipc_error_timer_.reset();
launch_timer_.reset();
self_ = NULL;
return;
}
self_ = NULL;
DWORD exit_code = launcher_delegate_->GetExitCode();
if (kMinPermanentErrorExitCode <= exit_code &&
exit_code <= kMaxPermanentErrorExitCode) {
worker_delegate_->OnPermanentError();
return;
}
launch_timer_->Start(FROM_HERE, launch_backoff_.GetTimeUntilRelease(),
this, &Core::LaunchWorker);
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void WorkerProcessLauncher::Core::StopWorker() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
// Keep the object alive in case one of delegates decides to delete |this|.
scoped_refptr<Core> self = this;
if (launch_success_timer_->IsRunning()) {
launch_success_timer_->Stop();
launch_backoff_.InformOfRequest(false);
}
ipc_enabled_ = false;
if (process_watcher_.GetWatchedObject() != NULL) {
launcher_delegate_->KillProcess(CONTROL_C_EXIT);
// Wait until the process is actually stopped if the caller keeps
// a reference to |this|. Otherwise terminate everything right now - there
// won't be a second chance.
if (!stopping_)
return;
process_watcher_.StopWatching();
}
ipc_error_timer_->Stop();
process_exit_event_.Close();
if (stopping_) {
ipc_error_timer_.reset();
launch_timer_.reset();
return;
}
if (launcher_delegate_->IsPermanentError(launch_backoff_.failure_count())) {
if (!stopping_)
worker_delegate_->OnPermanentError();
} else {
// Schedule the next attempt to launch the worker process.
launch_timer_->Start(FROM_HERE, launch_backoff_.GetTimeUntilRelease(),
this, &Core::LaunchWorker);
}
}
| 171,549 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev,
struct nci_rf_intf_activated_ntf *ntf, __u8 *data)
{
struct activation_params_nfca_poll_iso_dep *nfca_poll;
struct activation_params_nfcb_poll_iso_dep *nfcb_poll;
switch (ntf->activation_rf_tech_and_mode) {
case NCI_NFC_A_PASSIVE_POLL_MODE:
nfca_poll = &ntf->activation_params.nfca_poll_iso_dep;
nfca_poll->rats_res_len = *data++;
pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len);
if (nfca_poll->rats_res_len > 0) {
memcpy(nfca_poll->rats_res,
data, nfca_poll->rats_res_len);
}
break;
case NCI_NFC_B_PASSIVE_POLL_MODE:
nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep;
nfcb_poll->attrib_res_len = *data++;
pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len);
if (nfcb_poll->attrib_res_len > 0) {
memcpy(nfcb_poll->attrib_res,
data, nfcb_poll->attrib_res_len);
}
break;
default:
pr_err("unsupported activation_rf_tech_and_mode 0x%x\n",
ntf->activation_rf_tech_and_mode);
return NCI_STATUS_RF_PROTOCOL_ERROR;
}
return NCI_STATUS_OK;
}
Commit Message: NFC: Prevent multiple buffer overflows in NCI
Fix multiple remotely-exploitable stack-based buffer overflows due to
the NCI code pulling length fields directly from incoming frames and
copying too much data into statically-sized arrays.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: [email protected]
Cc: [email protected]
Cc: Lauro Ramos Venancio <[email protected]>
Cc: Aloisio Almeida Jr <[email protected]>
Cc: Samuel Ortiz <[email protected]>
Cc: David S. Miller <[email protected]>
Acked-by: Ilan Elias <[email protected]>
Signed-off-by: Samuel Ortiz <[email protected]>
CWE ID: CWE-119 | static int nci_extract_activation_params_iso_dep(struct nci_dev *ndev,
struct nci_rf_intf_activated_ntf *ntf, __u8 *data)
{
struct activation_params_nfca_poll_iso_dep *nfca_poll;
struct activation_params_nfcb_poll_iso_dep *nfcb_poll;
switch (ntf->activation_rf_tech_and_mode) {
case NCI_NFC_A_PASSIVE_POLL_MODE:
nfca_poll = &ntf->activation_params.nfca_poll_iso_dep;
nfca_poll->rats_res_len = min_t(__u8, *data++, 20);
pr_debug("rats_res_len %d\n", nfca_poll->rats_res_len);
if (nfca_poll->rats_res_len > 0) {
memcpy(nfca_poll->rats_res,
data, nfca_poll->rats_res_len);
}
break;
case NCI_NFC_B_PASSIVE_POLL_MODE:
nfcb_poll = &ntf->activation_params.nfcb_poll_iso_dep;
nfcb_poll->attrib_res_len = min_t(__u8, *data++, 50);
pr_debug("attrib_res_len %d\n", nfcb_poll->attrib_res_len);
if (nfcb_poll->attrib_res_len > 0) {
memcpy(nfcb_poll->attrib_res,
data, nfcb_poll->attrib_res_len);
}
break;
default:
pr_err("unsupported activation_rf_tech_and_mode 0x%x\n",
ntf->activation_rf_tech_and_mode);
return NCI_STATUS_RF_PROTOCOL_ERROR;
}
return NCI_STATUS_OK;
}
| 166,200 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void StoreExistingGroupExistingCache() {
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
EXPECT_EQ(kDefaultEntrySize, storage()->usage_map_[kOrigin]);
base::Time now = base::Time::Now();
cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::MASTER, 1, 100));
cache_->set_update_time(now);
PushNextTask(base::BindOnce(
&AppCacheStorageImplTest::Verify_StoreExistingGroupExistingCache,
base::Unretained(this), now));
EXPECT_EQ(cache_.get(), group_->newest_complete_cache());
storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate());
EXPECT_FALSE(delegate()->stored_group_success_);
}
Commit Message: Reland "AppCache: Add padding to cross-origin responses."
This is a reland of 85b389caa7d725cdd31f59e9a2b79ff54804b7b7
Initialized CacheRecord::padding_size to 0.
Original change's description:
> AppCache: Add padding to cross-origin responses.
>
> Bug: 918293
> Change-Id: I4f16640f06feac009d6bbbb624951da6d2669f6c
> Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1488059
> Commit-Queue: Staphany Park <[email protected]>
> Reviewed-by: Victor Costan <[email protected]>
> Reviewed-by: Marijn Kruisselbrink <[email protected]>
> Cr-Commit-Position: refs/heads/master@{#644624}
Bug: 918293
Change-Id: Ie1d3f99c7e8a854d33255a4d66243da2ce16441c
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1539906
Reviewed-by: Victor Costan <[email protected]>
Commit-Queue: Staphany Park <[email protected]>
Cr-Commit-Position: refs/heads/master@{#644719}
CWE ID: CWE-200 | void StoreExistingGroupExistingCache() {
MakeCacheAndGroup(kManifestUrl, 1, 1, true);
EXPECT_EQ(kDefaultEntrySize + kDefaultEntryPadding,
storage()->usage_map_[kOrigin]);
base::Time now = base::Time::Now();
cache_->AddEntry(kEntryUrl, AppCacheEntry(AppCacheEntry::EXPLICIT,
/*response_id=*/1,
/*response_size=*/100,
/*padding_size=*/10));
cache_->set_update_time(now);
PushNextTask(base::BindOnce(
&AppCacheStorageImplTest::Verify_StoreExistingGroupExistingCache,
base::Unretained(this), now));
EXPECT_EQ(cache_.get(), group_->newest_complete_cache());
storage()->StoreGroupAndNewestCache(group_.get(), cache_.get(), delegate());
EXPECT_FALSE(delegate()->stored_group_success_);
}
| 172,990 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void construct_get_dest_keyring(struct key **_dest_keyring)
{
struct request_key_auth *rka;
const struct cred *cred = current_cred();
struct key *dest_keyring = *_dest_keyring, *authkey;
kenter("%p", dest_keyring);
/* find the appropriate keyring */
if (dest_keyring) {
/* the caller supplied one */
key_get(dest_keyring);
} else {
/* use a default keyring; falling through the cases until we
* find one that we actually have */
switch (cred->jit_keyring) {
case KEY_REQKEY_DEFL_DEFAULT:
case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
if (cred->request_key_auth) {
authkey = cred->request_key_auth;
down_read(&authkey->sem);
rka = authkey->payload.data[0];
if (!test_bit(KEY_FLAG_REVOKED,
&authkey->flags))
dest_keyring =
key_get(rka->dest_keyring);
up_read(&authkey->sem);
if (dest_keyring)
break;
}
case KEY_REQKEY_DEFL_THREAD_KEYRING:
dest_keyring = key_get(cred->thread_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_PROCESS_KEYRING:
dest_keyring = key_get(cred->process_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_SESSION_KEYRING:
rcu_read_lock();
dest_keyring = key_get(
rcu_dereference(cred->session_keyring));
rcu_read_unlock();
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
dest_keyring =
key_get(cred->user->session_keyring);
break;
case KEY_REQKEY_DEFL_USER_KEYRING:
dest_keyring = key_get(cred->user->uid_keyring);
break;
case KEY_REQKEY_DEFL_GROUP_KEYRING:
default:
BUG();
}
}
*_dest_keyring = dest_keyring;
kleave(" [dk %d]", key_serial(dest_keyring));
return;
}
Commit Message: KEYS: add missing permission check for request_key() destination
When the request_key() syscall is not passed a destination keyring, it
links the requested key (if constructed) into the "default" request-key
keyring. This should require Write permission to the keyring. However,
there is actually no permission check.
This can be abused to add keys to any keyring to which only Search
permission is granted. This is because Search permission allows joining
the keyring. keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_SESSION_KEYRING)
then will set the default request-key keyring to the session keyring.
Then, request_key() can be used to add keys to the keyring.
Both negatively and positively instantiated keys can be added using this
method. Adding negative keys is trivial. Adding a positive key is a
bit trickier. It requires that either /sbin/request-key positively
instantiates the key, or that another thread adds the key to the process
keyring at just the right time, such that request_key() misses it
initially but then finds it in construct_alloc_key().
Fix this bug by checking for Write permission to the keyring in
construct_get_dest_keyring() when the default keyring is being used.
We don't do the permission check for non-default keyrings because that
was already done by the earlier call to lookup_user_key(). Also,
request_key_and_link() is currently passed a 'struct key *' rather than
a key_ref_t, so the "possessed" bit is unavailable.
We also don't do the permission check for the "requestor keyring", to
continue to support the use case described by commit 8bbf4976b59f
("KEYS: Alter use of key instantiation link-to-keyring argument") where
/sbin/request-key recursively calls request_key() to add keys to the
original requestor's destination keyring. (I don't know of any users
who actually do that, though...)
Fixes: 3e30148c3d52 ("[PATCH] Keys: Make request-key create an authorisation key")
Cc: <[email protected]> # v2.6.13+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: David Howells <[email protected]>
CWE ID: CWE-862 | static void construct_get_dest_keyring(struct key **_dest_keyring)
static int construct_get_dest_keyring(struct key **_dest_keyring)
{
struct request_key_auth *rka;
const struct cred *cred = current_cred();
struct key *dest_keyring = *_dest_keyring, *authkey;
int ret;
kenter("%p", dest_keyring);
/* find the appropriate keyring */
if (dest_keyring) {
/* the caller supplied one */
key_get(dest_keyring);
} else {
bool do_perm_check = true;
/* use a default keyring; falling through the cases until we
* find one that we actually have */
switch (cred->jit_keyring) {
case KEY_REQKEY_DEFL_DEFAULT:
case KEY_REQKEY_DEFL_REQUESTOR_KEYRING:
if (cred->request_key_auth) {
authkey = cred->request_key_auth;
down_read(&authkey->sem);
rka = authkey->payload.data[0];
if (!test_bit(KEY_FLAG_REVOKED,
&authkey->flags))
dest_keyring =
key_get(rka->dest_keyring);
up_read(&authkey->sem);
if (dest_keyring) {
do_perm_check = false;
break;
}
}
case KEY_REQKEY_DEFL_THREAD_KEYRING:
dest_keyring = key_get(cred->thread_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_PROCESS_KEYRING:
dest_keyring = key_get(cred->process_keyring);
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_SESSION_KEYRING:
rcu_read_lock();
dest_keyring = key_get(
rcu_dereference(cred->session_keyring));
rcu_read_unlock();
if (dest_keyring)
break;
case KEY_REQKEY_DEFL_USER_SESSION_KEYRING:
dest_keyring =
key_get(cred->user->session_keyring);
break;
case KEY_REQKEY_DEFL_USER_KEYRING:
dest_keyring = key_get(cred->user->uid_keyring);
break;
case KEY_REQKEY_DEFL_GROUP_KEYRING:
default:
BUG();
}
/*
* Require Write permission on the keyring. This is essential
* because the default keyring may be the session keyring, and
* joining a keyring only requires Search permission.
*
* However, this check is skipped for the "requestor keyring" so
* that /sbin/request-key can itself use request_key() to add
* keys to the original requestor's destination keyring.
*/
if (dest_keyring && do_perm_check) {
ret = key_permission(make_key_ref(dest_keyring, 1),
KEY_NEED_WRITE);
if (ret) {
key_put(dest_keyring);
return ret;
}
}
}
*_dest_keyring = dest_keyring;
kleave(" [dk %d]", key_serial(dest_keyring));
return 0;
}
| 167,647 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltFreeTemplateHashes(xsltStylesheetPtr style) {
if (style->templatesHash != NULL)
xmlHashFree((xmlHashTablePtr) style->templatesHash,
(xmlHashDeallocator) xsltFreeCompMatchList);
if (style->rootMatch != NULL)
xsltFreeCompMatchList(style->rootMatch);
if (style->keyMatch != NULL)
xsltFreeCompMatchList(style->keyMatch);
if (style->elemMatch != NULL)
xsltFreeCompMatchList(style->elemMatch);
if (style->attrMatch != NULL)
xsltFreeCompMatchList(style->attrMatch);
if (style->parentMatch != NULL)
xsltFreeCompMatchList(style->parentMatch);
if (style->textMatch != NULL)
xsltFreeCompMatchList(style->textMatch);
if (style->piMatch != NULL)
xsltFreeCompMatchList(style->piMatch);
if (style->commentMatch != NULL)
xsltFreeCompMatchList(style->commentMatch);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltFreeTemplateHashes(xsltStylesheetPtr style) {
if (style->templatesHash != NULL)
xmlHashFree((xmlHashTablePtr) style->templatesHash,
(xmlHashDeallocator) xsltFreeCompMatchList);
if (style->rootMatch != NULL)
xsltFreeCompMatchList(style->rootMatch);
if (style->keyMatch != NULL)
xsltFreeCompMatchList(style->keyMatch);
if (style->elemMatch != NULL)
xsltFreeCompMatchList(style->elemMatch);
if (style->attrMatch != NULL)
xsltFreeCompMatchList(style->attrMatch);
if (style->parentMatch != NULL)
xsltFreeCompMatchList(style->parentMatch);
if (style->textMatch != NULL)
xsltFreeCompMatchList(style->textMatch);
if (style->piMatch != NULL)
xsltFreeCompMatchList(style->piMatch);
if (style->commentMatch != NULL)
xsltFreeCompMatchList(style->commentMatch);
if (style->namedTemplates != NULL)
xmlHashFree(style->namedTemplates, NULL);
}
| 173,312 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MojoAudioInputStream::OnStreamCreated(
int stream_id,
const base::SharedMemory* shared_memory,
std::unique_ptr<base::CancelableSyncSocket> foreign_socket,
bool initially_muted) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(stream_created_callback_);
DCHECK(shared_memory);
DCHECK(foreign_socket);
base::SharedMemoryHandle foreign_memory_handle =
shared_memory->GetReadOnlyHandle();
if (!base::SharedMemory::IsHandleValid(foreign_memory_handle)) {
OnStreamError(/*not used*/ 0);
return;
}
mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(
foreign_memory_handle, shared_memory->requested_size(),
/*read_only*/ true);
mojo::ScopedHandle socket_handle =
mojo::WrapPlatformFile(foreign_socket->Release());
DCHECK(buffer_handle.is_valid());
DCHECK(socket_handle.is_valid());
base::ResetAndReturn(&stream_created_callback_)
.Run(std::move(buffer_handle), std::move(socket_handle), initially_muted);
}
Commit Message: Correct mojo::WrapSharedMemoryHandle usage
Fixes some incorrect uses of mojo::WrapSharedMemoryHandle which
were assuming that the call actually has any control over the memory
protection applied to a handle when mapped.
Where fixing usage is infeasible for this CL, TODOs are added to
annotate follow-up work.
Also updates the API and documentation to (hopefully) improve clarity
and avoid similar mistakes from being made in the future.
BUG=792900
Cq-Include-Trybots: master.tryserver.chromium.android:android_optional_gpu_tests_rel;master.tryserver.chromium.linux:linux_optional_gpu_tests_rel;master.tryserver.chromium.mac:mac_optional_gpu_tests_rel;master.tryserver.chromium.win:win_optional_gpu_tests_rel
Change-Id: I0578aaa9ca3bfcb01aaf2451315d1ede95458477
Reviewed-on: https://chromium-review.googlesource.com/818282
Reviewed-by: Wei Li <[email protected]>
Reviewed-by: Lei Zhang <[email protected]>
Reviewed-by: John Abd-El-Malek <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Sadrul Chowdhury <[email protected]>
Reviewed-by: Yuzhu Shen <[email protected]>
Reviewed-by: Robert Sesek <[email protected]>
Commit-Queue: Ken Rockot <[email protected]>
Cr-Commit-Position: refs/heads/master@{#530268}
CWE ID: CWE-787 | void MojoAudioInputStream::OnStreamCreated(
int stream_id,
const base::SharedMemory* shared_memory,
std::unique_ptr<base::CancelableSyncSocket> foreign_socket,
bool initially_muted) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(stream_created_callback_);
DCHECK(shared_memory);
DCHECK(foreign_socket);
base::SharedMemoryHandle foreign_memory_handle =
shared_memory->GetReadOnlyHandle();
if (!base::SharedMemory::IsHandleValid(foreign_memory_handle)) {
OnStreamError(/*not used*/ 0);
return;
}
mojo::ScopedSharedBufferHandle buffer_handle = mojo::WrapSharedMemoryHandle(
foreign_memory_handle, shared_memory->requested_size(),
mojo::UnwrappedSharedMemoryHandleProtection::kReadOnly);
mojo::ScopedHandle socket_handle =
mojo::WrapPlatformFile(foreign_socket->Release());
DCHECK(buffer_handle.is_valid());
DCHECK(socket_handle.is_valid());
base::ResetAndReturn(&stream_created_callback_)
.Run(std::move(buffer_handle), std::move(socket_handle), initially_muted);
}
| 172,877 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: ikev1_id_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
#define USE_IPSECDOI_IN_PHASE1 1
const struct ikev1_pl_id *p;
struct ikev1_pl_id id;
static const char *idtypestr[] = {
"IPv4", "IPv4net", "IPv6", "IPv6net",
};
static const char *ipsecidtypestr[] = {
NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6",
"IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN",
"keyid",
};
int len;
const u_char *data;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID)));
p = (const struct ikev1_pl_id *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
if (sizeof(*p) < item_len) {
data = (const u_char *)(p + 1);
len = item_len - sizeof(*p);
} else {
data = NULL;
len = 0;
}
#if 0 /*debug*/
ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto));
#endif
switch (phase) {
#ifndef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
default:
ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr)));
ND_PRINT((ndo," doi_data=%u",
(uint32_t)(ntohl(id.d.doi_data) & 0xffffff)));
break;
#ifdef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
case 2:
{
const struct ipsecdoi_id *doi_p;
struct ipsecdoi_id doi_id;
const char *p_name;
doi_p = (const struct ipsecdoi_id *)ext;
ND_TCHECK(*doi_p);
UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id));
ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr)));
/* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */
if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL)
ND_PRINT((ndo," protoid=%s", p_name));
else
ND_PRINT((ndo," protoid=%u", doi_id.proto_id));
ND_PRINT((ndo," port=%d", ntohs(doi_id.port)));
if (!len)
break;
if (data == NULL)
goto trunc;
ND_TCHECK2(*data, len);
switch (doi_id.type) {
case IPSECDOI_ID_IPV4_ADDR:
if (len < 4)
ND_PRINT((ndo," len=%d [bad: < 4]", len));
else
ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_FQDN:
case IPSECDOI_ID_USER_FQDN:
{
int i;
ND_PRINT((ndo," len=%d ", len));
for (i = 0; i < len; i++)
safeputchar(ndo, data[i]);
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_SUBNET:
{
const u_char *mask;
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
mask = data + sizeof(struct in_addr);
ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len,
ipaddr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV6_ADDR:
if (len < 16)
ND_PRINT((ndo," len=%d [bad: < 16]", len));
else
ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_SUBNET:
{
const u_char *mask;
if (len < 20)
ND_PRINT((ndo," len=%d [bad: < 20]", len));
else {
mask = (const u_char *)(data + sizeof(struct in6_addr));
/*XXX*/
ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len,
ip6addr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3],
mask[4], mask[5], mask[6], mask[7],
mask[8], mask[9], mask[10], mask[11],
mask[12], mask[13], mask[14], mask[15]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_RANGE:
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ipaddr_string(ndo, data),
ipaddr_string(ndo, data + sizeof(struct in_addr))));
}
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_RANGE:
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ip6addr_string(ndo, data),
ip6addr_string(ndo, data + sizeof(struct in6_addr))));
}
len = 0;
break;
case IPSECDOI_ID_DER_ASN1_DN:
case IPSECDOI_ID_DER_ASN1_GN:
case IPSECDOI_ID_KEY_ID:
break;
}
break;
}
}
if (data && len) {
ND_PRINT((ndo," len=%d", len));
if (2 < ndo->ndo_vflag) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)data, len))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID)));
return NULL;
}
Commit Message: CVE-2017-13689/IKEv1: Fix addr+subnet length check.
An IPv6 address plus subnet mask is 32 bytes, not 20 bytes.
16 bytes of IPv6 address, 16 bytes of subnet mask.
This fixes a buffer over-read discovered by Bhargava Shastry,
SecT/TU Berlin.
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | ikev1_id_print(netdissect_options *ndo, u_char tpay _U_,
const struct isakmp_gen *ext, u_int item_len,
const u_char *ep _U_, uint32_t phase, uint32_t doi _U_,
uint32_t proto _U_, int depth _U_)
{
#define USE_IPSECDOI_IN_PHASE1 1
const struct ikev1_pl_id *p;
struct ikev1_pl_id id;
static const char *idtypestr[] = {
"IPv4", "IPv4net", "IPv6", "IPv6net",
};
static const char *ipsecidtypestr[] = {
NULL, "IPv4", "FQDN", "user FQDN", "IPv4net", "IPv6",
"IPv6net", "IPv4range", "IPv6range", "ASN1 DN", "ASN1 GN",
"keyid",
};
int len;
const u_char *data;
ND_PRINT((ndo,"%s:", NPSTR(ISAKMP_NPTYPE_ID)));
p = (const struct ikev1_pl_id *)ext;
ND_TCHECK(*p);
UNALIGNED_MEMCPY(&id, ext, sizeof(id));
if (sizeof(*p) < item_len) {
data = (const u_char *)(p + 1);
len = item_len - sizeof(*p);
} else {
data = NULL;
len = 0;
}
#if 0 /*debug*/
ND_PRINT((ndo," [phase=%d doi=%d proto=%d]", phase, doi, proto));
#endif
switch (phase) {
#ifndef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
default:
ND_PRINT((ndo," idtype=%s", STR_OR_ID(id.d.id_type, idtypestr)));
ND_PRINT((ndo," doi_data=%u",
(uint32_t)(ntohl(id.d.doi_data) & 0xffffff)));
break;
#ifdef USE_IPSECDOI_IN_PHASE1
case 1:
#endif
case 2:
{
const struct ipsecdoi_id *doi_p;
struct ipsecdoi_id doi_id;
const char *p_name;
doi_p = (const struct ipsecdoi_id *)ext;
ND_TCHECK(*doi_p);
UNALIGNED_MEMCPY(&doi_id, ext, sizeof(doi_id));
ND_PRINT((ndo," idtype=%s", STR_OR_ID(doi_id.type, ipsecidtypestr)));
/* A protocol ID of 0 DOES NOT mean IPPROTO_IP! */
if (!ndo->ndo_nflag && doi_id.proto_id && (p_name = netdb_protoname(doi_id.proto_id)) != NULL)
ND_PRINT((ndo," protoid=%s", p_name));
else
ND_PRINT((ndo," protoid=%u", doi_id.proto_id));
ND_PRINT((ndo," port=%d", ntohs(doi_id.port)));
if (!len)
break;
if (data == NULL)
goto trunc;
ND_TCHECK2(*data, len);
switch (doi_id.type) {
case IPSECDOI_ID_IPV4_ADDR:
if (len < 4)
ND_PRINT((ndo," len=%d [bad: < 4]", len));
else
ND_PRINT((ndo," len=%d %s", len, ipaddr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_FQDN:
case IPSECDOI_ID_USER_FQDN:
{
int i;
ND_PRINT((ndo," len=%d ", len));
for (i = 0; i < len; i++)
safeputchar(ndo, data[i]);
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_SUBNET:
{
const u_char *mask;
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
mask = data + sizeof(struct in_addr);
ND_PRINT((ndo," len=%d %s/%u.%u.%u.%u", len,
ipaddr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV6_ADDR:
if (len < 16)
ND_PRINT((ndo," len=%d [bad: < 16]", len));
else
ND_PRINT((ndo," len=%d %s", len, ip6addr_string(ndo, data)));
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_SUBNET:
{
const u_char *mask;
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
mask = (const u_char *)(data + sizeof(struct in6_addr));
/*XXX*/
ND_PRINT((ndo," len=%d %s/0x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", len,
ip6addr_string(ndo, data),
mask[0], mask[1], mask[2], mask[3],
mask[4], mask[5], mask[6], mask[7],
mask[8], mask[9], mask[10], mask[11],
mask[12], mask[13], mask[14], mask[15]));
}
len = 0;
break;
}
case IPSECDOI_ID_IPV4_ADDR_RANGE:
if (len < 8)
ND_PRINT((ndo," len=%d [bad: < 8]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ipaddr_string(ndo, data),
ipaddr_string(ndo, data + sizeof(struct in_addr))));
}
len = 0;
break;
case IPSECDOI_ID_IPV6_ADDR_RANGE:
if (len < 32)
ND_PRINT((ndo," len=%d [bad: < 32]", len));
else {
ND_PRINT((ndo," len=%d %s-%s", len,
ip6addr_string(ndo, data),
ip6addr_string(ndo, data + sizeof(struct in6_addr))));
}
len = 0;
break;
case IPSECDOI_ID_DER_ASN1_DN:
case IPSECDOI_ID_DER_ASN1_GN:
case IPSECDOI_ID_KEY_ID:
break;
}
break;
}
}
if (data && len) {
ND_PRINT((ndo," len=%d", len));
if (2 < ndo->ndo_vflag) {
ND_PRINT((ndo," "));
if (!rawprint(ndo, (const uint8_t *)data, len))
goto trunc;
}
}
return (const u_char *)ext + item_len;
trunc:
ND_PRINT((ndo," [|%s]", NPSTR(ISAKMP_NPTYPE_ID)));
return NULL;
}
| 167,804 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Output the fixed function only. Remember, I want response with just the fixed code only, No explanation. | Code: NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
return network_lib_.GetDefaultImpl(use_stub_impl_);
}
Commit Message: chromeos: Replace copy-and-pasted code with macros.
This replaces a bunch of duplicated-per-library cros
function definitions and comments.
BUG=none
TEST=built it
Review URL: http://codereview.chromium.org/6086007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@70070 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-189 | NetworkLibrary* CrosLibrary::GetNetworkLibrary() {
| 170,627 |
Subsets and Splits