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 gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
PurpleXfer *xfer = data;
struct im_connection *ic = purple_ic_by_pa(xfer->account);
struct prpl_xfer_data *px = xfer->ui_data;
PurpleBuddy *buddy;
const char *who;
buddy = purple_find_buddy(xfer->account, xfer->who);
who = buddy ? purple_buddy_get_name(buddy) : xfer->who;
/* TODO(wilmer): After spreading some more const goodness in BitlBee,
remove the evil cast below. */
px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);
px->ft->data = px;
px->ft->accept = prpl_xfer_accept;
px->ft->canceled = prpl_xfer_canceled;
px->ft->free = prpl_xfer_free;
px->ft->write_request = prpl_xfer_write_request;
return FALSE;
}
Commit Message: purple: Fix crash on ft requests from unknown contacts
Followup to 701ab81 (included in 3.5) which was a partial fix which only
improved things for non-libpurple file transfers (that is, just jabber)
CWE ID: CWE-476 | static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
PurpleXfer *xfer = data;
struct im_connection *ic = purple_ic_by_pa(xfer->account);
struct prpl_xfer_data *px = xfer->ui_data;
PurpleBuddy *buddy;
const char *who;
buddy = purple_find_buddy(xfer->account, xfer->who);
who = buddy ? purple_buddy_get_name(buddy) : xfer->who;
/* TODO(wilmer): After spreading some more const goodness in BitlBee,
remove the evil cast below. */
px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);
if (!px->ft) {
return FALSE;
}
px->ft->data = px;
px->ft->accept = prpl_xfer_accept;
px->ft->canceled = prpl_xfer_canceled;
px->ft->free = prpl_xfer_free;
px->ft->write_request = prpl_xfer_write_request;
return FALSE;
}
| 168,380 |
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 CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init ();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput ();
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get ("cl_motd", "1", 0);
#endif
cl_timeout = Cvar_Get ("cl_timeout", "200", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get ("timedemo", "0", 0);
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0);
rconAddress = Cvar_Get ("rconAddress", "", 0);
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0);
cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE);
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE);
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE);
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE);
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE);
#endif
cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0);
#ifdef __APPLE__
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE);
#else
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE);
#endif
cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0);
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
#ifdef __APPLE__
m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE);
#else
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
#endif
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("teamtask", "0", CVAR_USERINFO );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("password", "", CVAR_USERINFO);
Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE );
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
Cmd_AddCommand ("cmd", CL_ForwardToServer_f);
Cmd_AddCommand ("configstrings", CL_Configstrings_f);
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f);
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f);
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f);
Cmd_AddCommand ("disconnect", CL_Disconnect_f);
Cmd_AddCommand ("record", CL_Record_f);
Cmd_AddCommand ("demo", CL_PlayDemo_f);
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f);
Cmd_AddCommand ("stoprecord", CL_StopRecord_f);
Cmd_AddCommand ("connect", CL_Connect_f);
Cmd_AddCommand ("reconnect", CL_Reconnect_f);
Cmd_AddCommand ("localservers", CL_LocalServers_f);
Cmd_AddCommand ("globalservers", CL_GlobalServers_f);
Cmd_AddCommand ("rcon", CL_Rcon_f);
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand ("ping", CL_Ping_f );
Cmd_AddCommand ("serverstatus", CL_ServerStatus_f );
Cmd_AddCommand ("showip", CL_ShowIP_f );
Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("model", CL_SetModel_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
if( !com_dedicated->integer ) {
Cmd_AddCommand ("sayto", CL_Sayto_f );
Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName );
}
CL_InitRef();
SCR_Init ();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s.
CWE ID: CWE-269 | void CL_Init( void ) {
Com_Printf( "----- Client Initialization -----\n" );
Con_Init ();
if(!com_fullyInitialized)
{
CL_ClearState();
clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED
cl_oldGameSet = qfalse;
}
cls.realtime = 0;
CL_InitInput ();
cl_noprint = Cvar_Get( "cl_noprint", "0", 0 );
#ifdef UPDATE_SERVER_NAME
cl_motd = Cvar_Get ("cl_motd", "1", 0);
#endif
cl_timeout = Cvar_Get ("cl_timeout", "200", 0);
cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP );
cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP );
cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP );
cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP );
cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP );
rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP );
cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP );
cl_timedemo = Cvar_Get ("timedemo", "0", 0);
cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE);
cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE);
cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE);
cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE);
cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0);
rconAddress = Cvar_Get ("rconAddress", "", 0);
cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE);
cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE);
cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0);
cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE );
cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE );
cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE);
cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE);
cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE);
cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE );
cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE );
cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE );
Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse);
cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0);
cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE);
#ifdef USE_CURL_DLOPEN
cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE | CVAR_PROTECTED);
#endif
cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0);
#ifdef __APPLE__
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE);
#else
cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE);
#endif
cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0);
Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE);
m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE);
m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE);
m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE);
m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE);
#ifdef __APPLE__
m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE);
#else
m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE);
#endif
j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE);
j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE);
j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE);
j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE);
j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE);
j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE);
j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE);
j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE);
j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE);
j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE);
Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue);
cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM );
Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE );
cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE);
cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE);
cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE);
Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE );
cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE);
Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("teamtask", "0", CVAR_USERINFO );
Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE );
Cvar_Get ("password", "", CVAR_USERINFO);
Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE );
#ifdef USE_MUMBLE
cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH);
cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE);
#endif
#ifdef USE_VOIP
cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0);
cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0);
cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE);
cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE);
cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE);
cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE);
cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE);
cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE);
Cvar_CheckRange( cl_voip, 0, 1, qtrue );
cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM);
#endif
Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE );
Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM);
Cmd_AddCommand ("cmd", CL_ForwardToServer_f);
Cmd_AddCommand ("configstrings", CL_Configstrings_f);
Cmd_AddCommand ("clientinfo", CL_Clientinfo_f);
Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f);
Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f);
Cmd_AddCommand ("disconnect", CL_Disconnect_f);
Cmd_AddCommand ("record", CL_Record_f);
Cmd_AddCommand ("demo", CL_PlayDemo_f);
Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName );
Cmd_AddCommand ("cinematic", CL_PlayCinematic_f);
Cmd_AddCommand ("stoprecord", CL_StopRecord_f);
Cmd_AddCommand ("connect", CL_Connect_f);
Cmd_AddCommand ("reconnect", CL_Reconnect_f);
Cmd_AddCommand ("localservers", CL_LocalServers_f);
Cmd_AddCommand ("globalservers", CL_GlobalServers_f);
Cmd_AddCommand ("rcon", CL_Rcon_f);
Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon );
Cmd_AddCommand ("ping", CL_Ping_f );
Cmd_AddCommand ("serverstatus", CL_ServerStatus_f );
Cmd_AddCommand ("showip", CL_ShowIP_f );
Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f );
Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f );
Cmd_AddCommand ("model", CL_SetModel_f );
Cmd_AddCommand ("video", CL_Video_f );
Cmd_AddCommand ("stopvideo", CL_StopVideo_f );
if( !com_dedicated->integer ) {
Cmd_AddCommand ("sayto", CL_Sayto_f );
Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName );
}
CL_InitRef();
SCR_Init ();
Cvar_Set( "cl_running", "1" );
CL_GenerateQKey();
Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM );
CL_UpdateGUID( NULL, 0 );
Com_Printf( "----- Client Initialization Complete -----\n" );
}
| 170,088 |
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 lzo1x_decompress_safe(const unsigned char *in, size_t in_len,
unsigned char *out, size_t *out_len)
{
unsigned char *op;
const unsigned char *ip;
size_t t, next;
size_t state = 0;
const unsigned char *m_pos;
const unsigned char * const ip_end = in + in_len;
unsigned char * const op_end = out + *out_len;
op = out;
ip = in;
if (unlikely(in_len < 3))
goto input_overrun;
if (*ip > 17) {
t = *ip++ - 17;
if (t < 4) {
next = t;
goto match_next;
}
goto copy_literal_run;
}
for (;;) {
t = *ip++;
if (t < 16) {
if (likely(state == 0)) {
if (unlikely(t == 0)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1);
}
t += 15 + *ip++;
}
t += 3;
copy_literal_run:
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (likely(HAVE_IP(t + 15) && HAVE_OP(t + 15))) {
const unsigned char *ie = ip + t;
unsigned char *oe = op + t;
do {
COPY8(op, ip);
op += 8;
ip += 8;
COPY8(op, ip);
op += 8;
ip += 8;
} while (ip < ie);
ip = ie;
op = oe;
} else
#endif
{
NEED_OP(t);
NEED_IP(t + 3);
do {
*op++ = *ip++;
} while (--t > 0);
}
state = 4;
continue;
} else if (state != 4) {
next = t & 3;
m_pos = op - 1;
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
TEST_LB(m_pos);
NEED_OP(2);
op[0] = m_pos[0];
op[1] = m_pos[1];
op += 2;
goto match_next;
} else {
next = t & 3;
m_pos = op - (1 + M2_MAX_OFFSET);
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
t = 3;
}
} else if (t >= 64) {
next = t & 3;
m_pos = op - 1;
m_pos -= (t >> 2) & 7;
m_pos -= *ip++ << 3;
t = (t >> 5) - 1 + (3 - 1);
} else if (t >= 32) {
t = (t & 31) + (3 - 1);
if (unlikely(t == 2)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1);
}
t += 31 + *ip++;
NEED_IP(2);
}
m_pos = op - 1;
next = get_unaligned_le16(ip);
ip += 2;
m_pos -= next >> 2;
next &= 3;
} else {
m_pos = op;
m_pos -= (t & 8) << 11;
t = (t & 7) + (3 - 1);
if (unlikely(t == 2)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1);
}
t += 7 + *ip++;
NEED_IP(2);
}
next = get_unaligned_le16(ip);
ip += 2;
m_pos -= next >> 2;
next &= 3;
if (m_pos == op)
goto eof_found;
m_pos -= 0x4000;
}
TEST_LB(m_pos);
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (op - m_pos >= 8) {
unsigned char *oe = op + t;
if (likely(HAVE_OP(t + 15))) {
do {
COPY8(op, m_pos);
op += 8;
m_pos += 8;
COPY8(op, m_pos);
op += 8;
m_pos += 8;
} while (op < oe);
op = oe;
if (HAVE_IP(6)) {
state = next;
COPY4(op, ip);
op += next;
ip += next;
continue;
}
} else {
NEED_OP(t);
do {
*op++ = *m_pos++;
} while (op < oe);
}
} else
#endif
{
unsigned char *oe = op + t;
NEED_OP(t);
op[0] = m_pos[0];
op[1] = m_pos[1];
op += 2;
m_pos += 2;
do {
*op++ = *m_pos++;
} while (op < oe);
}
match_next:
state = next;
t = next;
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (likely(HAVE_IP(6) && HAVE_OP(4))) {
COPY4(op, ip);
op += t;
ip += t;
} else
#endif
{
NEED_IP(t + 3);
NEED_OP(t);
while (t > 0) {
*op++ = *ip++;
t--;
}
}
}
eof_found:
*out_len = op - out;
return (t != 3 ? LZO_E_ERROR :
ip == ip_end ? LZO_E_OK :
ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN);
input_overrun:
*out_len = op - out;
return LZO_E_INPUT_OVERRUN;
output_overrun:
*out_len = op - out;
return LZO_E_OUTPUT_OVERRUN;
lookbehind_overrun:
*out_len = op - out;
return LZO_E_LOOKBEHIND_OVERRUN;
}
Commit Message: lzo: properly check for overruns
The lzo decompressor can, if given some really crazy data, possibly
overrun some variable types. Modify the checking logic to properly
detect overruns before they happen.
Reported-by: "Don A. Bailey" <[email protected]>
Tested-by: "Don A. Bailey" <[email protected]>
Cc: stable <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-119 | int lzo1x_decompress_safe(const unsigned char *in, size_t in_len,
unsigned char *out, size_t *out_len)
{
unsigned char *op;
const unsigned char *ip;
size_t t, next;
size_t state = 0;
const unsigned char *m_pos;
const unsigned char * const ip_end = in + in_len;
unsigned char * const op_end = out + *out_len;
op = out;
ip = in;
if (unlikely(in_len < 3))
goto input_overrun;
if (*ip > 17) {
t = *ip++ - 17;
if (t < 4) {
next = t;
goto match_next;
}
goto copy_literal_run;
}
for (;;) {
t = *ip++;
if (t < 16) {
if (likely(state == 0)) {
if (unlikely(t == 0)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1, 0);
}
t += 15 + *ip++;
}
t += 3;
copy_literal_run:
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (likely(HAVE_IP(t, 15) && HAVE_OP(t, 15))) {
const unsigned char *ie = ip + t;
unsigned char *oe = op + t;
do {
COPY8(op, ip);
op += 8;
ip += 8;
COPY8(op, ip);
op += 8;
ip += 8;
} while (ip < ie);
ip = ie;
op = oe;
} else
#endif
{
NEED_OP(t, 0);
NEED_IP(t, 3);
do {
*op++ = *ip++;
} while (--t > 0);
}
state = 4;
continue;
} else if (state != 4) {
next = t & 3;
m_pos = op - 1;
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
TEST_LB(m_pos);
NEED_OP(2, 0);
op[0] = m_pos[0];
op[1] = m_pos[1];
op += 2;
goto match_next;
} else {
next = t & 3;
m_pos = op - (1 + M2_MAX_OFFSET);
m_pos -= t >> 2;
m_pos -= *ip++ << 2;
t = 3;
}
} else if (t >= 64) {
next = t & 3;
m_pos = op - 1;
m_pos -= (t >> 2) & 7;
m_pos -= *ip++ << 3;
t = (t >> 5) - 1 + (3 - 1);
} else if (t >= 32) {
t = (t & 31) + (3 - 1);
if (unlikely(t == 2)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1, 0);
}
t += 31 + *ip++;
NEED_IP(2, 0);
}
m_pos = op - 1;
next = get_unaligned_le16(ip);
ip += 2;
m_pos -= next >> 2;
next &= 3;
} else {
m_pos = op;
m_pos -= (t & 8) << 11;
t = (t & 7) + (3 - 1);
if (unlikely(t == 2)) {
while (unlikely(*ip == 0)) {
t += 255;
ip++;
NEED_IP(1, 0);
}
t += 7 + *ip++;
NEED_IP(2, 0);
}
next = get_unaligned_le16(ip);
ip += 2;
m_pos -= next >> 2;
next &= 3;
if (m_pos == op)
goto eof_found;
m_pos -= 0x4000;
}
TEST_LB(m_pos);
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (op - m_pos >= 8) {
unsigned char *oe = op + t;
if (likely(HAVE_OP(t, 15))) {
do {
COPY8(op, m_pos);
op += 8;
m_pos += 8;
COPY8(op, m_pos);
op += 8;
m_pos += 8;
} while (op < oe);
op = oe;
if (HAVE_IP(6, 0)) {
state = next;
COPY4(op, ip);
op += next;
ip += next;
continue;
}
} else {
NEED_OP(t, 0);
do {
*op++ = *m_pos++;
} while (op < oe);
}
} else
#endif
{
unsigned char *oe = op + t;
NEED_OP(t, 0);
op[0] = m_pos[0];
op[1] = m_pos[1];
op += 2;
m_pos += 2;
do {
*op++ = *m_pos++;
} while (op < oe);
}
match_next:
state = next;
t = next;
#if defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)
if (likely(HAVE_IP(6, 0) && HAVE_OP(4, 0))) {
COPY4(op, ip);
op += t;
ip += t;
} else
#endif
{
NEED_IP(t, 3);
NEED_OP(t, 0);
while (t > 0) {
*op++ = *ip++;
t--;
}
}
}
eof_found:
*out_len = op - out;
return (t != 3 ? LZO_E_ERROR :
ip == ip_end ? LZO_E_OK :
ip < ip_end ? LZO_E_INPUT_NOT_CONSUMED : LZO_E_INPUT_OVERRUN);
input_overrun:
*out_len = op - out;
return LZO_E_INPUT_OVERRUN;
output_overrun:
*out_len = op - out;
return LZO_E_OUTPUT_OVERRUN;
lookbehind_overrun:
*out_len = op - out;
return LZO_E_LOOKBEHIND_OVERRUN;
}
| 166,302 |
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 merge_param(HashTable *params, zval *zdata, zval ***current_param, zval ***current_args TSRMLS_DC)
{
zval **ptr, **zdata_ptr;
php_http_array_hashkey_t hkey = php_http_array_hashkey_init(0);
#if 0
{
zval tmp;
INIT_PZVAL_ARRAY(&tmp, params);
fprintf(stderr, "params = ");
zend_print_zval_r(&tmp, 1 TSRMLS_CC);
fprintf(stderr, "\n");
}
#endif
hkey.type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zdata), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL);
if ((hkey.type == HASH_KEY_IS_STRING && !zend_hash_exists(params, hkey.str, hkey.len))
|| (hkey.type == HASH_KEY_IS_LONG && !zend_hash_index_exists(params, hkey.num))
) {
zval *tmp, *arg, **args;
/* create the entry if it doesn't exist */
zend_hash_get_current_data(Z_ARRVAL_P(zdata), (void *) &ptr);
Z_ADDREF_PP(ptr);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(tmp, ZEND_STRS("value"), *ptr);
MAKE_STD_ZVAL(arg);
array_init(arg);
zend_hash_update(Z_ARRVAL_P(tmp), "arguments", sizeof("arguments"), (void *) &arg, sizeof(zval *), (void *) &args);
*current_args = args;
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_update(params, hkey.str, hkey.len, (void *) &tmp, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_index_update(params, hkey.num, (void *) &tmp, sizeof(zval *), (void *) &ptr);
}
} else {
/* merge */
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_find(params, hkey.str, hkey.len, (void *) &ptr);
} else {
zend_hash_index_find(params, hkey.num, (void *) &ptr);
}
zdata_ptr = &zdata;
if (Z_TYPE_PP(ptr) == IS_ARRAY
&& SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), "value", sizeof("value"), (void *) &ptr)
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &zdata_ptr)
) {
/*
* params = [arr => [value => [0 => 1]]]
* ^- ptr
* zdata = [arr => [0 => NULL]]
* ^- zdata_ptr
*/
zval **test_ptr;
while (Z_TYPE_PP(zdata_ptr) == IS_ARRAY
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &test_ptr)
) {
if (Z_TYPE_PP(test_ptr) == IS_ARRAY) {
/* now find key in ptr */
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
if (SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
} else {
if (SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(ptr), hkey.num, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else if (hkey.num) {
Z_ADDREF_PP(test_ptr);
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
}
} else {
/* this is the leaf */
Z_ADDREF_PP(test_ptr);
if (Z_TYPE_PP(ptr) != IS_ARRAY) {
zval_dtor(*ptr);
array_init(*ptr);
}
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else if (hkey.num) {
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
}
break;
}
}
}
}
/* bubble up */
while (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(ptr), (void *) &ptr));
*current_param = ptr;
}
Commit Message: fix bug #73055
CWE ID: CWE-704 | static void merge_param(HashTable *params, zval *zdata, zval ***current_param, zval ***current_args TSRMLS_DC)
{
zval **ptr, **zdata_ptr;
php_http_array_hashkey_t hkey = php_http_array_hashkey_init(0);
#if 0
{
zval tmp;
INIT_PZVAL_ARRAY(&tmp, params);
fprintf(stderr, "params = ");
zend_print_zval_r(&tmp, 1 TSRMLS_CC);
fprintf(stderr, "\n");
}
#endif
hkey.type = zend_hash_get_current_key_ex(Z_ARRVAL_P(zdata), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL);
if ((hkey.type == HASH_KEY_IS_STRING && !zend_hash_exists(params, hkey.str, hkey.len))
|| (hkey.type == HASH_KEY_IS_LONG && !zend_hash_index_exists(params, hkey.num))
) {
zval *tmp, *arg, **args;
/* create the entry if it doesn't exist */
zend_hash_get_current_data(Z_ARRVAL_P(zdata), (void *) &ptr);
Z_ADDREF_PP(ptr);
MAKE_STD_ZVAL(tmp);
array_init(tmp);
add_assoc_zval_ex(tmp, ZEND_STRS("value"), *ptr);
MAKE_STD_ZVAL(arg);
array_init(arg);
zend_hash_update(Z_ARRVAL_P(tmp), "arguments", sizeof("arguments"), (void *) &arg, sizeof(zval *), (void *) &args);
*current_args = args;
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_update(params, hkey.str, hkey.len, (void *) &tmp, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_index_update(params, hkey.num, (void *) &tmp, sizeof(zval *), (void *) &ptr);
}
} else {
/* merge */
if (hkey.type == HASH_KEY_IS_STRING) {
zend_hash_find(params, hkey.str, hkey.len, (void *) &ptr);
} else {
zend_hash_index_find(params, hkey.num, (void *) &ptr);
}
zdata_ptr = &zdata;
if (Z_TYPE_PP(ptr) == IS_ARRAY
&& SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), "value", sizeof("value"), (void *) &ptr)
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &zdata_ptr)
) {
/*
* params = [arr => [value => [0 => 1]]]
* ^- ptr
* zdata = [arr => [0 => NULL]]
* ^- zdata_ptr
*/
zval **test_ptr;
while (Z_TYPE_PP(zdata_ptr) == IS_ARRAY
&& SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(zdata_ptr), (void *) &test_ptr)
) {
if (Z_TYPE_PP(test_ptr) == IS_ARRAY && Z_TYPE_PP(ptr) == IS_ARRAY) {
/* now find key in ptr */
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
if (SUCCESS == zend_hash_find(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
} else {
if (SUCCESS == zend_hash_index_find(Z_ARRVAL_PP(ptr), hkey.num, (void *) &ptr)) {
zdata_ptr = test_ptr;
} else if (hkey.num) {
Z_ADDREF_PP(test_ptr);
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
} else {
Z_ADDREF_PP(test_ptr);
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
break;
}
}
} else {
/* this is the leaf */
Z_ADDREF_PP(test_ptr);
if (Z_TYPE_PP(ptr) != IS_ARRAY) {
zval_dtor(*ptr);
array_init(*ptr);
}
if (HASH_KEY_IS_STRING == zend_hash_get_current_key_ex(Z_ARRVAL_PP(zdata_ptr), &hkey.str, &hkey.len, &hkey.num, hkey.dup, NULL)) {
zend_hash_update(Z_ARRVAL_PP(ptr), hkey.str, hkey.len, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else if (hkey.num) {
zend_hash_index_update(Z_ARRVAL_PP(ptr), hkey.num, (void *) test_ptr, sizeof(zval *), (void *) &ptr);
} else {
zend_hash_next_index_insert(Z_ARRVAL_PP(ptr), (void *) test_ptr, sizeof(zval *), (void *) &ptr);
}
break;
}
}
}
}
/* bubble up */
while (Z_TYPE_PP(ptr) == IS_ARRAY && SUCCESS == zend_hash_get_current_data(Z_ARRVAL_PP(ptr), (void *) &ptr));
*current_param = ptr;
}
| 169,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: status_t BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
status_t err = NO_MEMORY;
void *params = calloc(size, 1);
if (params) {
err = data.read(params, size);
if (err != OK) {
android_errorWriteLog(0x534e4554, "26914474");
} else {
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
}
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
free(params);
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = createInputSurface(node, port_index, &bufferProducer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
}
return NO_ERROR;
}
case CREATE_PERSISTENT_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
sp<IGraphicBufferProducer> bufferProducer;
sp<IGraphicBufferConsumer> bufferConsumer;
status_t err = createPersistentInputSurface(
&bufferProducer, &bufferConsumer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
reply->writeStrongBinder(IInterface::asBinder(bufferConsumer));
}
return NO_ERROR;
}
case SET_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferConsumer> bufferConsumer =
interface_cast<IGraphicBufferConsumer>(data.readStrongBinder());
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = setInputSurface(node, port_index, bufferConsumer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = storeMetaDataInBuffers(node, port_index, enable, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(fillBuffer(node, buffer, fenceFd));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | status_t BnOMX::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case LIVES_LOCALLY:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
pid_t pid = (pid_t)data.readInt32();
reply->writeInt32(livesLocally(node, pid));
return OK;
}
case LIST_NODES:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
List<ComponentInfo> list;
listNodes(&list);
reply->writeInt32(list.size());
for (List<ComponentInfo>::iterator it = list.begin();
it != list.end(); ++it) {
ComponentInfo &cur = *it;
reply->writeString8(cur.mName);
reply->writeInt32(cur.mRoles.size());
for (List<String8>::iterator role_it = cur.mRoles.begin();
role_it != cur.mRoles.end(); ++role_it) {
reply->writeString8(*role_it);
}
}
return NO_ERROR;
}
case ALLOCATE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
const char *name = data.readCString();
sp<IOMXObserver> observer =
interface_cast<IOMXObserver>(data.readStrongBinder());
node_id node;
status_t err = allocateNode(name, observer, &node);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)node);
}
return NO_ERROR;
}
case FREE_NODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
reply->writeInt32(freeNode(node));
return NO_ERROR;
}
case SEND_COMMAND:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_COMMANDTYPE cmd =
static_cast<OMX_COMMANDTYPE>(data.readInt32());
OMX_S32 param = data.readInt32();
reply->writeInt32(sendCommand(node, cmd, param));
return NO_ERROR;
}
case GET_PARAMETER:
case SET_PARAMETER:
case GET_CONFIG:
case SET_CONFIG:
case SET_INTERNAL_OPTION:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_INDEXTYPE index = static_cast<OMX_INDEXTYPE>(data.readInt32());
size_t size = data.readInt64();
status_t err = NOT_ENOUGH_DATA;
void *params = NULL;
size_t pageSize = 0;
size_t allocSize = 0;
if (code != SET_INTERNAL_OPTION && size < 8) {
// we expect the structure to contain at least the size and
// version, 8 bytes total
ALOGE("b/27207275 (%zu)", size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
err = NO_MEMORY;
pageSize = (size_t) sysconf(_SC_PAGE_SIZE);
if (size > SIZE_MAX - (pageSize * 2)) {
ALOGE("requested param size too big");
} else {
allocSize = (size + pageSize * 2) & ~(pageSize - 1);
params = mmap(NULL, allocSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS, -1 /* fd */, 0 /* offset */);
}
if (params != MAP_FAILED) {
err = data.read(params, size);
if (err != OK) {
android_errorWriteLog(0x534e4554, "26914474");
} else {
err = NOT_ENOUGH_DATA;
OMX_U32 declaredSize = *(OMX_U32*)params;
if (code != SET_INTERNAL_OPTION && declaredSize > size) {
// the buffer says it's bigger than it actually is
ALOGE("b/27207275 (%u/%zu)", declaredSize, size);
android_errorWriteLog(0x534e4554, "27207275");
} else {
// mark the last page as inaccessible, to avoid exploitation
// of codecs that access past the end of the allocation because
// they didn't check the size
mprotect((char*)params + allocSize - pageSize, pageSize, PROT_NONE);
switch (code) {
case GET_PARAMETER:
err = getParameter(node, index, params, size);
break;
case SET_PARAMETER:
err = setParameter(node, index, params, size);
break;
case GET_CONFIG:
err = getConfig(node, index, params, size);
break;
case SET_CONFIG:
err = setConfig(node, index, params, size);
break;
case SET_INTERNAL_OPTION:
{
InternalOptionType type =
(InternalOptionType)data.readInt32();
err = setInternalOption(node, index, type, params, size);
break;
}
default:
TRESPASS();
}
}
}
} else {
ALOGE("couldn't map: %s", strerror(errno));
}
}
reply->writeInt32(err);
if ((code == GET_PARAMETER || code == GET_CONFIG) && err == OK) {
reply->write(params, size);
}
if (params) {
munmap(params, allocSize);
}
params = NULL;
return NO_ERROR;
}
case GET_STATE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_STATETYPE state = OMX_StateInvalid;
status_t err = getState(node, &state);
reply->writeInt32(state);
reply->writeInt32(err);
return NO_ERROR;
}
case ENABLE_GRAPHIC_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
status_t err = enableGraphicBuffers(node, port_index, enable);
reply->writeInt32(err);
return NO_ERROR;
}
case GET_GRAPHIC_BUFFER_USAGE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_U32 usage = 0;
status_t err = getGraphicBufferUsage(node, port_index, &usage);
reply->writeInt32(err);
reply->writeInt32(usage);
return NO_ERROR;
}
case USE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = useBuffer(node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case USE_GRAPHIC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer;
status_t err = useGraphicBuffer(
node, port_index, graphicBuffer, &buffer);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case UPDATE_GRAPHIC_BUFFER_IN_META:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<GraphicBuffer> graphicBuffer = new GraphicBuffer();
data.read(*graphicBuffer);
buffer_id buffer = (buffer_id)data.readInt32();
status_t err = updateGraphicBufferInMeta(
node, port_index, graphicBuffer, buffer);
reply->writeInt32(err);
return NO_ERROR;
}
case CREATE_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferProducer> bufferProducer;
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = createInputSurface(node, port_index, &bufferProducer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
}
return NO_ERROR;
}
case CREATE_PERSISTENT_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
sp<IGraphicBufferProducer> bufferProducer;
sp<IGraphicBufferConsumer> bufferConsumer;
status_t err = createPersistentInputSurface(
&bufferProducer, &bufferConsumer);
reply->writeInt32(err);
if (err == OK) {
reply->writeStrongBinder(IInterface::asBinder(bufferProducer));
reply->writeStrongBinder(IInterface::asBinder(bufferConsumer));
}
return NO_ERROR;
}
case SET_INPUT_SURFACE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IGraphicBufferConsumer> bufferConsumer =
interface_cast<IGraphicBufferConsumer>(data.readStrongBinder());
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = setInputSurface(node, port_index, bufferConsumer, &type);
if ((err != OK) && (type == kMetadataBufferTypeInvalid)) {
android_errorWriteLog(0x534e4554, "26324358");
}
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case SIGNAL_END_OF_INPUT_STREAM:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
status_t err = signalEndOfInputStream(node);
reply->writeInt32(err);
return NO_ERROR;
}
case STORE_META_DATA_IN_BUFFERS:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
MetadataBufferType type = kMetadataBufferTypeInvalid;
status_t err = storeMetaDataInBuffers(node, port_index, enable, &type);
reply->writeInt32(type);
reply->writeInt32(err);
return NO_ERROR;
}
case PREPARE_FOR_ADAPTIVE_PLAYBACK:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL enable = (OMX_BOOL)data.readInt32();
OMX_U32 max_width = data.readInt32();
OMX_U32 max_height = data.readInt32();
status_t err = prepareForAdaptivePlayback(
node, port_index, enable, max_width, max_height);
reply->writeInt32(err);
return NO_ERROR;
}
case CONFIGURE_VIDEO_TUNNEL_MODE:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
OMX_BOOL tunneled = (OMX_BOOL)data.readInt32();
OMX_U32 audio_hw_sync = data.readInt32();
native_handle_t *sideband_handle = NULL;
status_t err = configureVideoTunnelMode(
node, port_index, tunneled, audio_hw_sync, &sideband_handle);
reply->writeInt32(err);
if(err == OK){
reply->writeNativeHandle(sideband_handle);
}
return NO_ERROR;
}
case ALLOC_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
if (!isSecure(node) || port_index != 0 /* kPortIndexInput */) {
ALOGE("b/24310423");
reply->writeInt32(INVALID_OPERATION);
return NO_ERROR;
}
size_t size = data.readInt64();
buffer_id buffer;
void *buffer_data;
status_t err = allocateBuffer(
node, port_index, size, &buffer, &buffer_data);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
reply->writeInt64((uintptr_t)buffer_data);
}
return NO_ERROR;
}
case ALLOC_BUFFER_WITH_BACKUP:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
sp<IMemory> params =
interface_cast<IMemory>(data.readStrongBinder());
OMX_U32 allottedSize = data.readInt32();
buffer_id buffer;
status_t err = allocateBufferWithBackup(
node, port_index, params, &buffer, allottedSize);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32((int32_t)buffer);
}
return NO_ERROR;
}
case FREE_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
OMX_U32 port_index = data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
reply->writeInt32(freeBuffer(node, port_index, buffer));
return NO_ERROR;
}
case FILL_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(fillBuffer(node, buffer, fenceFd));
return NO_ERROR;
}
case EMPTY_BUFFER:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
buffer_id buffer = (buffer_id)data.readInt32();
OMX_U32 range_offset = data.readInt32();
OMX_U32 range_length = data.readInt32();
OMX_U32 flags = data.readInt32();
OMX_TICKS timestamp = data.readInt64();
bool haveFence = data.readInt32();
int fenceFd = haveFence ? ::dup(data.readFileDescriptor()) : -1;
reply->writeInt32(emptyBuffer(
node, buffer, range_offset, range_length, flags, timestamp, fenceFd));
return NO_ERROR;
}
case GET_EXTENSION_INDEX:
{
CHECK_OMX_INTERFACE(IOMX, data, reply);
node_id node = (node_id)data.readInt32();
const char *parameter_name = data.readCString();
OMX_INDEXTYPE index;
status_t err = getExtensionIndex(node, parameter_name, &index);
reply->writeInt32(err);
if (err == OK) {
reply->writeInt32(index);
}
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
| 174,185 |
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 double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
{
/* Error in the linear composition arithmetic - only relevant when
* composition actually happens (0 < alpha < 1).
*/
if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxcalc16;
else if (pm->assume_16_bit_calculations)
return pm->maxcalcG;
else
return pm->maxcalc8;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | static double calcerr(PNG_CONST png_modifier *pm, int in_depth, int out_depth)
static double calcerr(const png_modifier *pm, int in_depth, int out_depth)
{
/* Error in the linear composition arithmetic - only relevant when
* composition actually happens (0 < alpha < 1).
*/
if ((pm->calculations_use_input_precision ? in_depth : out_depth) == 16)
return pm->maxcalc16;
else if (pm->assume_16_bit_calculations)
return pm->maxcalcG;
else
return pm->maxcalc8;
}
| 173,604 |
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: parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
p += sizeof ( short );
for ( i = 0; i < string_count && i < 64; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= FT_MIN( string_count, 64 ) )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
Commit Message:
CWE ID: CWE-119 | parse_fond( char* fond_data,
short* have_sfnt,
ResID* sfnt_id,
Str255 lwfn_file_name,
short face_index )
{
AsscEntry* assoc;
AsscEntry* base_assoc;
FamRec* fond;
*sfnt_id = 0;
*have_sfnt = 0;
lwfn_file_name[0] = 0;
fond = (FamRec*)fond_data;
assoc = (AsscEntry*)( fond_data + sizeof ( FamRec ) + 2 );
base_assoc = assoc;
/* the maximum faces in a FOND is 48, size of StyleTable.indexes[] */
if ( 47 < face_index )
return;
/* Let's do a little range checking before we get too excited here */
if ( face_index < count_faces_sfnt( fond_data ) )
{
assoc += face_index; /* add on the face_index! */
/* if the face at this index is not scalable,
fall back to the first one (old behavior) */
if ( EndianS16_BtoN( assoc->fontSize ) == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( assoc->fontID );
}
else if ( base_assoc->fontSize == 0 )
{
*have_sfnt = 1;
*sfnt_id = EndianS16_BtoN( base_assoc->fontID );
}
}
if ( EndianS32_BtoN( fond->ffStylOff ) )
{
unsigned char* p = (unsigned char*)fond_data;
StyleTable* style;
unsigned short string_count;
char ps_name[256];
unsigned char* names[64];
int i;
p += EndianS32_BtoN( fond->ffStylOff );
style = (StyleTable*)p;
p += sizeof ( StyleTable );
string_count = EndianS16_BtoN( *(short*)(p) );
string_count = FT_MIN( 64, string_count );
p += sizeof ( short );
for ( i = 0; i < string_count; i++ )
{
names[i] = p;
p += names[i][0];
}
{
size_t ps_name_len = (size_t)names[0][0];
if ( ps_name_len != 0 )
{
ft_memcpy(ps_name, names[0] + 1, ps_name_len);
ps_name[ps_name_len] = 0;
ps_name[ps_name_len] = 0;
}
if ( style->indexes[face_index] > 1 &&
style->indexes[face_index] <= string_count )
{
unsigned char* suffixes = names[style->indexes[face_index] - 1];
for ( i = 1; i <= suffixes[0]; i++ )
{
unsigned char* s;
size_t j = suffixes[i] - 1;
if ( j < string_count && ( s = names[j] ) != NULL )
{
size_t s_len = (size_t)s[0];
if ( s_len != 0 && ps_name_len + s_len < sizeof ( ps_name ) )
{
ft_memcpy( ps_name + ps_name_len, s + 1, s_len );
ps_name_len += s_len;
ps_name[ps_name_len] = 0;
}
}
}
}
}
create_lwfn_name( ps_name, lwfn_file_name );
}
}
| 164,842 |
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 inet_sk_reselect_saddr(struct sock *sk)
{
struct inet_sock *inet = inet_sk(sk);
__be32 old_saddr = inet->inet_saddr;
__be32 daddr = inet->inet_daddr;
struct flowi4 fl4;
struct rtable *rt;
__be32 new_saddr;
if (inet->opt && inet->opt->srr)
daddr = inet->opt->faddr;
/* Query new route. */
rt = ip_route_connect(&fl4, daddr, 0, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if, sk->sk_protocol,
inet->inet_sport, inet->inet_dport, sk, false);
if (IS_ERR(rt))
return PTR_ERR(rt);
sk_setup_caps(sk, &rt->dst);
new_saddr = rt->rt_src;
if (new_saddr == old_saddr)
return 0;
if (sysctl_ip_dynaddr > 1) {
printk(KERN_INFO "%s(): shifting inet->saddr from %pI4 to %pI4\n",
__func__, &old_saddr, &new_saddr);
}
inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;
/*
* XXX The only one ugly spot where we need to
* XXX really change the sockets identity after
* XXX it has entered the hashes. -DaveM
*
* Besides that, it does not check for connection
* uniqueness. Wait for troubles.
*/
__sk_prot_rehash(sk);
return 0;
}
Commit Message: inet: add RCU protection to inet->opt
We lack proper synchronization to manipulate inet->opt ip_options
Problem is ip_make_skb() calls ip_setup_cork() and
ip_setup_cork() possibly makes a copy of ipc->opt (struct ip_options),
without any protection against another thread manipulating inet->opt.
Another thread can change inet->opt pointer and free old one under us.
Use RCU to protect inet->opt (changed to inet->inet_opt).
Instead of handling atomic refcounts, just copy ip_options when
necessary, to avoid cache line dirtying.
We cant insert an rcu_head in struct ip_options since its included in
skb->cb[], so this patch is large because I had to introduce a new
ip_options_rcu structure.
Signed-off-by: Eric Dumazet <[email protected]>
Cc: Herbert Xu <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-362 | static int inet_sk_reselect_saddr(struct sock *sk)
{
struct inet_sock *inet = inet_sk(sk);
__be32 old_saddr = inet->inet_saddr;
__be32 daddr = inet->inet_daddr;
struct flowi4 fl4;
struct rtable *rt;
__be32 new_saddr;
struct ip_options_rcu *inet_opt;
inet_opt = rcu_dereference_protected(inet->inet_opt,
sock_owned_by_user(sk));
if (inet_opt && inet_opt->opt.srr)
daddr = inet_opt->opt.faddr;
/* Query new route. */
rt = ip_route_connect(&fl4, daddr, 0, RT_CONN_FLAGS(sk),
sk->sk_bound_dev_if, sk->sk_protocol,
inet->inet_sport, inet->inet_dport, sk, false);
if (IS_ERR(rt))
return PTR_ERR(rt);
sk_setup_caps(sk, &rt->dst);
new_saddr = rt->rt_src;
if (new_saddr == old_saddr)
return 0;
if (sysctl_ip_dynaddr > 1) {
printk(KERN_INFO "%s(): shifting inet->saddr from %pI4 to %pI4\n",
__func__, &old_saddr, &new_saddr);
}
inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;
/*
* XXX The only one ugly spot where we need to
* XXX really change the sockets identity after
* XXX it has entered the hashes. -DaveM
*
* Besides that, it does not check for connection
* uniqueness. Wait for troubles.
*/
__sk_prot_rehash(sk);
return 0;
}
| 165,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: int sbusfb_ioctl_helper(unsigned long cmd, unsigned long arg,
struct fb_info *info,
int type, int fb_depth, unsigned long fb_size)
{
switch(cmd) {
case FBIOGTYPE: {
struct fbtype __user *f = (struct fbtype __user *) arg;
if (put_user(type, &f->fb_type) ||
__put_user(info->var.yres, &f->fb_height) ||
__put_user(info->var.xres, &f->fb_width) ||
__put_user(fb_depth, &f->fb_depth) ||
__put_user(0, &f->fb_cmsize) ||
__put_user(fb_size, &f->fb_cmsize))
return -EFAULT;
return 0;
}
case FBIOPUTCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
struct fb_cmap cmap;
u16 red, green, blue;
u8 red8, green8, blue8;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
int index, count, i;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
cmap.len = 1;
cmap.red = &red;
cmap.green = &green;
cmap.blue = &blue;
cmap.transp = NULL;
for (i = 0; i < count; i++) {
int err;
if (get_user(red8, &ured[i]) ||
get_user(green8, &ugreen[i]) ||
get_user(blue8, &ublue[i]))
return -EFAULT;
red = red8 << 8;
green = green8 << 8;
blue = blue8 << 8;
cmap.start = index + i;
err = fb_set_cmap(&cmap, info);
if (err)
return err;
}
return 0;
}
case FBIOGETCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
struct fb_cmap *cmap = &info->cmap;
int index, count, i;
u8 red, green, blue;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
if (index + count > cmap->len)
return -EINVAL;
for (i = 0; i < count; i++) {
red = cmap->red[index + i] >> 8;
green = cmap->green[index + i] >> 8;
blue = cmap->blue[index + i] >> 8;
if (put_user(red, &ured[i]) ||
put_user(green, &ugreen[i]) ||
put_user(blue, &ublue[i]))
return -EFAULT;
}
return 0;
}
default:
return -EINVAL;
}
}
Commit Message: fbdev: Fixing arbitrary kernel leak in case FBIOGETCMAP_SPARC in sbusfb_ioctl_helper().
Fixing arbitrary kernel leak in case FBIOGETCMAP_SPARC in
sbusfb_ioctl_helper().
'index' is defined as an int in sbusfb_ioctl_helper().
We retrieve this from the user:
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
and then we use 'index' in the following way:
red = cmap->red[index + i] >> 8;
green = cmap->green[index + i] >> 8;
blue = cmap->blue[index + i] >> 8;
This is a classic information leak vulnerability. 'index' should be
an unsigned int, given its usage above.
This patch is straight-forward; it changes 'index' to unsigned int
in two switch-cases: FBIOGETCMAP_SPARC && FBIOPUTCMAP_SPARC.
This patch fixes CVE-2018-6412.
Signed-off-by: Peter Malone <[email protected]>
Acked-by: Mathieu Malaterre <[email protected]>
Signed-off-by: Bartlomiej Zolnierkiewicz <[email protected]>
CWE ID: CWE-200 | int sbusfb_ioctl_helper(unsigned long cmd, unsigned long arg,
struct fb_info *info,
int type, int fb_depth, unsigned long fb_size)
{
switch(cmd) {
case FBIOGTYPE: {
struct fbtype __user *f = (struct fbtype __user *) arg;
if (put_user(type, &f->fb_type) ||
__put_user(info->var.yres, &f->fb_height) ||
__put_user(info->var.xres, &f->fb_width) ||
__put_user(fb_depth, &f->fb_depth) ||
__put_user(0, &f->fb_cmsize) ||
__put_user(fb_size, &f->fb_cmsize))
return -EFAULT;
return 0;
}
case FBIOPUTCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
struct fb_cmap cmap;
u16 red, green, blue;
u8 red8, green8, blue8;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
unsigned int index, count, i;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
cmap.len = 1;
cmap.red = &red;
cmap.green = &green;
cmap.blue = &blue;
cmap.transp = NULL;
for (i = 0; i < count; i++) {
int err;
if (get_user(red8, &ured[i]) ||
get_user(green8, &ugreen[i]) ||
get_user(blue8, &ublue[i]))
return -EFAULT;
red = red8 << 8;
green = green8 << 8;
blue = blue8 << 8;
cmap.start = index + i;
err = fb_set_cmap(&cmap, info);
if (err)
return err;
}
return 0;
}
case FBIOGETCMAP_SPARC: {
struct fbcmap __user *c = (struct fbcmap __user *) arg;
unsigned char __user *ured;
unsigned char __user *ugreen;
unsigned char __user *ublue;
struct fb_cmap *cmap = &info->cmap;
unsigned int index, count, i;
u8 red, green, blue;
if (get_user(index, &c->index) ||
__get_user(count, &c->count) ||
__get_user(ured, &c->red) ||
__get_user(ugreen, &c->green) ||
__get_user(ublue, &c->blue))
return -EFAULT;
if (index + count > cmap->len)
return -EINVAL;
for (i = 0; i < count; i++) {
red = cmap->red[index + i] >> 8;
green = cmap->green[index + i] >> 8;
blue = cmap->blue[index + i] >> 8;
if (put_user(red, &ured[i]) ||
put_user(green, &ugreen[i]) ||
put_user(blue, &ublue[i]))
return -EFAULT;
}
return 0;
}
default:
return -EINVAL;
}
}
| 169,344 |
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 PaintArtifactCompositor::CollectPendingLayers(
const PaintArtifact& paint_artifact,
Vector<PendingLayer>& pending_layers) {
Vector<PaintChunk>::const_iterator cursor =
paint_artifact.PaintChunks().begin();
LayerizeGroup(paint_artifact, pending_layers,
*EffectPaintPropertyNode::Root(), cursor);
DCHECK_EQ(paint_artifact.PaintChunks().end(), cursor);
}
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: | void PaintArtifactCompositor::CollectPendingLayers(
const PaintArtifact& paint_artifact,
Vector<PendingLayer>& pending_layers) {
Vector<PaintChunk>::const_iterator cursor =
paint_artifact.PaintChunks().begin();
LayerizeGroup(paint_artifact, pending_layers, EffectPaintPropertyNode::Root(),
cursor);
DCHECK_EQ(paint_artifact.PaintChunks().end(), cursor);
}
| 171,813 |
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: IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec,
nal_header_t *ps_nal)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 i;
WORD32 sps_id;
pps_t *ps_pps;
sps_t *ps_sps;
slice_header_t *ps_slice_hdr;
WORD32 disable_deblocking_filter_flag;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 idr_pic_flag;
WORD32 pps_id;
WORD32 first_slice_in_pic_flag;
WORD32 no_output_of_prior_pics_flag = 0;
WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type;
WORD32 num_poc_total_curr = 0;
WORD32 slice_address;
if(ps_codec->i4_slice_error == 1)
return ret;
idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) ||
(NAL_IDR_N_LP == i1_nal_unit_type);
BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1);
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1);
}
UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm);
pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2);
/* Get the current PPS structure */
ps_pps = ps_codec->s_parse.ps_pps_base + pps_id;
if(0 == ps_pps->i1_pps_valid)
{
pps_t *ps_pps_ref = ps_codec->ps_pps_base;
while(0 == ps_pps_ref->i1_pps_valid)
ps_pps_ref++;
if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1))
return IHEVCD_INVALID_HEADER;
ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id);
}
/* Get SPS id for the current PPS */
sps_id = ps_pps->i1_sps_id;
/* Get the current SPS structure */
ps_sps = ps_codec->s_parse.ps_sps_base + sps_id;
/* When the current slice is the first in a pic,
* check whether the previous frame is complete
* If the previous frame is incomplete -
* treat the remaining CTBs as skip */
if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) &&
first_slice_in_pic_flag)
{
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
if(first_slice_in_pic_flag)
{
ps_codec->s_parse.i4_cur_slice_idx = 0;
}
else
{
/* If the current slice is not the first slice in the pic,
* but the first one to be parsed, set the current slice indx to 1
* Treat the first slice to be missing and copy the current slice header
* to the first one */
if(0 == ps_codec->i4_pic_present)
ps_codec->s_parse.i4_cur_slice_idx = 1;
}
ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
if((ps_pps->i1_dependent_slice_enabled_flag) &&
(!first_slice_in_pic_flag))
{
BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1);
/* If dependendent slice, copy slice header from previous slice */
if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0))
{
ihevcd_copy_slice_hdr(ps_codec,
(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)),
((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1)));
}
ps_slice_hdr->i1_dependent_slice_flag = value;
}
else
{
ps_slice_hdr->i1_dependent_slice_flag = 0;
}
ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type;
ps_slice_hdr->i1_pps_id = pps_id;
ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag;
ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1;
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag;
}
ps_slice_hdr->i1_pps_id = pps_id;
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
WORD32 num_bits;
/* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */
num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1);
BITS_PARSE("slice_address", value, ps_bitstrm, num_bits);
slice_address = value;
/* If slice address is greater than the number of CTBs in a picture,
* ignore the slice */
if(value >= ps_sps->i4_pic_size_in_ctb)
return IHEVCD_IGNORE_SLICE;
}
else
{
slice_address = 0;
}
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i1_pic_output_flag = 1;
ps_slice_hdr->i4_pic_order_cnt_lsb = 0;
ps_slice_hdr->i1_num_long_term_sps = 0;
ps_slice_hdr->i1_num_long_term_pics = 0;
for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++)
{
BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1);
}
UEV_PARSE("slice_type", value, ps_bitstrm);
ps_slice_hdr->i1_slice_type = value;
/* If the picture is IRAP, slice type must be equal to ISLICE */
if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) &&
(ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23))
ps_slice_hdr->i1_slice_type = ISLICE;
if((ps_slice_hdr->i1_slice_type < 0) ||
(ps_slice_hdr->i1_slice_type > 2))
return IHEVCD_IGNORE_SLICE;
if(ps_pps->i1_output_flag_present_flag)
{
BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_pic_output_flag = value;
}
ps_slice_hdr->i1_colour_plane_id = 0;
if(1 == ps_sps->i1_separate_colour_plane_flag)
{
BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2);
ps_slice_hdr->i1_colour_plane_id = value;
}
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0;
if(!idr_pic_flag)
{
WORD32 st_rps_idx;
WORD32 num_neg_pics;
WORD32 num_pos_pics;
WORD8 *pi1_used;
BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->i4_pic_order_cnt_lsb = value;
BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value;
if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag)
{
WORD32 numbits;
ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0;
if(ps_sps->i1_num_short_term_ref_pic_sets > 1)
{
numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1);
BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits);
ps_slice_hdr->i1_short_term_ref_pic_set_idx = value;
}
st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx;
num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics;
num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics;
pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used;
}
else
{
ihevcd_short_term_ref_pic_set(ps_bitstrm,
&ps_sps->as_stref_picset[0],
ps_sps->i1_num_short_term_ref_pic_sets,
ps_sps->i1_num_short_term_ref_pic_sets,
&ps_slice_hdr->s_stref_picset);
st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets;
num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics;
num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics;
pi1_used = ps_slice_hdr->s_stref_picset.ai1_used;
}
if(ps_sps->i1_long_term_ref_pics_present_flag)
{
if(ps_sps->i1_num_long_term_ref_pics_sps > 0)
{
UEV_PARSE("num_long_term_sps", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_sps = value;
ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics);
}
UEV_PARSE("num_long_term_pics", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_pics = value;
ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics -
ps_slice_hdr->i1_num_long_term_sps);
for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps +
ps_slice_hdr->i1_num_long_term_pics); i++)
{
if(i < ps_slice_hdr->i1_num_long_term_sps)
{
/* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */
WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps);
BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits);
ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->ai1_lt_ref_pic_poc_lsb_sps[value];
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value];
}
else
{
BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->ai4_poc_lsb_lt[i] = value;
BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value;
}
BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value;
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0;
if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i])
{
UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm);
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value;
}
if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps))
{
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1];
}
}
}
for(i = 0; i < num_neg_pics + num_pos_pics; i++)
{
if(pi1_used[i])
{
num_poc_total_curr++;
}
}
for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++)
{
if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i])
{
num_poc_total_curr++;
}
}
if(ps_sps->i1_sps_temporal_mvp_enable_flag)
{
BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value;
}
}
ps_slice_hdr->i1_slice_sao_luma_flag = 0;
ps_slice_hdr->i1_slice_sao_chroma_flag = 0;
if(ps_sps->i1_sample_adaptive_offset_enabled_flag)
{
BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_luma_flag = value;
BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_chroma_flag = value;
}
ps_slice_hdr->i1_max_num_merge_cand = 1;
ps_slice_hdr->i1_cabac_init_flag = 0;
ps_slice_hdr->i1_num_ref_idx_l0_active = 0;
ps_slice_hdr->i1_num_ref_idx_l1_active = 0;
ps_slice_hdr->i1_slice_cb_qp_offset = 0;
ps_slice_hdr->i1_slice_cr_qp_offset = 0;
if((PSLICE == ps_slice_hdr->i1_slice_type) ||
(BSLICE == ps_slice_hdr->i1_slice_type))
{
BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_num_ref_idx_active_override_flag = value;
if(ps_slice_hdr->i1_num_ref_idx_active_override_flag)
{
UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1;
}
}
else
{
ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active;
}
}
ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1);
ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1);
if(0 == num_poc_total_curr)
return IHEVCD_IGNORE_SLICE;
if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1))
{
ihevcd_ref_pic_list_modification(ps_bitstrm,
ps_slice_hdr, num_poc_total_curr);
}
else
{
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0;
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0;
}
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_mvd_l1_zero_flag = value;
}
ps_slice_hdr->i1_cabac_init_flag = 0;
if(ps_pps->i1_cabac_init_present_flag)
{
BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_cabac_init_flag = value;
}
ps_slice_hdr->i1_collocated_from_l0_flag = 1;
ps_slice_hdr->i1_collocated_ref_idx = 0;
if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag)
{
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_collocated_from_l0_flag = value;
}
if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) ||
(!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1)))
{
UEV_PARSE("collocated_ref_idx", value, ps_bitstrm);
ps_slice_hdr->i1_collocated_ref_idx = value;
}
}
ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1);
if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) ||
(ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type)))
{
ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr);
}
UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm);
ps_slice_hdr->i1_max_num_merge_cand = 5 - value;
}
ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5);
SEV_PARSE("slice_qp_delta", value, ps_bitstrm);
ps_slice_hdr->i1_slice_qp_delta = value;
if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag)
{
SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cb_qp_offset = value;
SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cr_qp_offset = value;
}
ps_slice_hdr->i1_deblocking_filter_override_flag = 0;
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2;
ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2;
disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
if(ps_pps->i1_deblocking_filter_override_enabled_flag)
{
BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_deblocking_filter_override_flag = value;
}
if(ps_slice_hdr->i1_deblocking_filter_override_flag)
{
BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value;
disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag;
if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
{
SEV_PARSE("beta_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_beta_offset_div2 = value;
SEV_PARSE("tc_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_tc_offset_div2 = value;
}
}
}
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag;
if(ps_pps->i1_loop_filter_across_slices_enabled_flag &&
(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag))
{
BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value;
}
}
/* Check sanity of slice */
if((!first_slice_in_pic_flag) &&
(ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base;
/* According to the standard, the above conditions must be satisfied - But for error resilience,
* only the following conditions are checked */
if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) ||
(ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb))
{
return IHEVCD_IGNORE_SLICE;
}
}
if(0 == ps_codec->i4_pic_present)
{
ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb);
}
else
{
ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt;
}
if(!first_slice_in_pic_flag)
{
/* Check if the current slice belongs to the same pic (Pic being parsed) */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
{
/* If the Next CTB's index is less than the slice address,
* the previous slice is incomplete.
* Indicate slice error, and treat the remaining CTBs as skip */
if(slice_address > ps_codec->s_parse.i4_next_ctb_indx)
{
if(ps_codec->i4_pic_present)
{
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
return ret;
}
else
{
return IHEVCD_IGNORE_SLICE;
}
}
/* If the slice address is less than the next CTB's index,
* extra CTBs have been decoded in the previous slice.
* Ignore the current slice. Treat it as incomplete */
else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx)
{
return IHEVCD_IGNORE_SLICE;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
/* The current slice does not belong to the pic that is being parsed */
else
{
/* The previous pic is incomplete.
* Treat the remaining CTBs as skip */
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
/* If the previous pic is complete,
* return if the current slice is dependant
* otherwise, update the parse context's POC */
else
{
if(ps_slice_hdr->i1_dependent_slice_flag)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
}
}
/* If the slice is the first slice in the pic, update the parse context's POC */
else
{
/* If the first slice is repeated, ignore the second occurrence
* If any other slice is repeated, the CTB addr will be greater than the slice addr,
* and hence the second occurrence is ignored */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
ps_slice_hdr->i4_num_entry_point_offsets = 0;
if((ps_pps->i1_tiles_enabled_flag) ||
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm);
ps_slice_hdr->i4_num_entry_point_offsets = value;
{
WORD32 max_num_entry_point_offsets;
if((ps_pps->i1_tiles_enabled_flag) &&
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1);
}
else if(ps_pps->i1_tiles_enabled_flag)
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows;
}
else
{
max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1);
}
ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets,
0, max_num_entry_point_offsets);
}
if(ps_slice_hdr->i4_num_entry_point_offsets > 0)
{
UEV_PARSE("offset_len_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_offset_len = value + 1;
for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++)
{
BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len);
/* TODO: pu4_entry_point_offset needs to be initialized */
}
}
}
if(ps_pps->i1_slice_header_extension_present_flag)
{
UEV_PARSE("slice_header_extension_length", value, ps_bitstrm);
ps_slice_hdr->i2_slice_header_extension_length = value;
for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++)
{
BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8);
}
}
ihevcd_bits_flush_to_byte_boundary(ps_bitstrm);
{
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
WORD32 r_idx;
if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(0 == ps_codec->u4_pic_cnt))
{
for(i = 0; i < MAX_DPB_BUFS; i++)
{
if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf)
{
pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf;
mv_buf_t *ps_mv_buf;
/* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */
ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc);
/* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */
ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf;
for(i = 0; i < BUF_MGR_MAX_CNT; i++)
{
if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc)
{
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, i, BUF_MGR_REF);
break;
}
ps_mv_buf++;
}
}
}
/* Initialize the reference lists to NULL
* This is done to take care of the cases where the first pic is not IDR
* but the reference list is not created for the first pic because
* pic count is zero leaving the reference list uninitialised */
for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL;
}
}
else
{
ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr);
}
}
/* Fill the remaining entries of the reference lists with the nearest POC
* This is done to handle cases where there is a corruption in the reference index */
if(ps_codec->i4_pic_present)
{
pic_buf_t *ps_pic_buf_ref;
mv_buf_t *ps_mv_buf_ref;
WORD32 r_idx;
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr;
ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt);
if(NULL == ps_pic_buf_ref)
{
ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic;
ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf;
}
else
{
ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc);
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
/* Update slice address in the header */
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x;
ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y;
}
}
else
{
ps_slice_hdr->i2_ctb_x = 0;
ps_slice_hdr->i2_ctb_y = 0;
ps_slice_hdr->i2_independent_ctb_x = 0;
ps_slice_hdr->i2_independent_ctb_y = 0;
}
/* If the first slice in the pic is missing, copy the current slice header to
* the first slice's header */
if((!first_slice_in_pic_flag) &&
(0 == ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base;
ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)));
ps_codec->i4_slice_error = 1;
ps_slice_hdr_prev->i2_ctb_x = 0;
ps_slice_hdr_prev->i2_ctb_y = 0;
ps_codec->s_parse.i4_ctb_x = 0;
ps_codec->s_parse.i4_ctb_y = 0;
ps_codec->s_parse.i4_cur_slice_idx = 0;
if((ps_slice_hdr->i2_ctb_x == 0) &&
(ps_slice_hdr->i2_ctb_y == 0))
{
ps_slice_hdr->i2_ctb_x++;
}
}
{
/* If skip B is enabled,
* ignore pictures that are non-reference
* TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is
* sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/
if((i1_nal_unit_type < NAL_BLA_W_LP) &&
(i1_nal_unit_type % 2 == 0))
{
if(IVD_SKIP_B == ps_codec->e_pic_skip_mode)
return IHEVCD_IGNORE_SLICE;
}
/* If skip PB is enabled,
* decode only I slices */
if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) &&
(ISLICE != ps_slice_hdr->i1_slice_type))
{
return IHEVCD_IGNORE_SLICE;
}
}
return ret;
}
Commit Message: Handle error return from ref list in slice hdr parsing
The error returned by ref_list function was not handled by the
caller parse_slice_header.
Bug: 34672748
Change-Id: I55f6cb0e651746e77f7ff3375115894ec3964203
(cherry picked from commit 25206ffa6eeb25f32103e69f893287425ab1bd10)
CWE ID: CWE-252 | IHEVCD_ERROR_T ihevcd_parse_slice_header(codec_t *ps_codec,
nal_header_t *ps_nal)
{
IHEVCD_ERROR_T ret = (IHEVCD_ERROR_T)IHEVCD_SUCCESS;
WORD32 value;
WORD32 i;
WORD32 sps_id;
pps_t *ps_pps;
sps_t *ps_sps;
slice_header_t *ps_slice_hdr;
WORD32 disable_deblocking_filter_flag;
bitstrm_t *ps_bitstrm = &ps_codec->s_parse.s_bitstrm;
WORD32 idr_pic_flag;
WORD32 pps_id;
WORD32 first_slice_in_pic_flag;
WORD32 no_output_of_prior_pics_flag = 0;
WORD8 i1_nal_unit_type = ps_nal->i1_nal_unit_type;
WORD32 num_poc_total_curr = 0;
WORD32 slice_address;
if(ps_codec->i4_slice_error == 1)
return ret;
idr_pic_flag = (NAL_IDR_W_LP == i1_nal_unit_type) ||
(NAL_IDR_N_LP == i1_nal_unit_type);
BITS_PARSE("first_slice_in_pic_flag", first_slice_in_pic_flag, ps_bitstrm, 1);
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
BITS_PARSE("no_output_of_prior_pics_flag", no_output_of_prior_pics_flag, ps_bitstrm, 1);
}
UEV_PARSE("pic_parameter_set_id", pps_id, ps_bitstrm);
pps_id = CLIP3(pps_id, 0, MAX_PPS_CNT - 2);
/* Get the current PPS structure */
ps_pps = ps_codec->s_parse.ps_pps_base + pps_id;
if(0 == ps_pps->i1_pps_valid)
{
pps_t *ps_pps_ref = ps_codec->ps_pps_base;
while(0 == ps_pps_ref->i1_pps_valid)
ps_pps_ref++;
if((ps_pps_ref - ps_codec->ps_pps_base >= MAX_PPS_CNT - 1))
return IHEVCD_INVALID_HEADER;
ihevcd_copy_pps(ps_codec, pps_id, ps_pps_ref->i1_pps_id);
}
/* Get SPS id for the current PPS */
sps_id = ps_pps->i1_sps_id;
/* Get the current SPS structure */
ps_sps = ps_codec->s_parse.ps_sps_base + sps_id;
/* When the current slice is the first in a pic,
* check whether the previous frame is complete
* If the previous frame is incomplete -
* treat the remaining CTBs as skip */
if((0 != ps_codec->u4_pic_cnt || ps_codec->i4_pic_present) &&
first_slice_in_pic_flag)
{
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
if(first_slice_in_pic_flag)
{
ps_codec->s_parse.i4_cur_slice_idx = 0;
}
else
{
/* If the current slice is not the first slice in the pic,
* but the first one to be parsed, set the current slice indx to 1
* Treat the first slice to be missing and copy the current slice header
* to the first one */
if(0 == ps_codec->i4_pic_present)
ps_codec->s_parse.i4_cur_slice_idx = 1;
}
ps_slice_hdr = ps_codec->s_parse.ps_slice_hdr_base + (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1));
if((ps_pps->i1_dependent_slice_enabled_flag) &&
(!first_slice_in_pic_flag))
{
BITS_PARSE("dependent_slice_flag", value, ps_bitstrm, 1);
/* If dependendent slice, copy slice header from previous slice */
if(value && (ps_codec->s_parse.i4_cur_slice_idx > 0))
{
ihevcd_copy_slice_hdr(ps_codec,
(ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)),
((ps_codec->s_parse.i4_cur_slice_idx - 1) & (MAX_SLICE_HDR_CNT - 1)));
}
ps_slice_hdr->i1_dependent_slice_flag = value;
}
else
{
ps_slice_hdr->i1_dependent_slice_flag = 0;
}
ps_slice_hdr->i1_nal_unit_type = i1_nal_unit_type;
ps_slice_hdr->i1_pps_id = pps_id;
ps_slice_hdr->i1_first_slice_in_pic_flag = first_slice_in_pic_flag;
ps_slice_hdr->i1_no_output_of_prior_pics_flag = 1;
if((NAL_BLA_W_LP <= i1_nal_unit_type) &&
(NAL_RSV_RAP_VCL23 >= i1_nal_unit_type))
{
ps_slice_hdr->i1_no_output_of_prior_pics_flag = no_output_of_prior_pics_flag;
}
ps_slice_hdr->i1_pps_id = pps_id;
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
WORD32 num_bits;
/* Use CLZ to compute Ceil( Log2( PicSizeInCtbsY ) ) */
num_bits = 32 - CLZ(ps_sps->i4_pic_size_in_ctb - 1);
BITS_PARSE("slice_address", value, ps_bitstrm, num_bits);
slice_address = value;
/* If slice address is greater than the number of CTBs in a picture,
* ignore the slice */
if(value >= ps_sps->i4_pic_size_in_ctb)
return IHEVCD_IGNORE_SLICE;
}
else
{
slice_address = 0;
}
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i1_pic_output_flag = 1;
ps_slice_hdr->i4_pic_order_cnt_lsb = 0;
ps_slice_hdr->i1_num_long_term_sps = 0;
ps_slice_hdr->i1_num_long_term_pics = 0;
for(i = 0; i < ps_pps->i1_num_extra_slice_header_bits; i++)
{
BITS_PARSE("slice_reserved_undetermined_flag[ i ]", value, ps_bitstrm, 1);
}
UEV_PARSE("slice_type", value, ps_bitstrm);
ps_slice_hdr->i1_slice_type = value;
/* If the picture is IRAP, slice type must be equal to ISLICE */
if((ps_slice_hdr->i1_nal_unit_type >= NAL_BLA_W_LP) &&
(ps_slice_hdr->i1_nal_unit_type <= NAL_RSV_RAP_VCL23))
ps_slice_hdr->i1_slice_type = ISLICE;
if((ps_slice_hdr->i1_slice_type < 0) ||
(ps_slice_hdr->i1_slice_type > 2))
return IHEVCD_IGNORE_SLICE;
if(ps_pps->i1_output_flag_present_flag)
{
BITS_PARSE("pic_output_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_pic_output_flag = value;
}
ps_slice_hdr->i1_colour_plane_id = 0;
if(1 == ps_sps->i1_separate_colour_plane_flag)
{
BITS_PARSE("colour_plane_id", value, ps_bitstrm, 2);
ps_slice_hdr->i1_colour_plane_id = value;
}
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = 0;
if(!idr_pic_flag)
{
WORD32 st_rps_idx;
WORD32 num_neg_pics;
WORD32 num_pos_pics;
WORD8 *pi1_used;
BITS_PARSE("pic_order_cnt_lsb", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->i4_pic_order_cnt_lsb = value;
BITS_PARSE("short_term_ref_pic_set_sps_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag = value;
if(1 == ps_slice_hdr->i1_short_term_ref_pic_set_sps_flag)
{
WORD32 numbits;
ps_slice_hdr->i1_short_term_ref_pic_set_idx = 0;
if(ps_sps->i1_num_short_term_ref_pic_sets > 1)
{
numbits = 32 - CLZ(ps_sps->i1_num_short_term_ref_pic_sets - 1);
BITS_PARSE("short_term_ref_pic_set_idx", value, ps_bitstrm, numbits);
ps_slice_hdr->i1_short_term_ref_pic_set_idx = value;
}
st_rps_idx = ps_slice_hdr->i1_short_term_ref_pic_set_idx;
num_neg_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_neg_pics;
num_pos_pics = ps_sps->as_stref_picset[st_rps_idx].i1_num_pos_pics;
pi1_used = ps_sps->as_stref_picset[st_rps_idx].ai1_used;
}
else
{
ihevcd_short_term_ref_pic_set(ps_bitstrm,
&ps_sps->as_stref_picset[0],
ps_sps->i1_num_short_term_ref_pic_sets,
ps_sps->i1_num_short_term_ref_pic_sets,
&ps_slice_hdr->s_stref_picset);
st_rps_idx = ps_sps->i1_num_short_term_ref_pic_sets;
num_neg_pics = ps_slice_hdr->s_stref_picset.i1_num_neg_pics;
num_pos_pics = ps_slice_hdr->s_stref_picset.i1_num_pos_pics;
pi1_used = ps_slice_hdr->s_stref_picset.ai1_used;
}
if(ps_sps->i1_long_term_ref_pics_present_flag)
{
if(ps_sps->i1_num_long_term_ref_pics_sps > 0)
{
UEV_PARSE("num_long_term_sps", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_sps = value;
ps_slice_hdr->i1_num_long_term_sps = CLIP3(ps_slice_hdr->i1_num_long_term_sps,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics);
}
UEV_PARSE("num_long_term_pics", value, ps_bitstrm);
ps_slice_hdr->i1_num_long_term_pics = value;
ps_slice_hdr->i1_num_long_term_pics = CLIP3(ps_slice_hdr->i1_num_long_term_pics,
0, MAX_DPB_SIZE - num_neg_pics - num_pos_pics -
ps_slice_hdr->i1_num_long_term_sps);
for(i = 0; i < (ps_slice_hdr->i1_num_long_term_sps +
ps_slice_hdr->i1_num_long_term_pics); i++)
{
if(i < ps_slice_hdr->i1_num_long_term_sps)
{
/* Use CLZ to compute Ceil( Log2( num_long_term_ref_pics_sps ) ) */
WORD32 num_bits = 32 - CLZ(ps_sps->i1_num_long_term_ref_pics_sps);
BITS_PARSE("lt_idx_sps[ i ]", value, ps_bitstrm, num_bits);
ps_slice_hdr->ai4_poc_lsb_lt[i] = ps_sps->ai1_lt_ref_pic_poc_lsb_sps[value];
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = ps_sps->ai1_used_by_curr_pic_lt_sps_flag[value];
}
else
{
BITS_PARSE("poc_lsb_lt[ i ]", value, ps_bitstrm, ps_sps->i1_log2_max_pic_order_cnt_lsb);
ps_slice_hdr->ai4_poc_lsb_lt[i] = value;
BITS_PARSE("used_by_curr_pic_lt_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i] = value;
}
BITS_PARSE("delta_poc_msb_present_flag[ i ]", value, ps_bitstrm, 1);
ps_slice_hdr->ai1_delta_poc_msb_present_flag[i] = value;
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = 0;
if(ps_slice_hdr->ai1_delta_poc_msb_present_flag[i])
{
UEV_PARSE("delata_poc_msb_cycle_lt[ i ]", value, ps_bitstrm);
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] = value;
}
if((i != 0) && (i != ps_slice_hdr->i1_num_long_term_sps))
{
ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i] += ps_slice_hdr->ai1_delta_poc_msb_cycle_lt[i - 1];
}
}
}
for(i = 0; i < num_neg_pics + num_pos_pics; i++)
{
if(pi1_used[i])
{
num_poc_total_curr++;
}
}
for(i = 0; i < ps_slice_hdr->i1_num_long_term_sps + ps_slice_hdr->i1_num_long_term_pics; i++)
{
if(ps_slice_hdr->ai1_used_by_curr_pic_lt_flag[i])
{
num_poc_total_curr++;
}
}
if(ps_sps->i1_sps_temporal_mvp_enable_flag)
{
BITS_PARSE("enable_temporal_mvp_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_temporal_mvp_enable_flag = value;
}
}
ps_slice_hdr->i1_slice_sao_luma_flag = 0;
ps_slice_hdr->i1_slice_sao_chroma_flag = 0;
if(ps_sps->i1_sample_adaptive_offset_enabled_flag)
{
BITS_PARSE("slice_sao_luma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_luma_flag = value;
BITS_PARSE("slice_sao_chroma_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_sao_chroma_flag = value;
}
ps_slice_hdr->i1_max_num_merge_cand = 1;
ps_slice_hdr->i1_cabac_init_flag = 0;
ps_slice_hdr->i1_num_ref_idx_l0_active = 0;
ps_slice_hdr->i1_num_ref_idx_l1_active = 0;
ps_slice_hdr->i1_slice_cb_qp_offset = 0;
ps_slice_hdr->i1_slice_cr_qp_offset = 0;
if((PSLICE == ps_slice_hdr->i1_slice_type) ||
(BSLICE == ps_slice_hdr->i1_slice_type))
{
BITS_PARSE("num_ref_idx_active_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_num_ref_idx_active_override_flag = value;
if(ps_slice_hdr->i1_num_ref_idx_active_override_flag)
{
UEV_PARSE("num_ref_idx_l0_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l0_active = value + 1;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
UEV_PARSE("num_ref_idx_l1_active_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_num_ref_idx_l1_active = value + 1;
}
}
else
{
ps_slice_hdr->i1_num_ref_idx_l0_active = ps_pps->i1_num_ref_idx_l0_default_active;
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
ps_slice_hdr->i1_num_ref_idx_l1_active = ps_pps->i1_num_ref_idx_l1_default_active;
}
}
ps_slice_hdr->i1_num_ref_idx_l0_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l0_active, 0, MAX_DPB_SIZE - 1);
ps_slice_hdr->i1_num_ref_idx_l1_active = CLIP3(ps_slice_hdr->i1_num_ref_idx_l1_active, 0, MAX_DPB_SIZE - 1);
if(0 == num_poc_total_curr)
return IHEVCD_IGNORE_SLICE;
if((ps_pps->i1_lists_modification_present_flag) && (num_poc_total_curr > 1))
{
ihevcd_ref_pic_list_modification(ps_bitstrm,
ps_slice_hdr, num_poc_total_curr);
}
else
{
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l0 = 0;
ps_slice_hdr->s_rplm.i1_ref_pic_list_modification_flag_l1 = 0;
}
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("mvd_l1_zero_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_mvd_l1_zero_flag = value;
}
ps_slice_hdr->i1_cabac_init_flag = 0;
if(ps_pps->i1_cabac_init_present_flag)
{
BITS_PARSE("cabac_init_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_cabac_init_flag = value;
}
ps_slice_hdr->i1_collocated_from_l0_flag = 1;
ps_slice_hdr->i1_collocated_ref_idx = 0;
if(ps_slice_hdr->i1_slice_temporal_mvp_enable_flag)
{
if(BSLICE == ps_slice_hdr->i1_slice_type)
{
BITS_PARSE("collocated_from_l0_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_collocated_from_l0_flag = value;
}
if((ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l0_active > 1)) ||
(!ps_slice_hdr->i1_collocated_from_l0_flag && (ps_slice_hdr->i1_num_ref_idx_l1_active > 1)))
{
UEV_PARSE("collocated_ref_idx", value, ps_bitstrm);
ps_slice_hdr->i1_collocated_ref_idx = value;
}
}
ps_slice_hdr->i1_collocated_ref_idx = CLIP3(ps_slice_hdr->i1_collocated_ref_idx, 0, MAX_DPB_SIZE - 1);
if((ps_pps->i1_weighted_pred_flag && (PSLICE == ps_slice_hdr->i1_slice_type)) ||
(ps_pps->i1_weighted_bipred_flag && (BSLICE == ps_slice_hdr->i1_slice_type)))
{
ihevcd_parse_pred_wt_ofst(ps_bitstrm, ps_sps, ps_pps, ps_slice_hdr);
}
UEV_PARSE("five_minus_max_num_merge_cand", value, ps_bitstrm);
ps_slice_hdr->i1_max_num_merge_cand = 5 - value;
}
ps_slice_hdr->i1_max_num_merge_cand = CLIP3(ps_slice_hdr->i1_max_num_merge_cand, 1, 5);
SEV_PARSE("slice_qp_delta", value, ps_bitstrm);
ps_slice_hdr->i1_slice_qp_delta = value;
if(ps_pps->i1_pic_slice_level_chroma_qp_offsets_present_flag)
{
SEV_PARSE("slice_cb_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cb_qp_offset = value;
SEV_PARSE("slice_cr_qp_offset", value, ps_bitstrm);
ps_slice_hdr->i1_slice_cr_qp_offset = value;
}
ps_slice_hdr->i1_deblocking_filter_override_flag = 0;
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
ps_slice_hdr->i1_beta_offset_div2 = ps_pps->i1_beta_offset_div2;
ps_slice_hdr->i1_tc_offset_div2 = ps_pps->i1_tc_offset_div2;
disable_deblocking_filter_flag = ps_pps->i1_pic_disable_deblocking_filter_flag;
if(ps_pps->i1_deblocking_filter_control_present_flag)
{
if(ps_pps->i1_deblocking_filter_override_enabled_flag)
{
BITS_PARSE("deblocking_filter_override_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_deblocking_filter_override_flag = value;
}
if(ps_slice_hdr->i1_deblocking_filter_override_flag)
{
BITS_PARSE("slice_disable_deblocking_filter_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_disable_deblocking_filter_flag = value;
disable_deblocking_filter_flag = ps_slice_hdr->i1_slice_disable_deblocking_filter_flag;
if(!ps_slice_hdr->i1_slice_disable_deblocking_filter_flag)
{
SEV_PARSE("beta_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_beta_offset_div2 = value;
SEV_PARSE("tc_offset_div2", value, ps_bitstrm);
ps_slice_hdr->i1_tc_offset_div2 = value;
}
}
}
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = ps_pps->i1_loop_filter_across_slices_enabled_flag;
if(ps_pps->i1_loop_filter_across_slices_enabled_flag &&
(ps_slice_hdr->i1_slice_sao_luma_flag || ps_slice_hdr->i1_slice_sao_chroma_flag || !disable_deblocking_filter_flag))
{
BITS_PARSE("slice_loop_filter_across_slices_enabled_flag", value, ps_bitstrm, 1);
ps_slice_hdr->i1_slice_loop_filter_across_slices_enabled_flag = value;
}
}
/* Check sanity of slice */
if((!first_slice_in_pic_flag) &&
(ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_base = ps_codec->ps_slice_hdr_base;
/* According to the standard, the above conditions must be satisfied - But for error resilience,
* only the following conditions are checked */
if((ps_slice_hdr_base->i1_pps_id != ps_slice_hdr->i1_pps_id) ||
(ps_slice_hdr_base->i4_pic_order_cnt_lsb != ps_slice_hdr->i4_pic_order_cnt_lsb))
{
return IHEVCD_IGNORE_SLICE;
}
}
if(0 == ps_codec->i4_pic_present)
{
ps_slice_hdr->i4_abs_pic_order_cnt = ihevcd_calc_poc(ps_codec, ps_nal, ps_sps->i1_log2_max_pic_order_cnt_lsb, ps_slice_hdr->i4_pic_order_cnt_lsb);
}
else
{
ps_slice_hdr->i4_abs_pic_order_cnt = ps_codec->s_parse.i4_abs_pic_order_cnt;
}
if(!first_slice_in_pic_flag)
{
/* Check if the current slice belongs to the same pic (Pic being parsed) */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
{
/* If the Next CTB's index is less than the slice address,
* the previous slice is incomplete.
* Indicate slice error, and treat the remaining CTBs as skip */
if(slice_address > ps_codec->s_parse.i4_next_ctb_indx)
{
if(ps_codec->i4_pic_present)
{
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
return ret;
}
else
{
return IHEVCD_IGNORE_SLICE;
}
}
/* If the slice address is less than the next CTB's index,
* extra CTBs have been decoded in the previous slice.
* Ignore the current slice. Treat it as incomplete */
else if(slice_address < ps_codec->s_parse.i4_next_ctb_indx)
{
return IHEVCD_IGNORE_SLICE;
}
else
{
ps_codec->i4_slice_error = 0;
}
}
/* The current slice does not belong to the pic that is being parsed */
else
{
/* The previous pic is incomplete.
* Treat the remaining CTBs as skip */
if(ps_codec->i4_pic_present)
{
slice_header_t *ps_slice_hdr_next;
ps_codec->i4_slice_error = 1;
ps_codec->s_parse.i4_cur_slice_idx--;
if(ps_codec->s_parse.i4_cur_slice_idx < 0)
ps_codec->s_parse.i4_cur_slice_idx = 0;
ps_slice_hdr_next = ps_codec->s_parse.ps_slice_hdr_base + ((ps_codec->s_parse.i4_cur_slice_idx + 1) & (MAX_SLICE_HDR_CNT - 1));
ps_slice_hdr_next->i2_ctb_x = 0;
ps_slice_hdr_next->i2_ctb_y = ps_codec->s_parse.ps_sps->i2_pic_ht_in_ctb;
return ret;
}
/* If the previous pic is complete,
* return if the current slice is dependant
* otherwise, update the parse context's POC */
else
{
if(ps_slice_hdr->i1_dependent_slice_flag)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
}
}
/* If the slice is the first slice in the pic, update the parse context's POC */
else
{
/* If the first slice is repeated, ignore the second occurrence
* If any other slice is repeated, the CTB addr will be greater than the slice addr,
* and hence the second occurrence is ignored */
if(ps_codec->s_parse.i4_abs_pic_order_cnt == ps_slice_hdr->i4_abs_pic_order_cnt)
return IHEVCD_IGNORE_SLICE;
ps_codec->s_parse.i4_abs_pic_order_cnt = ps_slice_hdr->i4_abs_pic_order_cnt;
}
ps_slice_hdr->i4_num_entry_point_offsets = 0;
if((ps_pps->i1_tiles_enabled_flag) ||
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
UEV_PARSE("num_entry_point_offsets", value, ps_bitstrm);
ps_slice_hdr->i4_num_entry_point_offsets = value;
{
WORD32 max_num_entry_point_offsets;
if((ps_pps->i1_tiles_enabled_flag) &&
(ps_pps->i1_entropy_coding_sync_enabled_flag))
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * (ps_sps->i2_pic_ht_in_ctb - 1);
}
else if(ps_pps->i1_tiles_enabled_flag)
{
max_num_entry_point_offsets = ps_pps->i1_num_tile_columns * ps_pps->i1_num_tile_rows;
}
else
{
max_num_entry_point_offsets = (ps_sps->i2_pic_ht_in_ctb - 1);
}
ps_slice_hdr->i4_num_entry_point_offsets = CLIP3(ps_slice_hdr->i4_num_entry_point_offsets,
0, max_num_entry_point_offsets);
}
if(ps_slice_hdr->i4_num_entry_point_offsets > 0)
{
UEV_PARSE("offset_len_minus1", value, ps_bitstrm);
ps_slice_hdr->i1_offset_len = value + 1;
for(i = 0; i < ps_slice_hdr->i4_num_entry_point_offsets; i++)
{
BITS_PARSE("entry_point_offset", value, ps_bitstrm, ps_slice_hdr->i1_offset_len);
/* TODO: pu4_entry_point_offset needs to be initialized */
}
}
}
if(ps_pps->i1_slice_header_extension_present_flag)
{
UEV_PARSE("slice_header_extension_length", value, ps_bitstrm);
ps_slice_hdr->i2_slice_header_extension_length = value;
for(i = 0; i < ps_slice_hdr->i2_slice_header_extension_length; i++)
{
BITS_PARSE("slice_header_extension_data_byte", value, ps_bitstrm, 8);
}
}
ihevcd_bits_flush_to_byte_boundary(ps_bitstrm);
{
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
WORD32 r_idx;
if((NAL_IDR_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_IDR_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_N_LP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_DLP == ps_slice_hdr->i1_nal_unit_type) ||
(NAL_BLA_W_LP == ps_slice_hdr->i1_nal_unit_type) ||
(0 == ps_codec->u4_pic_cnt))
{
for(i = 0; i < MAX_DPB_BUFS; i++)
{
if(ps_dpb_mgr->as_dpb_info[i].ps_pic_buf)
{
pic_buf_t *ps_pic_buf = ps_dpb_mgr->as_dpb_info[i].ps_pic_buf;
mv_buf_t *ps_mv_buf;
/* Long term index is set to MAX_DPB_BUFS to ensure it is not added as LT */
ihevc_dpb_mgr_del_ref((dpb_mgr_t *)ps_codec->pv_dpb_mgr, (buf_mgr_t *)ps_codec->pv_pic_buf_mgr, ps_pic_buf->i4_abs_poc);
/* Find buffer id of the MV bank corresponding to the buffer being freed (Buffer with POC of u4_abs_poc) */
ps_mv_buf = (mv_buf_t *)ps_codec->ps_mv_buf;
for(i = 0; i < BUF_MGR_MAX_CNT; i++)
{
if(ps_mv_buf && ps_mv_buf->i4_abs_poc == ps_pic_buf->i4_abs_poc)
{
ihevc_buf_mgr_release((buf_mgr_t *)ps_codec->pv_mv_buf_mgr, i, BUF_MGR_REF);
break;
}
ps_mv_buf++;
}
}
}
/* Initialize the reference lists to NULL
* This is done to take care of the cases where the first pic is not IDR
* but the reference list is not created for the first pic because
* pic count is zero leaving the reference list uninitialised */
for(r_idx = 0; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = NULL;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = NULL;
}
}
else
{
ret = ihevcd_ref_list(ps_codec, ps_pps, ps_sps, ps_slice_hdr);
if ((WORD32)IHEVCD_SUCCESS != ret)
{
return ret;
}
}
}
/* Fill the remaining entries of the reference lists with the nearest POC
* This is done to handle cases where there is a corruption in the reference index */
if(ps_codec->i4_pic_present)
{
pic_buf_t *ps_pic_buf_ref;
mv_buf_t *ps_mv_buf_ref;
WORD32 r_idx;
dpb_mgr_t *ps_dpb_mgr = (dpb_mgr_t *)ps_codec->pv_dpb_mgr;
buf_mgr_t *ps_mv_buf_mgr = (buf_mgr_t *)ps_codec->pv_mv_buf_mgr;
ps_pic_buf_ref = ihevc_dpb_mgr_get_ref_by_nearest_poc(ps_dpb_mgr, ps_slice_hdr->i4_abs_pic_order_cnt);
if(NULL == ps_pic_buf_ref)
{
ps_pic_buf_ref = ps_codec->as_process[0].ps_cur_pic;
ps_mv_buf_ref = ps_codec->s_parse.ps_cur_mv_buf;
}
else
{
ps_mv_buf_ref = ihevcd_mv_mgr_get_poc(ps_mv_buf_mgr, ps_pic_buf_ref->i4_abs_poc);
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l0_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list0[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
for(r_idx = 0; r_idx < ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx++)
{
if(NULL == ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
for(r_idx = ps_slice_hdr->i1_num_ref_idx_l1_active; r_idx < MAX_DPB_SIZE; r_idx++)
{
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_pic_buf = (void *)ps_pic_buf_ref;
ps_slice_hdr->as_ref_pic_list1[r_idx].pv_mv_buf = (void *)ps_mv_buf_ref;
}
}
/* Update slice address in the header */
if(!ps_slice_hdr->i1_first_slice_in_pic_flag)
{
ps_slice_hdr->i2_ctb_x = slice_address % ps_sps->i2_pic_wd_in_ctb;
ps_slice_hdr->i2_ctb_y = slice_address / ps_sps->i2_pic_wd_in_ctb;
if(!ps_slice_hdr->i1_dependent_slice_flag)
{
ps_slice_hdr->i2_independent_ctb_x = ps_slice_hdr->i2_ctb_x;
ps_slice_hdr->i2_independent_ctb_y = ps_slice_hdr->i2_ctb_y;
}
}
else
{
ps_slice_hdr->i2_ctb_x = 0;
ps_slice_hdr->i2_ctb_y = 0;
ps_slice_hdr->i2_independent_ctb_x = 0;
ps_slice_hdr->i2_independent_ctb_y = 0;
}
/* If the first slice in the pic is missing, copy the current slice header to
* the first slice's header */
if((!first_slice_in_pic_flag) &&
(0 == ps_codec->i4_pic_present))
{
slice_header_t *ps_slice_hdr_prev = ps_codec->s_parse.ps_slice_hdr_base;
ihevcd_copy_slice_hdr(ps_codec, 0, (ps_codec->s_parse.i4_cur_slice_idx & (MAX_SLICE_HDR_CNT - 1)));
ps_codec->i4_slice_error = 1;
ps_slice_hdr_prev->i2_ctb_x = 0;
ps_slice_hdr_prev->i2_ctb_y = 0;
ps_codec->s_parse.i4_ctb_x = 0;
ps_codec->s_parse.i4_ctb_y = 0;
ps_codec->s_parse.i4_cur_slice_idx = 0;
if((ps_slice_hdr->i2_ctb_x == 0) &&
(ps_slice_hdr->i2_ctb_y == 0))
{
ps_slice_hdr->i2_ctb_x++;
}
}
{
/* If skip B is enabled,
* ignore pictures that are non-reference
* TODO: (i1_nal_unit_type < NAL_BLA_W_LP) && (i1_nal_unit_type % 2 == 0) only says it is
* sub-layer non-reference slice. May need to find a way to detect actual non-reference pictures*/
if((i1_nal_unit_type < NAL_BLA_W_LP) &&
(i1_nal_unit_type % 2 == 0))
{
if(IVD_SKIP_B == ps_codec->e_pic_skip_mode)
return IHEVCD_IGNORE_SLICE;
}
/* If skip PB is enabled,
* decode only I slices */
if((IVD_SKIP_PB == ps_codec->e_pic_skip_mode) &&
(ISLICE != ps_slice_hdr->i1_slice_type))
{
return IHEVCD_IGNORE_SLICE;
}
}
return ret;
}
| 174,007 |
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 Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
const content::NavigationEntry* entry =
source->GetController().GetActiveEntry();
if (entry) {
const GURL& url = entry->GetURL();
const GURL& virtual_url = entry->GetVirtualURL();
if ((url.SchemeIs(content::kChromeUIScheme) &&
url.host_piece() == chrome::kChromeUINewTabHost) ||
(virtual_url.SchemeIs(content::kChromeUIScheme) &&
virtual_url.host_piece() == chrome::kChromeUINewTabHost)) {
return true;
}
}
return search::NavEntryIsInstantNTP(source, entry);
}
Commit Message: Don't focus the location bar for NTP navigations in non-selected tabs.
BUG=677716
TEST=See bug for repro steps.
Review-Url: https://codereview.chromium.org/2624373002
Cr-Commit-Position: refs/heads/master@{#443338}
CWE ID: | bool Browser::ShouldFocusLocationBarByDefault(WebContents* source) {
// Navigations in background tabs shouldn't change the focus state of the
// omnibox, since it's associated with the foreground tab.
if (source != tab_strip_model_->GetActiveWebContents())
return false;
const content::NavigationEntry* entry =
source->GetController().GetActiveEntry();
if (entry) {
const GURL& url = entry->GetURL();
const GURL& virtual_url = entry->GetVirtualURL();
if ((url.SchemeIs(content::kChromeUIScheme) &&
url.host_piece() == chrome::kChromeUINewTabHost) ||
(virtual_url.SchemeIs(content::kChromeUIScheme) &&
virtual_url.host_piece() == chrome::kChromeUINewTabHost)) {
return true;
}
}
return search::NavEntryIsInstantNTP(source, entry);
}
| 172,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: long join_session_keyring(const char *name)
{
const struct cred *old;
struct cred *new;
struct key *keyring;
long ret, serial;
new = prepare_creds();
if (!new)
return -ENOMEM;
old = current_cred();
/* if no name is provided, install an anonymous keyring */
if (!name) {
ret = install_session_keyring_to_cred(new, NULL);
if (ret < 0)
goto error;
serial = new->session_keyring->serial;
ret = commit_creds(new);
if (ret == 0)
ret = serial;
goto okay;
}
/* allow the user to join or create a named keyring */
mutex_lock(&key_session_mutex);
/* look for an existing keyring of this name */
keyring = find_keyring_by_name(name, false);
if (PTR_ERR(keyring) == -ENOKEY) {
/* not found - try and create a new one */
keyring = keyring_alloc(
name, old->uid, old->gid, old,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
}
} else if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
} else if (keyring == new->session_keyring) {
ret = 0;
goto error2;
}
/* we've got a keyring - now to install it */
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0)
goto error2;
commit_creds(new);
mutex_unlock(&key_session_mutex);
ret = keyring->serial;
key_put(keyring);
okay:
return ret;
error2:
mutex_unlock(&key_session_mutex);
error:
abort_creds(new);
return ret;
}
Commit Message: KEYS: Fix keyring ref leak in join_session_keyring()
This fixes CVE-2016-0728.
If a thread is asked to join as a session keyring the keyring that's already
set as its session, we leak a keyring reference.
This can be tested with the following program:
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <keyutils.h>
int main(int argc, const char *argv[])
{
int i = 0;
key_serial_t serial;
serial = keyctl(KEYCTL_JOIN_SESSION_KEYRING,
"leaked-keyring");
if (serial < 0) {
perror("keyctl");
return -1;
}
if (keyctl(KEYCTL_SETPERM, serial,
KEY_POS_ALL | KEY_USR_ALL) < 0) {
perror("keyctl");
return -1;
}
for (i = 0; i < 100; i++) {
serial = keyctl(KEYCTL_JOIN_SESSION_KEYRING,
"leaked-keyring");
if (serial < 0) {
perror("keyctl");
return -1;
}
}
return 0;
}
If, after the program has run, there something like the following line in
/proc/keys:
3f3d898f I--Q--- 100 perm 3f3f0000 0 0 keyring leaked-keyring: empty
with a usage count of 100 * the number of times the program has been run,
then the kernel is malfunctioning. If leaked-keyring has zero usages or
has been garbage collected, then the problem is fixed.
Reported-by: Yevgeny Pats <[email protected]>
Signed-off-by: David Howells <[email protected]>
Acked-by: Don Zickus <[email protected]>
Acked-by: Prarit Bhargava <[email protected]>
Acked-by: Jarod Wilson <[email protected]>
Signed-off-by: James Morris <[email protected]>
CWE ID: | long join_session_keyring(const char *name)
{
const struct cred *old;
struct cred *new;
struct key *keyring;
long ret, serial;
new = prepare_creds();
if (!new)
return -ENOMEM;
old = current_cred();
/* if no name is provided, install an anonymous keyring */
if (!name) {
ret = install_session_keyring_to_cred(new, NULL);
if (ret < 0)
goto error;
serial = new->session_keyring->serial;
ret = commit_creds(new);
if (ret == 0)
ret = serial;
goto okay;
}
/* allow the user to join or create a named keyring */
mutex_lock(&key_session_mutex);
/* look for an existing keyring of this name */
keyring = find_keyring_by_name(name, false);
if (PTR_ERR(keyring) == -ENOKEY) {
/* not found - try and create a new one */
keyring = keyring_alloc(
name, old->uid, old->gid, old,
KEY_POS_ALL | KEY_USR_VIEW | KEY_USR_READ | KEY_USR_LINK,
KEY_ALLOC_IN_QUOTA, NULL);
if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
}
} else if (IS_ERR(keyring)) {
ret = PTR_ERR(keyring);
goto error2;
} else if (keyring == new->session_keyring) {
key_put(keyring);
ret = 0;
goto error2;
}
/* we've got a keyring - now to install it */
ret = install_session_keyring_to_cred(new, keyring);
if (ret < 0)
goto error2;
commit_creds(new);
mutex_unlock(&key_session_mutex);
ret = keyring->serial;
key_put(keyring);
okay:
return ret;
error2:
mutex_unlock(&key_session_mutex);
error:
abort_creds(new);
return ret;
}
| 167,452 |
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 sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
newsk->sk_state = TCP_SYN_RECV;
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
newsk->sk_write_space = sk_stream_write_space;
/* listeners have SOCK_RCU_FREE, not the children */
sock_reset_flag(newsk, SOCK_RCU_FREE);
newsk->sk_mark = inet_rsk(req)->ir_mark;
atomic64_set(&newsk->sk_cookie,
atomic64_read(&inet_rsk(req)->ir_cookie));
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
security_inet_csk_clone(newsk, req);
}
return newsk;
}
Commit Message: dccp/tcp: do not inherit mc_list from parent
syzkaller found a way to trigger double frees from ip_mc_drop_socket()
It turns out that leave a copy of parent mc_list at accept() time,
which is very bad.
Very similar to commit 8b485ce69876 ("tcp: do not inherit
fastopen_req from parent")
Initial report from Pray3r, completed by Andrey one.
Thanks a lot to them !
Signed-off-by: Eric Dumazet <[email protected]>
Reported-by: Pray3r <[email protected]>
Reported-by: Andrey Konovalov <[email protected]>
Tested-by: Andrey Konovalov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-415 | struct sock *inet_csk_clone_lock(const struct sock *sk,
const struct request_sock *req,
const gfp_t priority)
{
struct sock *newsk = sk_clone_lock(sk, priority);
if (newsk) {
struct inet_connection_sock *newicsk = inet_csk(newsk);
newsk->sk_state = TCP_SYN_RECV;
newicsk->icsk_bind_hash = NULL;
inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
newsk->sk_write_space = sk_stream_write_space;
/* listeners have SOCK_RCU_FREE, not the children */
sock_reset_flag(newsk, SOCK_RCU_FREE);
inet_sk(newsk)->mc_list = NULL;
newsk->sk_mark = inet_rsk(req)->ir_mark;
atomic64_set(&newsk->sk_cookie,
atomic64_read(&inet_rsk(req)->ir_cookie));
newicsk->icsk_retransmits = 0;
newicsk->icsk_backoff = 0;
newicsk->icsk_probes_out = 0;
/* Deinitialize accept_queue to trap illegal accesses. */
memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
security_inet_csk_clone(newsk, req);
}
return newsk;
}
| 168,190 |
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 UpdatePropertyCallback(IBusPanelService* panel,
IBusProperty* ibus_prop,
gpointer user_data) {
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->UpdateProperty(ibus_prop);
}
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 | static void UpdatePropertyCallback(IBusPanelService* panel,
void UpdateProperty(IBusPanelService* panel, IBusProperty* ibus_prop) {
VLOG(1) << "UpdateProperty";
DCHECK(ibus_prop);
// You can call
// LOG(INFO) << "\n" << PrintProp(ibus_prop, 0);
// here to dump |ibus_prop|.
ImePropertyList prop_list; // our representation.
if (!FlattenProperty(ibus_prop, &prop_list)) {
// Don't update the UI on errors.
LOG(ERROR) << "Malformed properties are detected";
return;
}
// Notify the change.
if (!prop_list.empty()) {
FOR_EACH_OBSERVER(Observer, observers_,
OnUpdateImeProperty(prop_list));
}
}
| 170,551 |
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 write_empty_blocks(struct page *page, unsigned from, unsigned to,
int mode)
{
struct inode *inode = page->mapping->host;
unsigned start, end, next, blksize;
sector_t block = page->index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
int ret;
blksize = 1 << inode->i_blkbits;
next = end = 0;
while (next < from) {
next += blksize;
block++;
}
start = next;
do {
next += blksize;
ret = needs_empty_write(block, inode);
if (unlikely(ret < 0))
return ret;
if (ret == 0) {
if (end) {
ret = __block_write_begin(page, start, end - start,
gfs2_block_map);
if (unlikely(ret))
return ret;
ret = empty_write_end(page, start, end, mode);
if (unlikely(ret))
return ret;
end = 0;
}
start = next;
}
else
end = next;
block++;
} while (next < to);
if (end) {
ret = __block_write_begin(page, start, end - start, gfs2_block_map);
if (unlikely(ret))
return ret;
ret = empty_write_end(page, start, end, mode);
if (unlikely(ret))
return ret;
}
return 0;
}
Commit Message: GFS2: rewrite fallocate code to write blocks directly
GFS2's fallocate code currently goes through the page cache. Since it's only
writing to the end of the file or to holes in it, it doesn't need to, and it
was causing issues on low memory environments. This patch pulls in some of
Steve's block allocation work, and uses it to simply allocate the blocks for
the file, and zero them out at allocation time. It provides a slight
performance increase, and it dramatically simplifies the code.
Signed-off-by: Benjamin Marzinski <[email protected]>
Signed-off-by: Steven Whitehouse <[email protected]>
CWE ID: CWE-119 | static int write_empty_blocks(struct page *page, unsigned from, unsigned to,
| 166,215 |
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: SYSCALL_DEFINE5(osf_getsysinfo, unsigned long, op, void __user *, buffer,
unsigned long, nbytes, int __user *, start, void __user *, arg)
{
unsigned long w;
struct percpu_struct *cpu;
switch (op) {
case GSI_IEEE_FP_CONTROL:
/* Return current software fp control & status bits. */
/* Note that DU doesn't verify available space here. */
w = current_thread_info()->ieee_state & IEEE_SW_MASK;
w = swcr_update_status(w, rdfpcr());
if (put_user(w, (unsigned long __user *) buffer))
return -EFAULT;
return 0;
case GSI_IEEE_STATE_AT_SIGNAL:
/*
* Not sure anybody will ever use this weird stuff. These
* ops can be used (under OSF/1) to set the fpcr that should
* be used when a signal handler starts executing.
*/
break;
case GSI_UACPROC:
if (nbytes < sizeof(unsigned int))
return -EINVAL;
w = (current_thread_info()->flags >> UAC_SHIFT) & UAC_BITMASK;
if (put_user(w, (unsigned int __user *)buffer))
return -EFAULT;
return 1;
case GSI_PROC_TYPE:
if (nbytes < sizeof(unsigned long))
return -EINVAL;
cpu = (struct percpu_struct*)
((char*)hwrpb + hwrpb->processor_offset);
w = cpu->type;
if (put_user(w, (unsigned long __user*)buffer))
return -EFAULT;
return 1;
case GSI_GET_HWRPB:
if (nbytes < sizeof(*hwrpb))
return -EINVAL;
if (copy_to_user(buffer, hwrpb, nbytes) != 0)
return -EFAULT;
return 1;
default:
break;
}
return -EOPNOTSUPP;
}
Commit Message: alpha: fix several security issues
Fix several security issues in Alpha-specific syscalls. Untested, but
mostly trivial.
1. Signedness issue in osf_getdomainname allows copying out-of-bounds
kernel memory to userland.
2. Signedness issue in osf_sysinfo allows copying large amounts of
kernel memory to userland.
3. Typo (?) in osf_getsysinfo bounds minimum instead of maximum copy
size, allowing copying large amounts of kernel memory to userland.
4. Usage of user pointer in osf_wait4 while under KERNEL_DS allows
privilege escalation via writing return value of sys_wait4 to kernel
memory.
Signed-off-by: Dan Rosenberg <[email protected]>
Cc: Richard Henderson <[email protected]>
Cc: Ivan Kokshaysky <[email protected]>
Cc: Matt Turner <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-264 | SYSCALL_DEFINE5(osf_getsysinfo, unsigned long, op, void __user *, buffer,
unsigned long, nbytes, int __user *, start, void __user *, arg)
{
unsigned long w;
struct percpu_struct *cpu;
switch (op) {
case GSI_IEEE_FP_CONTROL:
/* Return current software fp control & status bits. */
/* Note that DU doesn't verify available space here. */
w = current_thread_info()->ieee_state & IEEE_SW_MASK;
w = swcr_update_status(w, rdfpcr());
if (put_user(w, (unsigned long __user *) buffer))
return -EFAULT;
return 0;
case GSI_IEEE_STATE_AT_SIGNAL:
/*
* Not sure anybody will ever use this weird stuff. These
* ops can be used (under OSF/1) to set the fpcr that should
* be used when a signal handler starts executing.
*/
break;
case GSI_UACPROC:
if (nbytes < sizeof(unsigned int))
return -EINVAL;
w = (current_thread_info()->flags >> UAC_SHIFT) & UAC_BITMASK;
if (put_user(w, (unsigned int __user *)buffer))
return -EFAULT;
return 1;
case GSI_PROC_TYPE:
if (nbytes < sizeof(unsigned long))
return -EINVAL;
cpu = (struct percpu_struct*)
((char*)hwrpb + hwrpb->processor_offset);
w = cpu->type;
if (put_user(w, (unsigned long __user*)buffer))
return -EFAULT;
return 1;
case GSI_GET_HWRPB:
if (nbytes > sizeof(*hwrpb))
return -EINVAL;
if (copy_to_user(buffer, hwrpb, nbytes) != 0)
return -EFAULT;
return 1;
default:
break;
}
return -EOPNOTSUPP;
}
| 165,870 |
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 SoftOpus::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.opus",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidOpus:
{
const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(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 SoftOpus::internalSetParameter(
OMX_INDEXTYPE index, const OMX_PTR params) {
switch ((int)index) {
case OMX_IndexParamStandardComponentRole:
{
const OMX_PARAM_COMPONENTROLETYPE *roleParams =
(const OMX_PARAM_COMPONENTROLETYPE *)params;
if (!isValidOMXParam(roleParams)) {
return OMX_ErrorBadParameter;
}
if (strncmp((const char *)roleParams->cRole,
"audio_decoder.opus",
OMX_MAX_STRINGNAME_SIZE - 1)) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
case OMX_IndexParamAudioAndroidOpus:
{
const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *opusParams =
(const OMX_AUDIO_PARAM_ANDROID_OPUSTYPE *)params;
if (!isValidOMXParam(opusParams)) {
return OMX_ErrorBadParameter;
}
if (opusParams->nPortIndex != 0) {
return OMX_ErrorUndefined;
}
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalSetParameter(index, params);
}
}
| 174,217 |
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: _pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw)
{
PyObject *logical = NULL; /* input unicode or string object */
FriBidiParType base = FRIBIDI_TYPE_RTL; /* optional direction */
const char *encoding = "utf-8"; /* optional input string encoding */
int clean = 0; /* optional flag to clean the string */
int reordernsm = 1; /* optional flag to allow reordering of non spacing marks*/
static char *kwargs[] =
{ "logical", "base_direction", "encoding", "clean", "reordernsm", NULL };
if (!PyArg_ParseTupleAndKeywords (args, kw, "O|isii", kwargs,
&logical, &base, &encoding, &clean, &reordernsm))
return NULL;
/* Validate base */
if (!(base == FRIBIDI_TYPE_RTL ||
base == FRIBIDI_TYPE_LTR || base == FRIBIDI_TYPE_ON))
return PyErr_Format (PyExc_ValueError,
"invalid value %d: use either RTL, LTR or ON",
base);
/* Check object type and delegate to one of the log2vis functions */
if (PyUnicode_Check (logical))
return log2vis_unicode (logical, base, clean, reordernsm);
else if (PyString_Check (logical))
return log2vis_encoded_string (logical, encoding, base, clean, reordernsm);
else
return PyErr_Format (PyExc_TypeError,
"expected unicode or str, not %s",
logical->ob_type->tp_name);
}
Commit Message: refactor pyfribidi.c module
pyfribidi.c is now compiled as _pyfribidi. This module only handles
unicode internally and doesn't use the fribidi_utf8_to_unicode
function (which can't handle 4 byte utf-8 sequences). This fixes the
buffer overflow in issue #2.
The code is now also much simpler: pyfribidi.c is down from 280 to 130
lines of code.
We now ship a pure python pyfribidi that handles the case when
non-unicode strings are passed in.
We now also adapt the size of the output string if clean=True is
passed.
CWE ID: CWE-119 | _pyfribidi_log2vis (PyObject * self, PyObject * args, PyObject * kw)
unicode_log2vis (PyUnicodeObject* string,
FriBidiParType base_direction, int clean, int reordernsm)
{
int i;
int length = string->length;
FriBidiChar *logical = NULL; /* input fribidi unicode buffer */
FriBidiChar *visual = NULL; /* output fribidi unicode buffer */
FriBidiStrIndex new_len = 0; /* length of the UTF-8 buffer */
PyUnicodeObject *result = NULL;
/* Allocate fribidi unicode buffers
TODO - Don't copy strings if sizeof(FriBidiChar) == sizeof(Py_UNICODE)
*/
logical = PyMem_New (FriBidiChar, length + 1);
if (logical == NULL) {
PyErr_NoMemory();
goto cleanup;
}
visual = PyMem_New (FriBidiChar, length + 1);
if (visual == NULL) {
PyErr_NoMemory();
goto cleanup;
}
for (i=0; i<length; ++i) {
logical[i] = string->str[i];
}
/* Convert to unicode and order visually */
fribidi_set_reorder_nsm(reordernsm);
if (!fribidi_log2vis (logical, length, &base_direction, visual,
NULL, NULL, NULL)) {
PyErr_SetString (PyExc_RuntimeError,
"fribidi failed to order string");
goto cleanup;
}
/* Cleanup the string if requested */
if (clean) {
length = fribidi_remove_bidi_marks (visual, length, NULL, NULL, NULL);
}
result = (PyUnicodeObject*) PyUnicode_FromUnicode(NULL, length);
if (result == NULL) {
goto cleanup;
}
for (i=0; i<length; ++i) {
result->str[i] = visual[i];
}
cleanup:
/* Delete unicode buffers */
PyMem_Del (logical);
PyMem_Del (visual);
return (PyObject *)result;
}
| 165,638 |
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 VideoCaptureImpl::OnBufferCreated(int32_t buffer_id,
mojo::ScopedSharedBufferHandle handle) {
DVLOG(1) << __func__ << " buffer_id: " << buffer_id;
DCHECK(io_thread_checker_.CalledOnValidThread());
DCHECK(handle.is_valid());
base::SharedMemoryHandle memory_handle;
size_t memory_size = 0;
bool read_only_flag = false;
const MojoResult result = mojo::UnwrapSharedMemoryHandle(
std::move(handle), &memory_handle, &memory_size, &read_only_flag);
DCHECK_EQ(MOJO_RESULT_OK, result);
DCHECK_GT(memory_size, 0u);
std::unique_ptr<base::SharedMemory> shm(
new base::SharedMemory(memory_handle, true /* read_only */));
if (!shm->Map(memory_size)) {
DLOG(ERROR) << "OnBufferCreated: Map failed.";
return;
}
const bool inserted =
client_buffers_
.insert(std::make_pair(buffer_id,
new ClientBuffer(std::move(shm), memory_size)))
.second;
DCHECK(inserted);
}
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 VideoCaptureImpl::OnBufferCreated(int32_t buffer_id,
mojo::ScopedSharedBufferHandle handle) {
DVLOG(1) << __func__ << " buffer_id: " << buffer_id;
DCHECK(io_thread_checker_.CalledOnValidThread());
DCHECK(handle.is_valid());
base::SharedMemoryHandle memory_handle;
size_t memory_size = 0;
mojo::UnwrappedSharedMemoryHandleProtection protection;
const MojoResult result = mojo::UnwrapSharedMemoryHandle(
std::move(handle), &memory_handle, &memory_size, &protection);
DCHECK_EQ(MOJO_RESULT_OK, result);
DCHECK_GT(memory_size, 0u);
// TODO(https://crbug.com/803136): We should also be able to assert that the
// unwrapped handle was shared for read-only mapping. That condition is not
// currently guaranteed to be met.
std::unique_ptr<base::SharedMemory> shm(
new base::SharedMemory(memory_handle, true /* read_only */));
if (!shm->Map(memory_size)) {
DLOG(ERROR) << "OnBufferCreated: Map failed.";
return;
}
const bool inserted =
client_buffers_
.insert(std::make_pair(buffer_id,
new ClientBuffer(std::move(shm), memory_size)))
.second;
DCHECK(inserted);
}
| 172,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: void HTMLImportsController::Dispose() {
for (const auto& loader : loaders_)
loader->Dispose();
loaders_.clear();
if (root_) {
root_->Dispose();
root_.Clear();
}
}
Commit Message: Speculative fix for crashes in HTMLImportsController::Dispose().
Copy the loaders_ vector before iterating it.
This CL has no tests because we don't know stable reproduction.
Bug: 843151
Change-Id: I3d5e184657cbce56dcfca0c717d7a0c464e20efe
Reviewed-on: https://chromium-review.googlesource.com/1245017
Reviewed-by: Keishi Hattori <[email protected]>
Commit-Queue: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#594226}
CWE ID: CWE-416 | void HTMLImportsController::Dispose() {
// TODO(tkent): We copy loaders_ before iteration to avoid crashes.
// This copy should be unnecessary. loaders_ is not modified during
// the iteration. Also, null-check for |loader| should be
// unnecessary. crbug.com/843151.
LoaderList list;
list.swap(loaders_);
for (const auto& loader : list) {
if (loader)
loader->Dispose();
}
if (root_) {
root_->Dispose();
root_.Clear();
}
}
| 172,663 |
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 qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = s->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);
if (ret < 0) {
error_setg(errp, "Failed to read l1 table for snapshot");
g_free(new_l1_table);
return ret;
}
/* Switch the L1 table */
g_free(s->l1_table);
s->l1_size = sn->l1_size;
s->l1_table_offset = sn->l1_table_offset;
s->l1_table = new_l1_table;
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
return 0;
}
Commit Message:
CWE ID: CWE-119 | int qcow2_snapshot_load_tmp(BlockDriverState *bs,
const char *snapshot_id,
const char *name,
Error **errp)
{
int i, snapshot_index;
BDRVQcowState *s = bs->opaque;
QCowSnapshot *sn;
uint64_t *new_l1_table;
int new_l1_bytes;
int ret;
assert(bs->read_only);
/* Search the snapshot */
snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);
if (snapshot_index < 0) {
error_setg(errp,
"Can't find snapshot");
return -ENOENT;
}
sn = &s->snapshots[snapshot_index];
/* Allocate and read in the snapshot's L1 table */
new_l1_bytes = sn->l1_size * sizeof(uint64_t);
new_l1_table = g_malloc0(align_offset(new_l1_bytes, 512));
ret = bdrv_pread(bs->file, sn->l1_table_offset, new_l1_table, new_l1_bytes);
if (ret < 0) {
error_setg(errp, "Failed to read l1 table for snapshot");
g_free(new_l1_table);
return ret;
}
/* Switch the L1 table */
g_free(s->l1_table);
s->l1_size = sn->l1_size;
s->l1_table_offset = sn->l1_table_offset;
s->l1_table = new_l1_table;
for(i = 0;i < s->l1_size; i++) {
be64_to_cpus(&s->l1_table[i]);
}
return 0;
}
| 165,402 |
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 bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
uint32_t size;
} prd;
Commit Message:
CWE ID: CWE-399 | static int bmdma_prepare_buf(IDEDMA *dma, int is_write)
/**
* Return the number of bytes successfully prepared.
* -1 on error.
*/
static int32_t bmdma_prepare_buf(IDEDMA *dma, int is_write)
{
BMDMAState *bm = DO_UPCAST(BMDMAState, dma, dma);
IDEState *s = bmdma_active_if(bm);
uint32_t size;
} prd;
| 164,840 |
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: PHP_FUNCTION( locale_get_region )
{
get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
Commit Message: Fix bug #72241: get_icu_value_internal out-of-bounds read
CWE ID: CWE-125 | PHP_FUNCTION( locale_get_region )
PHP_FUNCTION( locale_get_region )
{
get_icu_value_src_php( LOC_REGION_TAG , INTERNAL_FUNCTION_PARAM_PASSTHRU );
}
| 167,183 |
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 Np_toString(js_State *J)
{
char buf[32];
js_Object *self = js_toobject(J, 0);
int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);
if (self->type != JS_CNUMBER)
js_typeerror(J, "not a number");
if (radix == 10) {
js_pushstring(J, jsV_numbertostring(J, buf, self->u.number));
return;
}
if (radix < 2 || radix > 36)
js_rangeerror(J, "invalid radix");
/* lame number to string conversion for any radix from 2 to 36 */
{
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
char buf[100];
double number = self->u.number;
int sign = self->u.number < 0;
js_Buffer *sb = NULL;
uint64_t u, limit = ((uint64_t)1<<52);
int ndigits, exp, point;
if (number == 0) { js_pushstring(J, "0"); return; }
if (isnan(number)) { js_pushstring(J, "NaN"); return; }
if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; }
if (sign)
number = -number;
/* fit as many digits as we want in an int */
exp = 0;
while (number * pow(radix, exp) > limit)
--exp;
while (number * pow(radix, exp+1) < limit)
++exp;
u = number * pow(radix, exp) + 0.5;
/* trim trailing zeros */
while (u > 0 && (u % radix) == 0) {
u /= radix;
--exp;
}
/* serialize digits */
ndigits = 0;
while (u > 0) {
buf[ndigits++] = digits[u % radix];
u /= radix;
}
point = ndigits - exp;
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
if (sign)
js_putc(J, &sb, '-');
if (point <= 0) {
js_putc(J, &sb, '0');
js_putc(J, &sb, '.');
while (point++ < 0)
js_putc(J, &sb, '0');
while (ndigits-- > 0)
js_putc(J, &sb, buf[ndigits]);
} else {
while (ndigits-- > 0) {
js_putc(J, &sb, buf[ndigits]);
if (--point == 0 && ndigits > 0)
js_putc(J, &sb, '.');
}
while (point-- > 0)
js_putc(J, &sb, '0');
}
js_putc(J, &sb, 0);
js_pushstring(J, sb->s);
js_endtry(J);
js_free(J, sb);
}
}
Commit Message: Bug 700938: Fix stack overflow in numtostr as used by Number#toFixed().
32 is not enough to fit sprintf("%.20f", 1e20).
We need at least 43 bytes to fit that format.
Bump the static buffer size.
CWE ID: CWE-119 | static void Np_toString(js_State *J)
{
char buf[100];
js_Object *self = js_toobject(J, 0);
int radix = js_isundefined(J, 1) ? 10 : js_tointeger(J, 1);
if (self->type != JS_CNUMBER)
js_typeerror(J, "not a number");
if (radix == 10) {
js_pushstring(J, jsV_numbertostring(J, buf, self->u.number));
return;
}
if (radix < 2 || radix > 36)
js_rangeerror(J, "invalid radix");
/* lame number to string conversion for any radix from 2 to 36 */
{
static const char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz";
double number = self->u.number;
int sign = self->u.number < 0;
js_Buffer *sb = NULL;
uint64_t u, limit = ((uint64_t)1<<52);
int ndigits, exp, point;
if (number == 0) { js_pushstring(J, "0"); return; }
if (isnan(number)) { js_pushstring(J, "NaN"); return; }
if (isinf(number)) { js_pushstring(J, sign ? "-Infinity" : "Infinity"); return; }
if (sign)
number = -number;
/* fit as many digits as we want in an int */
exp = 0;
while (number * pow(radix, exp) > limit)
--exp;
while (number * pow(radix, exp+1) < limit)
++exp;
u = number * pow(radix, exp) + 0.5;
/* trim trailing zeros */
while (u > 0 && (u % radix) == 0) {
u /= radix;
--exp;
}
/* serialize digits */
ndigits = 0;
while (u > 0) {
buf[ndigits++] = digits[u % radix];
u /= radix;
}
point = ndigits - exp;
if (js_try(J)) {
js_free(J, sb);
js_throw(J);
}
if (sign)
js_putc(J, &sb, '-');
if (point <= 0) {
js_putc(J, &sb, '0');
js_putc(J, &sb, '.');
while (point++ < 0)
js_putc(J, &sb, '0');
while (ndigits-- > 0)
js_putc(J, &sb, buf[ndigits]);
} else {
while (ndigits-- > 0) {
js_putc(J, &sb, buf[ndigits]);
if (--point == 0 && ndigits > 0)
js_putc(J, &sb, '.');
}
while (point-- > 0)
js_putc(J, &sb, '0');
}
js_putc(J, &sb, 0);
js_pushstring(J, sb->s);
js_endtry(J);
js_free(J, sb);
}
}
| 169,703 |
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 M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M_fs_file_mode_t mode, M_fs_progress_cb_t cb, M_fs_progress_flags_t progress_flags, M_fs_progress_t *progress, const M_fs_perms_t *perms)
{
M_fs_file_t *fd_old;
M_fs_file_t *fd_new;
M_fs_info_t *info = NULL;
unsigned char temp[M_FS_BUF_SIZE];
size_t read_len;
size_t wrote_len;
size_t wrote_total = 0;
size_t offset;
M_fs_error_t res;
/* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it
* to new file. */
if (M_fs_perms_can_access(path_new, M_FS_PERMS_MODE_NONE) == M_FS_ERROR_SUCCESS) {
/* Try to delete the file since we'll be overwrite it. This is so when we create the file we create it without
* any permissions and to ensure that anything that has the file already open won't be able to read the new
* contents we're writing to the file or be able to change the perms. There is an unavoidable race condition
* between deleting and creating the file where someone could create the file and have access. However,
* depending on the OS they may have access even if the file is created with no perms... */
res = M_fs_delete(path_new, M_FALSE, NULL, M_FS_PROGRESS_NOEXTRA);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
}
/* Open the old file */
res = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
if (perms == NULL && mode & M_FS_FILE_MODE_PRESERVE_PERMS) {
res = M_fs_info_file(&info, fd_old, M_FS_PATH_INFO_FLAGS_NONE);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_file_close(fd_old);
return res;
}
perms = M_fs_info_get_perms(info);
}
res = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms);
M_fs_info_destroy(info);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_file_close(fd_old);
return res;
}
/* Copy the contents of old into new. */
while ((res = M_fs_file_read(fd_old, temp, sizeof(temp), &read_len, M_FS_FILE_RW_NORMAL)) == M_FS_ERROR_SUCCESS && read_len != 0) {
offset = 0;
while (offset < read_len) {
res = M_fs_file_write(fd_new, temp+offset, read_len-offset, &wrote_len, M_FS_FILE_RW_NORMAL);
offset += wrote_len;
wrote_total += wrote_len;
if (cb) {
M_fs_progress_set_result(progress, res);
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total_progess(progress, M_fs_progress_get_size_total_progess(progress)+wrote_len);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current_progress(progress, wrote_total);
}
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1);
}
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
M_fs_file_close(fd_old);
M_fs_file_close(fd_new);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
return M_FS_ERROR_SUCCESS;
}
Commit Message: fs: Don't try to delete the file when copying. It could cause a security issue if the file exists and doesn't allow other's to read/write. delete could allow someone to create the file and have access to the data.
CWE ID: CWE-732 | static M_fs_error_t M_fs_copy_file(const char *path_old, const char *path_new, M_fs_file_mode_t mode, M_fs_progress_cb_t cb, M_fs_progress_flags_t progress_flags, M_fs_progress_t *progress, const M_fs_perms_t *perms)
{
M_fs_file_t *fd_old;
M_fs_file_t *fd_new;
M_fs_info_t *info = NULL;
unsigned char temp[M_FS_BUF_SIZE];
size_t read_len;
size_t wrote_len;
size_t wrote_total = 0;
size_t offset;
M_fs_error_t res;
/* Open the old file */
res = M_fs_file_open(&fd_old, path_old, M_FS_BUF_SIZE, M_FS_FILE_MODE_READ|M_FS_FILE_MODE_NOCREATE, NULL);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
if (perms == NULL && mode & M_FS_FILE_MODE_PRESERVE_PERMS) {
res = M_fs_info_file(&info, fd_old, M_FS_PATH_INFO_FLAGS_NONE);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_file_close(fd_old);
return res;
}
perms = M_fs_info_get_perms(info);
}
/* We're going to create/open/truncate the new file, then as we read the contents from the old file we'll write it
* to new file. */
res = M_fs_file_open(&fd_new, path_new, M_FS_BUF_SIZE, M_FS_FILE_MODE_WRITE|M_FS_FILE_MODE_OVERWRITE, perms);
M_fs_info_destroy(info);
if (res != M_FS_ERROR_SUCCESS) {
M_fs_file_close(fd_old);
return res;
}
/* Copy the contents of old into new. */
while ((res = M_fs_file_read(fd_old, temp, sizeof(temp), &read_len, M_FS_FILE_RW_NORMAL)) == M_FS_ERROR_SUCCESS && read_len != 0) {
offset = 0;
while (offset < read_len) {
res = M_fs_file_write(fd_new, temp+offset, read_len-offset, &wrote_len, M_FS_FILE_RW_NORMAL);
offset += wrote_len;
wrote_total += wrote_len;
if (cb) {
M_fs_progress_set_result(progress, res);
if (progress_flags & M_FS_PROGRESS_SIZE_TOTAL) {
M_fs_progress_set_size_total_progess(progress, M_fs_progress_get_size_total_progess(progress)+wrote_len);
}
if (progress_flags & M_FS_PROGRESS_SIZE_CUR) {
M_fs_progress_set_size_current_progress(progress, wrote_total);
}
if (progress_flags & M_FS_PROGRESS_COUNT) {
M_fs_progress_set_count(progress, M_fs_progress_get_count(progress)+1);
}
if (!cb(progress)) {
res = M_FS_ERROR_CANCELED;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
if (res != M_FS_ERROR_SUCCESS) {
break;
}
}
M_fs_file_close(fd_old);
M_fs_file_close(fd_new);
if (res != M_FS_ERROR_SUCCESS) {
return res;
}
return M_FS_ERROR_SUCCESS;
}
| 169,142 |
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: DataReductionProxyConfigServiceClient::DataReductionProxyConfigServiceClient(
const net::BackoffEntry::Policy& backoff_policy,
DataReductionProxyRequestOptions* request_options,
DataReductionProxyMutableConfigValues* config_values,
DataReductionProxyConfig* config,
DataReductionProxyIOData* io_data,
network::NetworkConnectionTracker* network_connection_tracker,
ConfigStorer config_storer)
: request_options_(request_options),
config_values_(config_values),
config_(config),
io_data_(io_data),
network_connection_tracker_(network_connection_tracker),
config_storer_(config_storer),
backoff_policy_(backoff_policy),
backoff_entry_(&backoff_policy_),
config_service_url_(util::AddApiKeyToUrl(params::GetConfigServiceURL())),
enabled_(false),
remote_config_applied_(false),
#if defined(OS_ANDROID)
foreground_fetch_pending_(false),
#endif
previous_request_failed_authentication_(false),
failed_attempts_before_success_(0),
fetch_in_progress_(false),
client_config_override_used_(false) {
DCHECK(request_options);
DCHECK(config_values);
DCHECK(config);
DCHECK(io_data);
DCHECK(config_service_url_.is_valid());
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
client_config_override_ = command_line.GetSwitchValueASCII(
switches::kDataReductionProxyServerClientConfig);
thread_checker_.DetachFromThread();
}
Commit Message: Disable all DRP URL fetches when holdback is enabled
Disable secure proxy checker, warmup url fetcher
and client config fetch when the client is in DRP
(Data Reduction Proxy) holdback.
This CL does not disable pingbacks when client is in the
holdback, but the pingback code is going away soon.
Change-Id: Icbb59d814d1452123869c609e0770d1439c1db51
Bug: 984964
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1709965
Commit-Queue: Tarun Bansal <[email protected]>
Reviewed-by: Robert Ogden <[email protected]>
Cr-Commit-Position: refs/heads/master@{#679649}
CWE ID: CWE-416 | DataReductionProxyConfigServiceClient::DataReductionProxyConfigServiceClient(
const net::BackoffEntry::Policy& backoff_policy,
DataReductionProxyRequestOptions* request_options,
DataReductionProxyMutableConfigValues* config_values,
DataReductionProxyConfig* config,
DataReductionProxyIOData* io_data,
network::NetworkConnectionTracker* network_connection_tracker,
ConfigStorer config_storer)
: request_options_(request_options),
config_values_(config_values),
config_(config),
io_data_(io_data),
network_connection_tracker_(network_connection_tracker),
config_storer_(config_storer),
backoff_policy_(backoff_policy),
backoff_entry_(&backoff_policy_),
config_service_url_(util::AddApiKeyToUrl(params::GetConfigServiceURL())),
enabled_(false),
remote_config_applied_(false),
#if defined(OS_ANDROID)
foreground_fetch_pending_(false),
#endif
previous_request_failed_authentication_(false),
failed_attempts_before_success_(0),
fetch_in_progress_(false),
client_config_override_used_(false) {
DCHECK(request_options);
DCHECK(config_values);
DCHECK(config);
DCHECK(io_data);
DCHECK(config_service_url_.is_valid());
DCHECK(!params::IsIncludedInHoldbackFieldTrial());
const base::CommandLine& command_line =
*base::CommandLine::ForCurrentProcess();
client_config_override_ = command_line.GetSwitchValueASCII(
switches::kDataReductionProxyServerClientConfig);
thread_checker_.DetachFromThread();
}
| 172,419 |
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 usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
Commit Message: USB: serial: console: fix use-after-free on disconnect
A clean-up patch removing two redundant NULL-checks from the console
disconnect handler inadvertently also removed a third check. This could
lead to the struct usb_serial being prematurely freed by the console
code when a driver accepts but does not register any ports for an
interface which also lacks endpoint descriptors.
Fixes: 0e517c93dc02 ("USB: serial: console: clean up sanity checks")
Cc: stable <[email protected]> # 4.11
Reported-by: Andrey Konovalov <[email protected]>
Acked-by: Greg Kroah-Hartman <[email protected]>
Signed-off-by: Johan Hovold <[email protected]>
CWE ID: CWE-416 | void usb_serial_console_disconnect(struct usb_serial *serial)
{
if (serial->port[0] && serial->port[0] == usbcons_info.port) {
usb_serial_console_exit();
usb_serial_put(serial);
}
}
| 170,012 |
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 ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt)
{
static u32 ip6_idents_hashrnd __read_mostly;
u32 hash, id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
hash = __ipv6_addr_jhash(&rt->rt6i_dst.addr, ip6_idents_hashrnd);
hash = __ipv6_addr_jhash(&rt->rt6i_src.addr, hash);
id = ip_idents_reserve(hash, 1);
fhdr->identification = htonl(id);
}
Commit Message: inet: update the IP ID generation algorithm to higher standards.
Commit 355b98553789 ("netns: provide pure entropy for net_hash_mix()")
makes net_hash_mix() return a true 32 bits of entropy. When used in the
IP ID generation algorithm, this has the effect of extending the IP ID
generation key from 32 bits to 64 bits.
However, net_hash_mix() is only used for IP ID generation starting with
kernel version 4.1. Therefore, earlier kernels remain with 32-bit key
no matter what the net_hash_mix() return value is.
This change addresses the issue by explicitly extending the key to 64
bits for kernels older than 4.1.
Signed-off-by: Amit Klein <[email protected]>
Cc: Ben Hutchings <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: CWE-200 | static void ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt)
{
static u32 ip6_idents_hashrnd __read_mostly;
static u32 ip6_idents_hashrnd_extra __read_mostly;
u32 hash, id;
net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd));
net_get_random_once(&ip6_idents_hashrnd_extra, sizeof(ip6_idents_hashrnd_extra));
hash = __ipv6_addr_jhash(&rt->rt6i_dst.addr, ip6_idents_hashrnd);
hash = __ipv6_addr_jhash(&rt->rt6i_src.addr, hash);
hash = jhash_1word(hash, ip6_idents_hashrnd_extra);
id = ip_idents_reserve(hash, 1);
fhdr->identification = htonl(id);
}
| 170,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 pid_ns_release_proc(struct pid_namespace *ns)
{
mntput(ns->proc_mnt);
}
Commit Message: procfs: fix a vfsmount longterm reference leak
kern_mount() doesn't pair with plain mntput()...
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-119 | void pid_ns_release_proc(struct pid_namespace *ns)
{
kern_unmount(ns->proc_mnt);
}
| 165,614 |
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: do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
unsigned int copylen;
struct net *net = sock_net(sk);
struct netns_ipvs *ipvs = net_ipvs(net);
BUG_ON(!net);
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
return -EINVAL;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
copylen = get_arglen[GET_CMDID(cmd)];
if (copylen > 128)
return -EINVAL;
if (copy_from_user(arg, user, copylen) != 0)
return -EFAULT;
/*
* Handle daemons first since it has its own locking
*/
if (cmd == IP_VS_SO_GET_DAEMON) {
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (mutex_lock_interruptible(&ipvs->sync_mutex))
return -ERESTARTSYS;
if (ipvs->sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn,
sizeof(d[0].mcast_ifn));
d[0].syncid = ipvs->master_syncid;
}
if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn,
sizeof(d[1].mcast_ifn));
d[1].syncid = ipvs->backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
mutex_unlock(&ipvs->sync_mutex);
return ret;
}
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = ip_vs_conn_tab_size;
info.num_services = ipvs->num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(net, get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
else
svc = __ip_vs_service_find(net, AF_INET,
entry->protocol, &addr,
entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(net, get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
__ip_vs_get_timeouts(net, &t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
Commit Message: ipvs: fix info leak in getsockopt(IP_VS_SO_GET_TIMEOUT)
If at least one of CONFIG_IP_VS_PROTO_TCP or CONFIG_IP_VS_PROTO_UDP is
not set, __ip_vs_get_timeouts() does not fully initialize the structure
that gets copied to userland and that for leaks up to 12 bytes of kernel
stack. Add an explicit memset(0) before passing the structure to
__ip_vs_get_timeouts() to avoid the info leak.
Signed-off-by: Mathias Krause <[email protected]>
Cc: Wensong Zhang <[email protected]>
Cc: Simon Horman <[email protected]>
Cc: Julian Anastasov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-200 | do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
{
unsigned char arg[128];
int ret = 0;
unsigned int copylen;
struct net *net = sock_net(sk);
struct netns_ipvs *ipvs = net_ipvs(net);
BUG_ON(!net);
if (!capable(CAP_NET_ADMIN))
return -EPERM;
if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
return -EINVAL;
if (*len < get_arglen[GET_CMDID(cmd)]) {
pr_err("get_ctl: len %u < %u\n",
*len, get_arglen[GET_CMDID(cmd)]);
return -EINVAL;
}
copylen = get_arglen[GET_CMDID(cmd)];
if (copylen > 128)
return -EINVAL;
if (copy_from_user(arg, user, copylen) != 0)
return -EFAULT;
/*
* Handle daemons first since it has its own locking
*/
if (cmd == IP_VS_SO_GET_DAEMON) {
struct ip_vs_daemon_user d[2];
memset(&d, 0, sizeof(d));
if (mutex_lock_interruptible(&ipvs->sync_mutex))
return -ERESTARTSYS;
if (ipvs->sync_state & IP_VS_STATE_MASTER) {
d[0].state = IP_VS_STATE_MASTER;
strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn,
sizeof(d[0].mcast_ifn));
d[0].syncid = ipvs->master_syncid;
}
if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
d[1].state = IP_VS_STATE_BACKUP;
strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn,
sizeof(d[1].mcast_ifn));
d[1].syncid = ipvs->backup_syncid;
}
if (copy_to_user(user, &d, sizeof(d)) != 0)
ret = -EFAULT;
mutex_unlock(&ipvs->sync_mutex);
return ret;
}
if (mutex_lock_interruptible(&__ip_vs_mutex))
return -ERESTARTSYS;
switch (cmd) {
case IP_VS_SO_GET_VERSION:
{
char buf[64];
sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
ret = -EFAULT;
goto out;
}
*len = strlen(buf)+1;
}
break;
case IP_VS_SO_GET_INFO:
{
struct ip_vs_getinfo info;
info.version = IP_VS_VERSION_CODE;
info.size = ip_vs_conn_tab_size;
info.num_services = ipvs->num_services;
if (copy_to_user(user, &info, sizeof(info)) != 0)
ret = -EFAULT;
}
break;
case IP_VS_SO_GET_SERVICES:
{
struct ip_vs_get_services *get;
int size;
get = (struct ip_vs_get_services *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_service_entry) * get->num_services;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_service_entries(net, get, user);
}
break;
case IP_VS_SO_GET_SERVICE:
{
struct ip_vs_service_entry *entry;
struct ip_vs_service *svc;
union nf_inet_addr addr;
entry = (struct ip_vs_service_entry *)arg;
addr.ip = entry->addr;
if (entry->fwmark)
svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark);
else
svc = __ip_vs_service_find(net, AF_INET,
entry->protocol, &addr,
entry->port);
if (svc) {
ip_vs_copy_service(entry, svc);
if (copy_to_user(user, entry, sizeof(*entry)) != 0)
ret = -EFAULT;
} else
ret = -ESRCH;
}
break;
case IP_VS_SO_GET_DESTS:
{
struct ip_vs_get_dests *get;
int size;
get = (struct ip_vs_get_dests *)arg;
size = sizeof(*get) +
sizeof(struct ip_vs_dest_entry) * get->num_dests;
if (*len != size) {
pr_err("length: %u != %u\n", *len, size);
ret = -EINVAL;
goto out;
}
ret = __ip_vs_get_dest_entries(net, get, user);
}
break;
case IP_VS_SO_GET_TIMEOUT:
{
struct ip_vs_timeout_user t;
memset(&t, 0, sizeof(t));
__ip_vs_get_timeouts(net, &t);
if (copy_to_user(user, &t, sizeof(t)) != 0)
ret = -EFAULT;
}
break;
default:
ret = -EINVAL;
}
out:
mutex_unlock(&__ip_vs_mutex);
return ret;
}
| 166,186 |
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_terminate (MyObject *obj, GError **error)
{
g_main_loop_quit (loop);
return TRUE;
}
Commit Message:
CWE ID: CWE-264 | my_object_terminate (MyObject *obj, GError **error)
| 165,123 |
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: donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
#ifdef ELFCORE
int os_style = -1;
#endif
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return offset;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return offset;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
(FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
goto core;
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 2) {
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
(void)memcpy(desc, &nbuf[doff], sizeof(desc));
if (file_printf(ms, ", for GNU/") == -1)
return size;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return size;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return size;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return size;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return size;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return size;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return size;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return size;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return size;
*flags |= FLAGS_DID_BUILD_ID;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
xnh_type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return size;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return size;
}
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
if (descsz == 4) {
do_note_netbsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
break;
case NT_NETBSD_MARCH:
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
do_note_freebsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
if (file_printf(ms, ", for OpenBSD") == -1)
return size;
/* Content of note is always 0 */
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
if (file_printf(ms, ", for DragonFly") == -1)
return size;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
core:
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
#ifdef ELFCORE
if ((*flags & FLAGS_DID_CORE) != 0)
return size;
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return size;
*flags |= FLAGS_DID_CORE_STYLE;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
uint32_t signo;
/*
* Extract the program name. It is at
* offset 0x7c, and is up to 32-bytes,
* including the terminating NUL.
*/
if (file_printf(ms, ", from '%.31s'",
&nbuf[doff + 0x7c]) == -1)
return size;
/*
* Extract the signal number. It is at
* offset 0x08.
*/
(void)memcpy(&signo, &nbuf[doff + 0x08],
sizeof(signo));
if (file_printf(ms, " (signal %u)",
elf_getu32(swap, signo)) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
}
break;
default:
if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS ; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
tryanother:
;
}
}
break;
}
#endif
return offset;
}
Commit Message: - limit the number of program and section header number of sections to be
processed to avoid excessive processing time.
- if a bad note is found, return 0 to stop processing immediately.
CWE ID: CWE-399 | donote(struct magic_set *ms, void *vbuf, size_t offset, size_t size,
int clazz, int swap, size_t align, int *flags)
{
Elf32_Nhdr nh32;
Elf64_Nhdr nh64;
size_t noff, doff;
#ifdef ELFCORE
int os_style = -1;
#endif
uint32_t namesz, descsz;
unsigned char *nbuf = CAST(unsigned char *, vbuf);
if (xnh_sizeof + offset > size) {
/*
* We're out of note headers.
*/
return xnh_sizeof + offset;
}
(void)memcpy(xnh_addr, &nbuf[offset], xnh_sizeof);
offset += xnh_sizeof;
namesz = xnh_namesz;
descsz = xnh_descsz;
if ((namesz == 0) && (descsz == 0)) {
/*
* We're out of note headers.
*/
return (offset >= size) ? offset : size;
}
if (namesz & 0x80000000) {
(void)file_printf(ms, ", bad note name size 0x%lx",
(unsigned long)namesz);
return 0;
}
if (descsz & 0x80000000) {
(void)file_printf(ms, ", bad note description size 0x%lx",
(unsigned long)descsz);
return 0;
}
noff = offset;
doff = ELF_ALIGN(offset + namesz);
if (offset + namesz > size) {
/*
* We're past the end of the buffer.
*/
return doff;
}
offset = ELF_ALIGN(doff + descsz);
if (doff + descsz > size) {
/*
* We're past the end of the buffer.
*/
return (offset >= size) ? offset : size;
}
if ((*flags & (FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID)) ==
(FLAGS_DID_NOTE|FLAGS_DID_BUILD_ID))
goto core;
if (namesz == 5 && strcmp((char *)&nbuf[noff], "SuSE") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 2) {
file_printf(ms, ", for SuSE %d.%d", nbuf[doff], nbuf[doff + 1]);
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_VERSION && descsz == 16) {
uint32_t desc[4];
(void)memcpy(desc, &nbuf[doff], sizeof(desc));
if (file_printf(ms, ", for GNU/") == -1)
return size;
switch (elf_getu32(swap, desc[0])) {
case GNU_OS_LINUX:
if (file_printf(ms, "Linux") == -1)
return size;
break;
case GNU_OS_HURD:
if (file_printf(ms, "Hurd") == -1)
return size;
break;
case GNU_OS_SOLARIS:
if (file_printf(ms, "Solaris") == -1)
return size;
break;
case GNU_OS_KFREEBSD:
if (file_printf(ms, "kFreeBSD") == -1)
return size;
break;
case GNU_OS_KNETBSD:
if (file_printf(ms, "kNetBSD") == -1)
return size;
break;
default:
if (file_printf(ms, "<unknown>") == -1)
return size;
}
if (file_printf(ms, " %d.%d.%d", elf_getu32(swap, desc[1]),
elf_getu32(swap, desc[2]), elf_getu32(swap, desc[3])) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "GNU") == 0 &&
xnh_type == NT_GNU_BUILD_ID && (descsz == 16 || descsz == 20)) {
uint8_t desc[20];
uint32_t i;
if (file_printf(ms, ", BuildID[%s]=", descsz == 16 ? "md5/uuid" :
"sha1") == -1)
return size;
(void)memcpy(desc, &nbuf[doff], descsz);
for (i = 0; i < descsz; i++)
if (file_printf(ms, "%02x", desc[i]) == -1)
return size;
*flags |= FLAGS_DID_BUILD_ID;
}
if (namesz == 4 && strcmp((char *)&nbuf[noff], "PaX") == 0 &&
xnh_type == NT_NETBSD_PAX && descsz == 4) {
static const char *pax[] = {
"+mprotect",
"-mprotect",
"+segvguard",
"-segvguard",
"+ASLR",
"-ASLR",
};
uint32_t desc;
size_t i;
int did = 0;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (desc && file_printf(ms, ", PaX: ") == -1)
return size;
for (i = 0; i < __arraycount(pax); i++) {
if (((1 << i) & desc) == 0)
continue;
if (file_printf(ms, "%s%s", did++ ? "," : "",
pax[i]) == -1)
return size;
}
}
if (namesz == 7 && strcmp((char *)&nbuf[noff], "NetBSD") == 0) {
switch (xnh_type) {
case NT_NETBSD_VERSION:
if (descsz == 4) {
do_note_netbsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
break;
case NT_NETBSD_MARCH:
if (file_printf(ms, ", compiled for: %.*s", (int)descsz,
(const char *)&nbuf[doff]) == -1)
return size;
break;
case NT_NETBSD_CMODEL:
if (file_printf(ms, ", compiler model: %.*s",
(int)descsz, (const char *)&nbuf[doff]) == -1)
return size;
break;
default:
if (file_printf(ms, ", note=%u", xnh_type) == -1)
return size;
break;
}
return size;
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0) {
if (xnh_type == NT_FREEBSD_VERSION && descsz == 4) {
do_note_freebsd_version(ms, swap, &nbuf[doff]);
*flags |= FLAGS_DID_NOTE;
return size;
}
}
if (namesz == 8 && strcmp((char *)&nbuf[noff], "OpenBSD") == 0 &&
xnh_type == NT_OPENBSD_VERSION && descsz == 4) {
if (file_printf(ms, ", for OpenBSD") == -1)
return size;
/* Content of note is always 0 */
*flags |= FLAGS_DID_NOTE;
return size;
}
if (namesz == 10 && strcmp((char *)&nbuf[noff], "DragonFly") == 0 &&
xnh_type == NT_DRAGONFLY_VERSION && descsz == 4) {
uint32_t desc;
if (file_printf(ms, ", for DragonFly") == -1)
return size;
(void)memcpy(&desc, &nbuf[doff], sizeof(desc));
desc = elf_getu32(swap, desc);
if (file_printf(ms, " %d.%d.%d", desc / 100000,
desc / 10000 % 10, desc % 10000) == -1)
return size;
*flags |= FLAGS_DID_NOTE;
return size;
}
core:
/*
* Sigh. The 2.0.36 kernel in Debian 2.1, at
* least, doesn't correctly implement name
* sections, in core dumps, as specified by
* the "Program Linking" section of "UNIX(R) System
* V Release 4 Programmer's Guide: ANSI C and
* Programming Support Tools", because my copy
* clearly says "The first 'namesz' bytes in 'name'
* contain a *null-terminated* [emphasis mine]
* character representation of the entry's owner
* or originator", but the 2.0.36 kernel code
* doesn't include the terminating null in the
* name....
*/
if ((namesz == 4 && strncmp((char *)&nbuf[noff], "CORE", 4) == 0) ||
(namesz == 5 && strcmp((char *)&nbuf[noff], "CORE") == 0)) {
os_style = OS_STYLE_SVR4;
}
if ((namesz == 8 && strcmp((char *)&nbuf[noff], "FreeBSD") == 0)) {
os_style = OS_STYLE_FREEBSD;
}
if ((namesz >= 11 && strncmp((char *)&nbuf[noff], "NetBSD-CORE", 11)
== 0)) {
os_style = OS_STYLE_NETBSD;
}
#ifdef ELFCORE
if ((*flags & FLAGS_DID_CORE) != 0)
return size;
if (os_style != -1 && (*flags & FLAGS_DID_CORE_STYLE) == 0) {
if (file_printf(ms, ", %s-style", os_style_names[os_style])
== -1)
return size;
*flags |= FLAGS_DID_CORE_STYLE;
}
switch (os_style) {
case OS_STYLE_NETBSD:
if (xnh_type == NT_NETBSD_CORE_PROCINFO) {
uint32_t signo;
/*
* Extract the program name. It is at
* offset 0x7c, and is up to 32-bytes,
* including the terminating NUL.
*/
if (file_printf(ms, ", from '%.31s'",
&nbuf[doff + 0x7c]) == -1)
return size;
/*
* Extract the signal number. It is at
* offset 0x08.
*/
(void)memcpy(&signo, &nbuf[doff + 0x08],
sizeof(signo));
if (file_printf(ms, " (signal %u)",
elf_getu32(swap, signo)) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
}
break;
default:
if (xnh_type == NT_PRPSINFO && *flags & FLAGS_IS_CORE) {
size_t i, j;
unsigned char c;
/*
* Extract the program name. We assume
* it to be 16 characters (that's what it
* is in SunOS 5.x and Linux).
*
* Unfortunately, it's at a different offset
* in various OSes, so try multiple offsets.
* If the characters aren't all printable,
* reject it.
*/
for (i = 0; i < NOFFSETS; i++) {
unsigned char *cname, *cp;
size_t reloffset = prpsoffsets(i);
size_t noffset = doff + reloffset;
size_t k;
for (j = 0; j < 16; j++, noffset++,
reloffset++) {
/*
* Make sure we're not past
* the end of the buffer; if
* we are, just give up.
*/
if (noffset >= size)
goto tryanother;
/*
* Make sure we're not past
* the end of the contents;
* if we are, this obviously
* isn't the right offset.
*/
if (reloffset >= descsz)
goto tryanother;
c = nbuf[noffset];
if (c == '\0') {
/*
* A '\0' at the
* beginning is
* obviously wrong.
* Any other '\0'
* means we're done.
*/
if (j == 0)
goto tryanother;
else
break;
} else {
/*
* A nonprintable
* character is also
* wrong.
*/
if (!isprint(c) || isquote(c))
goto tryanother;
}
}
/*
* Well, that worked.
*/
/*
* Try next offsets, in case this match is
* in the middle of a string.
*/
for (k = i + 1 ; k < NOFFSETS ; k++) {
size_t no;
int adjust = 1;
if (prpsoffsets(k) >= prpsoffsets(i))
continue;
for (no = doff + prpsoffsets(k);
no < doff + prpsoffsets(i); no++)
adjust = adjust
&& isprint(nbuf[no]);
if (adjust)
i = k;
}
cname = (unsigned char *)
&nbuf[doff + prpsoffsets(i)];
for (cp = cname; *cp && isprint(*cp); cp++)
continue;
/*
* Linux apparently appends a space at the end
* of the command line: remove it.
*/
while (cp > cname && isspace(cp[-1]))
cp--;
if (file_printf(ms, ", from '%.*s'",
(int)(cp - cname), cname) == -1)
return size;
*flags |= FLAGS_DID_CORE;
return size;
tryanother:
;
}
}
break;
}
#endif
return offset;
}
| 169,903 |
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 VirtualAuthenticator::AddRegistration(
blink::test::mojom::RegisteredKeyPtr registration,
AddRegistrationCallback callback) {
if (registration->application_parameter.size() != device::kRpIdHashLength) {
std::move(callback).Run(false);
return;
}
bool success = false;
std::tie(std::ignore, success) = state_->registrations.emplace(
std::move(registration->key_handle),
::device::VirtualFidoDevice::RegistrationData(
crypto::ECPrivateKey::CreateFromPrivateKeyInfo(
registration->private_key),
registration->application_parameter, registration->counter));
std::move(callback).Run(success);
}
Commit Message: [base] Make dynamic container to static span conversion explicit
This change disallows implicit conversions from dynamic containers to
static spans. This conversion can cause CHECK failures, and thus should
be done carefully. Requiring explicit construction makes it more obvious
when this happens. To aid usability, appropriate base::make_span<size_t>
overloads are added.
Bug: 877931
Change-Id: Id9f526bc57bfd30a52d14df827b0445ca087381d
Reviewed-on: https://chromium-review.googlesource.com/1189985
Reviewed-by: Ryan Sleevi <[email protected]>
Reviewed-by: Balazs Engedy <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Commit-Queue: Jan Wilken Dörrie <[email protected]>
Cr-Commit-Position: refs/heads/master@{#586657}
CWE ID: CWE-22 | void VirtualAuthenticator::AddRegistration(
blink::test::mojom::RegisteredKeyPtr registration,
AddRegistrationCallback callback) {
if (registration->application_parameter.size() != device::kRpIdHashLength) {
std::move(callback).Run(false);
return;
}
bool success = false;
std::tie(std::ignore, success) = state_->registrations.emplace(
std::move(registration->key_handle),
::device::VirtualFidoDevice::RegistrationData(
crypto::ECPrivateKey::CreateFromPrivateKeyInfo(
registration->private_key),
base::make_span<device::kRpIdHashLength>(
registration->application_parameter),
registration->counter));
std::move(callback).Run(success);
}
| 172,273 |
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: juniper_parse_header(netdissect_options *ndo,
const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
const struct juniper_cookie_table_t *lp = juniper_cookie_table;
u_int idx, jnx_ext_len, jnx_header_len = 0;
uint8_t tlv_type,tlv_len;
uint32_t control_word;
int tlv_value;
const u_char *tptr;
l2info->header_len = 0;
l2info->cookie_len = 0;
l2info->proto = 0;
l2info->length = h->len;
l2info->caplen = h->caplen;
ND_TCHECK2(p[0], 4);
l2info->flags = p[3];
l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;
if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
ND_PRINT((ndo, "no magic-number found!"));
return 0;
}
if (ndo->ndo_eflag) /* print direction */
ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));
/* magic number + flags */
jnx_header_len = 4;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
bittok2str(jnx_flag_values, "none", l2info->flags)));
/* extensions present ? - calculate how much bytes to skip */
if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {
tptr = p+jnx_header_len;
/* ok to read extension length ? */
ND_TCHECK2(tptr[0], 2);
jnx_ext_len = EXTRACT_16BITS(tptr);
jnx_header_len += 2;
tptr +=2;
/* nail up the total length -
* just in case something goes wrong
* with TLV parsing */
jnx_header_len += jnx_ext_len;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));
ND_TCHECK2(tptr[0], jnx_ext_len);
while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
tlv_type = *(tptr++);
tlv_len = *(tptr++);
tlv_value = 0;
/* sanity checks */
if (tlv_type == 0 || tlv_len == 0)
break;
if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
goto trunc;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ",
tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
tlv_type,
tlv_len));
tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
switch (tlv_type) {
case JUNIPER_EXT_TLV_IFD_NAME:
/* FIXME */
break;
case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifmt_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_ENCAPS:
case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifle_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
case JUNIPER_EXT_TLV_IFL_UNIT:
case JUNIPER_EXT_TLV_IFD_IDX:
default:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%u", tlv_value));
}
break;
}
tptr+=tlv_len;
jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
}
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
}
if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "no-L2-hdr, "));
/* there is no link-layer present -
* perform the v4/v6 heuristics
* to figure out what it is
*/
ND_TCHECK2(p[jnx_header_len + 4], 1);
if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
l2info->length - (jnx_header_len + 4)) == 0)
ND_PRINT((ndo, "no IP-hdr found!"));
l2info->header_len=jnx_header_len+4;
return 0; /* stop parsing the output further */
}
l2info->header_len = jnx_header_len;
p+=l2info->header_len;
l2info->length -= l2info->header_len;
l2info->caplen -= l2info->header_len;
/* search through the cookie table and copy values matching for our PIC type */
ND_TCHECK(p[0]);
while (lp->s != NULL) {
if (lp->pictype == l2info->pictype) {
l2info->cookie_len += lp->cookie_len;
switch (p[0]) {
case LS_COOKIE_ID:
l2info->cookie_type = LS_COOKIE_ID;
l2info->cookie_len += 2;
break;
case AS_COOKIE_ID:
l2info->cookie_type = AS_COOKIE_ID;
l2info->cookie_len = 8;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
#ifdef DLT_JUNIPER_MFR
/* MFR child links don't carry cookies */
if (l2info->pictype == DLT_JUNIPER_MFR &&
(p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
l2info->cookie_len = 0;
}
#endif
l2info->header_len += l2info->cookie_len;
l2info->length -= l2info->cookie_len;
l2info->caplen -= l2info->cookie_len;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s-PIC, cookie-len %u",
lp->s,
l2info->cookie_len));
if (l2info->cookie_len > 0) {
ND_TCHECK2(p[0], l2info->cookie_len);
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", cookie 0x"));
for (idx = 0; idx < l2info->cookie_len; idx++) {
l2info->cookie[idx] = p[idx]; /* copy cookie data */
if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
}
}
if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/
l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
break;
}
++lp;
}
p+=l2info->cookie_len;
/* DLT_ specific parsing */
switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
case DLT_JUNIPER_MLPPP:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MLFR
case DLT_JUNIPER_MLFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
ND_TCHECK2(p[0], 2);
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MFR
case DLT_JUNIPER_MFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
ND_TCHECK2(p[0], 2);
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_ATM2
case DLT_JUNIPER_ATM2:
ND_TCHECK2(p[0], 4);
/* ATM cell relay control word present ? */
if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
control_word = EXTRACT_32BITS(p);
/* some control word heuristics */
switch(control_word) {
case 0: /* zero control word */
case 0x08000000: /* < JUNOS 7.4 control-word */
case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
l2info->header_len += 4;
break;
default:
break;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "control-word 0x%08x ", control_word));
}
break;
#endif
#ifdef DLT_JUNIPER_GGSN
case DLT_JUNIPER_GGSN:
break;
#endif
#ifdef DLT_JUNIPER_ATM1
case DLT_JUNIPER_ATM1:
break;
#endif
#ifdef DLT_JUNIPER_PPP
case DLT_JUNIPER_PPP:
break;
#endif
#ifdef DLT_JUNIPER_CHDLC
case DLT_JUNIPER_CHDLC:
break;
#endif
#ifdef DLT_JUNIPER_ETHER
case DLT_JUNIPER_ETHER:
break;
#endif
#ifdef DLT_JUNIPER_FRELAY
case DLT_JUNIPER_FRELAY:
break;
#endif
default:
ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
break;
}
if (ndo->ndo_eflag > 1)
ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));
return 1; /* everything went ok so far. continue parsing */
trunc:
ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
return 0;
}
Commit Message: CVE-2017-13004/Juniper: Add a bounds check.
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 | juniper_parse_header(netdissect_options *ndo,
const u_char *p, const struct pcap_pkthdr *h, struct juniper_l2info_t *l2info)
{
const struct juniper_cookie_table_t *lp = juniper_cookie_table;
u_int idx, jnx_ext_len, jnx_header_len = 0;
uint8_t tlv_type,tlv_len;
uint32_t control_word;
int tlv_value;
const u_char *tptr;
l2info->header_len = 0;
l2info->cookie_len = 0;
l2info->proto = 0;
l2info->length = h->len;
l2info->caplen = h->caplen;
ND_TCHECK2(p[0], 4);
l2info->flags = p[3];
l2info->direction = p[3]&JUNIPER_BPF_PKT_IN;
if (EXTRACT_24BITS(p) != JUNIPER_MGC_NUMBER) { /* magic number found ? */
ND_PRINT((ndo, "no magic-number found!"));
return 0;
}
if (ndo->ndo_eflag) /* print direction */
ND_PRINT((ndo, "%3s ", tok2str(juniper_direction_values, "---", l2info->direction)));
/* magic number + flags */
jnx_header_len = 4;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\tJuniper PCAP Flags [%s]",
bittok2str(jnx_flag_values, "none", l2info->flags)));
/* extensions present ? - calculate how much bytes to skip */
if ((l2info->flags & JUNIPER_BPF_EXT ) == JUNIPER_BPF_EXT ) {
tptr = p+jnx_header_len;
/* ok to read extension length ? */
ND_TCHECK2(tptr[0], 2);
jnx_ext_len = EXTRACT_16BITS(tptr);
jnx_header_len += 2;
tptr +=2;
/* nail up the total length -
* just in case something goes wrong
* with TLV parsing */
jnx_header_len += jnx_ext_len;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, ", PCAP Extension(s) total length %u", jnx_ext_len));
ND_TCHECK2(tptr[0], jnx_ext_len);
while (jnx_ext_len > JUNIPER_EXT_TLV_OVERHEAD) {
tlv_type = *(tptr++);
tlv_len = *(tptr++);
tlv_value = 0;
/* sanity checks */
if (tlv_type == 0 || tlv_len == 0)
break;
if (tlv_len+JUNIPER_EXT_TLV_OVERHEAD > jnx_ext_len)
goto trunc;
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t %s Extension TLV #%u, length %u, value ",
tok2str(jnx_ext_tlv_values,"Unknown",tlv_type),
tlv_type,
tlv_len));
tlv_value = juniper_read_tlv_value(tptr, tlv_type, tlv_len);
switch (tlv_type) {
case JUNIPER_EXT_TLV_IFD_NAME:
/* FIXME */
break;
case JUNIPER_EXT_TLV_IFD_MEDIATYPE:
case JUNIPER_EXT_TLV_TTP_IFD_MEDIATYPE:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifmt_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_ENCAPS:
case JUNIPER_EXT_TLV_TTP_IFL_ENCAPS:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%s (%u)",
tok2str(juniper_ifle_values, "Unknown", tlv_value),
tlv_value));
}
break;
case JUNIPER_EXT_TLV_IFL_IDX: /* fall through */
case JUNIPER_EXT_TLV_IFL_UNIT:
case JUNIPER_EXT_TLV_IFD_IDX:
default:
if (tlv_value != -1) {
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "%u", tlv_value));
}
break;
}
tptr+=tlv_len;
jnx_ext_len -= tlv_len+JUNIPER_EXT_TLV_OVERHEAD;
}
if (ndo->ndo_vflag > 1)
ND_PRINT((ndo, "\n\t-----original packet-----\n\t"));
}
if ((l2info->flags & JUNIPER_BPF_NO_L2 ) == JUNIPER_BPF_NO_L2 ) {
if (ndo->ndo_eflag)
ND_PRINT((ndo, "no-L2-hdr, "));
/* there is no link-layer present -
* perform the v4/v6 heuristics
* to figure out what it is
*/
ND_TCHECK2(p[jnx_header_len + 4], 1);
if (ip_heuristic_guess(ndo, p + jnx_header_len + 4,
l2info->length - (jnx_header_len + 4)) == 0)
ND_PRINT((ndo, "no IP-hdr found!"));
l2info->header_len=jnx_header_len+4;
return 0; /* stop parsing the output further */
}
l2info->header_len = jnx_header_len;
p+=l2info->header_len;
l2info->length -= l2info->header_len;
l2info->caplen -= l2info->header_len;
/* search through the cookie table and copy values matching for our PIC type */
ND_TCHECK(p[0]);
while (lp->s != NULL) {
if (lp->pictype == l2info->pictype) {
l2info->cookie_len += lp->cookie_len;
switch (p[0]) {
case LS_COOKIE_ID:
l2info->cookie_type = LS_COOKIE_ID;
l2info->cookie_len += 2;
break;
case AS_COOKIE_ID:
l2info->cookie_type = AS_COOKIE_ID;
l2info->cookie_len = 8;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
#ifdef DLT_JUNIPER_MFR
/* MFR child links don't carry cookies */
if (l2info->pictype == DLT_JUNIPER_MFR &&
(p[0] & MFR_BE_MASK) == MFR_BE_MASK) {
l2info->cookie_len = 0;
}
#endif
l2info->header_len += l2info->cookie_len;
l2info->length -= l2info->cookie_len;
l2info->caplen -= l2info->cookie_len;
if (ndo->ndo_eflag)
ND_PRINT((ndo, "%s-PIC, cookie-len %u",
lp->s,
l2info->cookie_len));
if (l2info->cookie_len > 0) {
ND_TCHECK2(p[0], l2info->cookie_len);
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", cookie 0x"));
for (idx = 0; idx < l2info->cookie_len; idx++) {
l2info->cookie[idx] = p[idx]; /* copy cookie data */
if (ndo->ndo_eflag) ND_PRINT((ndo, "%02x", p[idx]));
}
}
if (ndo->ndo_eflag) ND_PRINT((ndo, ": ")); /* print demarc b/w L2/L3*/
ND_TCHECK_16BITS(p+l2info->cookie_len);
l2info->proto = EXTRACT_16BITS(p+l2info->cookie_len);
break;
}
++lp;
}
p+=l2info->cookie_len;
/* DLT_ specific parsing */
switch(l2info->pictype) {
#ifdef DLT_JUNIPER_MLPPP
case DLT_JUNIPER_MLPPP:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
l2info->bundle = l2info->cookie[1];
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MLFR
case DLT_JUNIPER_MLFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
ND_TCHECK2(p[0], 2);
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
}
break;
#endif
#ifdef DLT_JUNIPER_MFR
case DLT_JUNIPER_MFR:
switch (l2info->cookie_type) {
case LS_COOKIE_ID:
ND_TCHECK2(p[0], 2);
l2info->bundle = l2info->cookie[1];
l2info->proto = EXTRACT_16BITS(p);
l2info->header_len += 2;
l2info->length -= 2;
l2info->caplen -= 2;
break;
case AS_COOKIE_ID:
l2info->bundle = (EXTRACT_16BITS(&l2info->cookie[6])>>3)&0xfff;
l2info->proto = (l2info->cookie[5])&JUNIPER_LSQ_L3_PROTO_MASK;
break;
default:
l2info->bundle = l2info->cookie[0];
break;
}
break;
#endif
#ifdef DLT_JUNIPER_ATM2
case DLT_JUNIPER_ATM2:
ND_TCHECK2(p[0], 4);
/* ATM cell relay control word present ? */
if (l2info->cookie[7] & ATM2_PKT_TYPE_MASK) {
control_word = EXTRACT_32BITS(p);
/* some control word heuristics */
switch(control_word) {
case 0: /* zero control word */
case 0x08000000: /* < JUNOS 7.4 control-word */
case 0x08380000: /* cntl word plus cell length (56) >= JUNOS 7.4*/
l2info->header_len += 4;
break;
default:
break;
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, "control-word 0x%08x ", control_word));
}
break;
#endif
#ifdef DLT_JUNIPER_GGSN
case DLT_JUNIPER_GGSN:
break;
#endif
#ifdef DLT_JUNIPER_ATM1
case DLT_JUNIPER_ATM1:
break;
#endif
#ifdef DLT_JUNIPER_PPP
case DLT_JUNIPER_PPP:
break;
#endif
#ifdef DLT_JUNIPER_CHDLC
case DLT_JUNIPER_CHDLC:
break;
#endif
#ifdef DLT_JUNIPER_ETHER
case DLT_JUNIPER_ETHER:
break;
#endif
#ifdef DLT_JUNIPER_FRELAY
case DLT_JUNIPER_FRELAY:
break;
#endif
default:
ND_PRINT((ndo, "Unknown Juniper DLT_ type %u: ", l2info->pictype));
break;
}
if (ndo->ndo_eflag > 1)
ND_PRINT((ndo, "hlen %u, proto 0x%04x, ", l2info->header_len, l2info->proto));
return 1; /* everything went ok so far. continue parsing */
trunc:
ND_PRINT((ndo, "[|juniper_hdr], length %u", h->len));
return 0;
}
| 170,028 |
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 AcceleratedStaticBitmapImage::Transfer() {
CheckThread();
EnsureMailbox(kVerifiedSyncToken, GL_NEAREST);
detach_thread_at_next_check_ = true;
}
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 AcceleratedStaticBitmapImage::Transfer() {
DCHECK_CALLED_ON_VALID_THREAD(thread_checker_);
EnsureMailbox(kVerifiedSyncToken, GL_NEAREST);
DETACH_FROM_THREAD(thread_checker_);
}
| 172,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: static int sclp_ctl_ioctl_sccb(void __user *user_area)
{
struct sclp_ctl_sccb ctl_sccb;
struct sccb_header *sccb;
int rc;
if (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb)))
return -EFAULT;
if (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw))
return -EOPNOTSUPP;
sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sizeof(*sccb))) {
rc = -EFAULT;
goto out_free;
}
if (sccb->length > PAGE_SIZE || sccb->length < 8)
return -EINVAL;
if (copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), sccb->length)) {
rc = -EFAULT;
goto out_free;
}
rc = sclp_sync_request(ctl_sccb.cmdw, sccb);
if (rc)
goto out_free;
if (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length))
rc = -EFAULT;
out_free:
free_page((unsigned long) sccb);
return rc;
}
Commit Message: s390/sclp_ctl: fix potential information leak with /dev/sclp
The sclp_ctl_ioctl_sccb function uses two copy_from_user calls to
retrieve the sclp request from user space. The first copy_from_user
fetches the length of the request which is stored in the first two
bytes of the request. The second copy_from_user gets the complete
sclp request, but this copies the length field a second time.
A malicious user may have changed the length in the meantime.
Reported-by: Pengfei Wang <[email protected]>
Reviewed-by: Michael Holzheu <[email protected]>
Signed-off-by: Martin Schwidefsky <[email protected]>
CWE ID: CWE-362 | static int sclp_ctl_ioctl_sccb(void __user *user_area)
{
struct sclp_ctl_sccb ctl_sccb;
struct sccb_header *sccb;
unsigned long copied;
int rc;
if (copy_from_user(&ctl_sccb, user_area, sizeof(ctl_sccb)))
return -EFAULT;
if (!sclp_ctl_cmdw_supported(ctl_sccb.cmdw))
return -EOPNOTSUPP;
sccb = (void *) get_zeroed_page(GFP_KERNEL | GFP_DMA);
if (!sccb)
return -ENOMEM;
copied = PAGE_SIZE -
copy_from_user(sccb, u64_to_uptr(ctl_sccb.sccb), PAGE_SIZE);
if (offsetof(struct sccb_header, length) +
sizeof(sccb->length) > copied || sccb->length > copied) {
rc = -EFAULT;
goto out_free;
}
if (sccb->length < 8) {
rc = -EINVAL;
goto out_free;
}
rc = sclp_sync_request(ctl_sccb.cmdw, sccb);
if (rc)
goto out_free;
if (copy_to_user(u64_to_uptr(ctl_sccb.sccb), sccb, sccb->length))
rc = -EFAULT;
out_free:
free_page((unsigned long) sccb);
return rc;
}
| 167,020 |
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 load_script(struct linux_binprm *bprm)
{
const char *i_arg, *i_name;
char *cp;
struct file *file;
char interp[BINPRM_BUF_SIZE];
int retval;
if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))
return -ENOEXEC;
/*
* This section does the #! interpretation.
* Sorta complicated, but hopefully it will work. -TYT
*/
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
bprm->buf[BINPRM_BUF_SIZE - 1] = '\0';
if ((cp = strchr(bprm->buf, '\n')) == NULL)
cp = bprm->buf+BINPRM_BUF_SIZE-1;
*cp = '\0';
while (cp > bprm->buf) {
cp--;
if ((*cp == ' ') || (*cp == '\t'))
*cp = '\0';
else
break;
}
for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++);
if (*cp == '\0')
return -ENOEXEC; /* No interpreter name found */
i_name = cp;
i_arg = NULL;
for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++)
/* nothing */ ;
while ((*cp == ' ') || (*cp == '\t'))
*cp++ = '\0';
if (*cp)
i_arg = cp;
strcpy (interp, i_name);
/*
* OK, we've parsed out the interpreter name and
* (optional) argument.
* Splice in (1) the interpreter's name for argv[0]
* (2) (optional) argument to interpreter
* (3) filename of shell script (replace argv[0])
*
* This is done in reverse order, because of how the
* user environment and arguments are stored.
*/
retval = remove_arg_zero(bprm);
if (retval)
return retval;
retval = copy_strings_kernel(1, &bprm->interp, bprm);
if (retval < 0) return retval;
bprm->argc++;
if (i_arg) {
retval = copy_strings_kernel(1, &i_arg, bprm);
if (retval < 0) return retval;
bprm->argc++;
}
retval = copy_strings_kernel(1, &i_name, bprm);
if (retval) return retval;
bprm->argc++;
bprm->interp = interp;
/*
* OK, now restart the process with the interpreter's dentry.
*/
file = open_exec(interp);
if (IS_ERR(file))
return PTR_ERR(file);
bprm->file = file;
retval = prepare_binprm(bprm);
if (retval < 0)
return retval;
return search_binary_handler(bprm);
}
Commit Message: exec: do not leave bprm->interp on stack
If a series of scripts are executed, each triggering module loading via
unprintable bytes in the script header, kernel stack contents can leak
into the command line.
Normally execution of binfmt_script and binfmt_misc happens recursively.
However, when modules are enabled, and unprintable bytes exist in the
bprm->buf, execution will restart after attempting to load matching
binfmt modules. Unfortunately, the logic in binfmt_script and
binfmt_misc does not expect to get restarted. They leave bprm->interp
pointing to their local stack. This means on restart bprm->interp is
left pointing into unused stack memory which can then be copied into the
userspace argv areas.
After additional study, it seems that both recursion and restart remains
the desirable way to handle exec with scripts, misc, and modules. As
such, we need to protect the changes to interp.
This changes the logic to require allocation for any changes to the
bprm->interp. To avoid adding a new kmalloc to every exec, the default
value is left as-is. Only when passing through binfmt_script or
binfmt_misc does an allocation take place.
For a proof of concept, see DoTest.sh from:
http://www.halfdog.net/Security/2012/LinuxKernelBinfmtScriptStackDataDisclosure/
Signed-off-by: Kees Cook <[email protected]>
Cc: halfdog <[email protected]>
Cc: P J P <[email protected]>
Cc: Alexander Viro <[email protected]>
Cc: <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-200 | static int load_script(struct linux_binprm *bprm)
{
const char *i_arg, *i_name;
char *cp;
struct file *file;
char interp[BINPRM_BUF_SIZE];
int retval;
if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))
return -ENOEXEC;
/*
* This section does the #! interpretation.
* Sorta complicated, but hopefully it will work. -TYT
*/
allow_write_access(bprm->file);
fput(bprm->file);
bprm->file = NULL;
bprm->buf[BINPRM_BUF_SIZE - 1] = '\0';
if ((cp = strchr(bprm->buf, '\n')) == NULL)
cp = bprm->buf+BINPRM_BUF_SIZE-1;
*cp = '\0';
while (cp > bprm->buf) {
cp--;
if ((*cp == ' ') || (*cp == '\t'))
*cp = '\0';
else
break;
}
for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++);
if (*cp == '\0')
return -ENOEXEC; /* No interpreter name found */
i_name = cp;
i_arg = NULL;
for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++)
/* nothing */ ;
while ((*cp == ' ') || (*cp == '\t'))
*cp++ = '\0';
if (*cp)
i_arg = cp;
strcpy (interp, i_name);
/*
* OK, we've parsed out the interpreter name and
* (optional) argument.
* Splice in (1) the interpreter's name for argv[0]
* (2) (optional) argument to interpreter
* (3) filename of shell script (replace argv[0])
*
* This is done in reverse order, because of how the
* user environment and arguments are stored.
*/
retval = remove_arg_zero(bprm);
if (retval)
return retval;
retval = copy_strings_kernel(1, &bprm->interp, bprm);
if (retval < 0) return retval;
bprm->argc++;
if (i_arg) {
retval = copy_strings_kernel(1, &i_arg, bprm);
if (retval < 0) return retval;
bprm->argc++;
}
retval = copy_strings_kernel(1, &i_name, bprm);
if (retval) return retval;
bprm->argc++;
retval = bprm_change_interp(interp, bprm);
if (retval < 0)
return retval;
/*
* OK, now restart the process with the interpreter's dentry.
*/
file = open_exec(interp);
if (IS_ERR(file))
return PTR_ERR(file);
bprm->file = file;
retval = prepare_binprm(bprm);
if (retval < 0)
return retval;
return search_binary_handler(bprm);
}
| 166,198 |
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 FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) {
if (ComputeVisibleSelectionInDOMTree().IsNone())
return;
SetSelection(
SelectionInDOMTree::Builder(
GetGranularityStrategy()->UpdateExtent(contents_point, frame_))
.SetIsHandleVisible(true)
.Build(),
SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetDoNotClearStrategy(true)
.SetSetSelectionBy(SetSelectionBy::kUser)
.Build());
}
Commit Message: Move SelectionTemplate::is_handle_visible_ to FrameSelection
This patch moves |is_handle_visible_| to |FrameSelection| from |SelectionTemplate|
since handle visibility is used only for setting |FrameSelection|, hence it is
a redundant member variable of |SelectionTemplate|.
Bug: 742093
Change-Id: I3add4da3844fb40be34dcb4d4b46b5fa6fed1d7e
Reviewed-on: https://chromium-review.googlesource.com/595389
Commit-Queue: Yoshifumi Inoue <[email protected]>
Reviewed-by: Xiaocheng Hu <[email protected]>
Reviewed-by: Kent Tamura <[email protected]>
Cr-Commit-Position: refs/heads/master@{#491660}
CWE ID: CWE-119 | void FrameSelection::MoveRangeSelectionExtent(const IntPoint& contents_point) {
if (ComputeVisibleSelectionInDOMTree().IsNone())
return;
SetSelection(
SelectionInDOMTree::Builder(
GetGranularityStrategy()->UpdateExtent(contents_point, frame_))
.Build(),
SetSelectionData::Builder()
.SetShouldCloseTyping(true)
.SetShouldClearTypingStyle(true)
.SetDoNotClearStrategy(true)
.SetSetSelectionBy(SetSelectionBy::kUser)
.SetShouldShowHandle(true)
.Build());
}
| 171,758 |
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: AutocompleteLog::AutocompleteLog(
const string16& text,
bool just_deleted_text,
AutocompleteInput::Type input_type,
size_t selected_index,
SessionID::id_type tab_id,
metrics::OmniboxEventProto::PageClassification current_page_classification,
base::TimeDelta elapsed_time_since_user_first_modified_omnibox,
size_t inline_autocompleted_length,
const AutocompleteResult& result)
: text(text),
just_deleted_text(just_deleted_text),
input_type(input_type),
selected_index(selected_index),
tab_id(tab_id),
current_page_classification(current_page_classification),
elapsed_time_since_user_first_modified_omnibox(
elapsed_time_since_user_first_modified_omnibox),
inline_autocompleted_length(inline_autocompleted_length),
result(result) {
}
Commit Message: Adds per-provider information to omnibox UMA logs.
Adds a fairly general structure to omnibox logs that can be used to pass information (that's not per-result information) from providers to the UMA logs. Right now it's only used to pass whether the asynchronous pass of a provider has finished, but it will probably be used for other things in the future.
BUG=
TEST=
Review URL: https://chromiumcodereview.appspot.com/10380007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@137288 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | AutocompleteLog::AutocompleteLog(
const string16& text,
bool just_deleted_text,
AutocompleteInput::Type input_type,
size_t selected_index,
SessionID::id_type tab_id,
metrics::OmniboxEventProto::PageClassification current_page_classification,
base::TimeDelta elapsed_time_since_user_first_modified_omnibox,
size_t inline_autocompleted_length,
const AutocompleteResult& result)
: text(text),
just_deleted_text(just_deleted_text),
input_type(input_type),
selected_index(selected_index),
tab_id(tab_id),
current_page_classification(current_page_classification),
elapsed_time_since_user_first_modified_omnibox(
elapsed_time_since_user_first_modified_omnibox),
inline_autocompleted_length(inline_autocompleted_length),
result(result),
providers_info() {
}
| 170,757 |
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 Document::InitSecurityContext(const DocumentInit& initializer) {
DCHECK(!GetSecurityOrigin());
if (!initializer.HasSecurityContext()) {
cookie_url_ = KURL(g_empty_string);
SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque());
InitContentSecurityPolicy();
ApplyFeaturePolicy({});
return;
}
SandboxFlags sandbox_flags = initializer.GetSandboxFlags();
if (fetcher_->Archive()) {
sandbox_flags |=
kSandboxAll &
~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts);
}
EnforceSandboxFlags(sandbox_flags);
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
ContentSecurityPolicy* policy_to_inherit = nullptr;
if (IsSandboxed(kSandboxOrigin)) {
cookie_url_ = url_;
scoped_refptr<SecurityOrigin> security_origin =
SecurityOrigin::CreateUniqueOpaque();
Document* owner = initializer.OwnerDocument();
if (owner) {
if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())
security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true);
if (owner->GetSecurityOrigin()->CanLoadLocalResources())
security_origin->GrantLoadLocalResources();
policy_to_inherit = owner->GetContentSecurityPolicy();
}
SetSecurityOrigin(std::move(security_origin));
} else if (Document* owner = initializer.OwnerDocument()) {
cookie_url_ = owner->CookieURL();
SetSecurityOrigin(owner->GetMutableSecurityOrigin());
policy_to_inherit = owner->GetContentSecurityPolicy();
} else {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::Create(url_));
}
if (initializer.IsHostedInReservedIPRange()) {
SetAddressSpace(GetSecurityOrigin()->IsLocalhost()
? mojom::IPAddressSpace::kLocal
: mojom::IPAddressSpace::kPrivate);
} else if (GetSecurityOrigin()->IsLocal()) {
SetAddressSpace(mojom::IPAddressSpace::kLocal);
} else {
SetAddressSpace(mojom::IPAddressSpace::kPublic);
}
if (ImportsController()) {
SetContentSecurityPolicy(
ImportsController()->Master()->GetContentSecurityPolicy());
} else {
InitContentSecurityPolicy(nullptr, policy_to_inherit);
}
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
GetMutableSecurityOrigin()->GrantUniversalAccess();
} else if (GetSecurityOrigin()->IsLocal()) {
if (settings->GetAllowUniversalAccessFromFileURLs()) {
GetMutableSecurityOrigin()->GrantUniversalAccess();
} else if (!settings->GetAllowFileAccessFromFileURLs()) {
GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin();
}
}
}
if (GetSecurityOrigin()->IsOpaque() &&
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true);
ApplyFeaturePolicy({});
InitSecureContextState();
}
Commit Message: Inherit CSP when self-navigating to local-scheme URL
As the linked bug example shows, we should inherit CSP when we navigate
to a local-scheme URL (even if we are in a main browsing context).
Bug: 799747
Change-Id: I8413aa8e8049461ebcf0ffbf7b04c41d1340af02
Reviewed-on: https://chromium-review.googlesource.com/c/1234337
Reviewed-by: Mike West <[email protected]>
Commit-Queue: Andy Paicu <[email protected]>
Cr-Commit-Position: refs/heads/master@{#597889}
CWE ID: | void Document::InitSecurityContext(const DocumentInit& initializer) {
DCHECK(!GetSecurityOrigin());
if (!initializer.HasSecurityContext()) {
cookie_url_ = KURL(g_empty_string);
SetSecurityOrigin(SecurityOrigin::CreateUniqueOpaque());
InitContentSecurityPolicy();
ApplyFeaturePolicy({});
return;
}
SandboxFlags sandbox_flags = initializer.GetSandboxFlags();
if (fetcher_->Archive()) {
sandbox_flags |=
kSandboxAll &
~(kSandboxPopups | kSandboxPropagatesToAuxiliaryBrowsingContexts);
}
EnforceSandboxFlags(sandbox_flags);
SetInsecureRequestPolicy(initializer.GetInsecureRequestPolicy());
if (initializer.InsecureNavigationsToUpgrade()) {
for (auto to_upgrade : *initializer.InsecureNavigationsToUpgrade())
AddInsecureNavigationUpgrade(to_upgrade);
}
const ContentSecurityPolicy* policy_to_inherit = nullptr;
if (IsSandboxed(kSandboxOrigin)) {
cookie_url_ = url_;
scoped_refptr<SecurityOrigin> security_origin =
SecurityOrigin::CreateUniqueOpaque();
Document* owner = initializer.OwnerDocument();
if (owner) {
if (owner->GetSecurityOrigin()->IsPotentiallyTrustworthy())
security_origin->SetOpaqueOriginIsPotentiallyTrustworthy(true);
if (owner->GetSecurityOrigin()->CanLoadLocalResources())
security_origin->GrantLoadLocalResources();
policy_to_inherit = owner->GetContentSecurityPolicy();
}
SetSecurityOrigin(std::move(security_origin));
} else if (Document* owner = initializer.OwnerDocument()) {
cookie_url_ = owner->CookieURL();
SetSecurityOrigin(owner->GetMutableSecurityOrigin());
policy_to_inherit = owner->GetContentSecurityPolicy();
} else {
cookie_url_ = url_;
SetSecurityOrigin(SecurityOrigin::Create(url_));
}
if (initializer.IsHostedInReservedIPRange()) {
SetAddressSpace(GetSecurityOrigin()->IsLocalhost()
? mojom::IPAddressSpace::kLocal
: mojom::IPAddressSpace::kPrivate);
} else if (GetSecurityOrigin()->IsLocal()) {
SetAddressSpace(mojom::IPAddressSpace::kLocal);
} else {
SetAddressSpace(mojom::IPAddressSpace::kPublic);
}
if (ImportsController()) {
SetContentSecurityPolicy(
ImportsController()->Master()->GetContentSecurityPolicy());
} else {
InitContentSecurityPolicy(nullptr, policy_to_inherit,
initializer.PreviousDocumentCSP());
}
if (Settings* settings = initializer.GetSettings()) {
if (!settings->GetWebSecurityEnabled()) {
GetMutableSecurityOrigin()->GrantUniversalAccess();
} else if (GetSecurityOrigin()->IsLocal()) {
if (settings->GetAllowUniversalAccessFromFileURLs()) {
GetMutableSecurityOrigin()->GrantUniversalAccess();
} else if (!settings->GetAllowFileAccessFromFileURLs()) {
GetMutableSecurityOrigin()->BlockLocalAccessFromLocalOrigin();
}
}
}
if (GetSecurityOrigin()->IsOpaque() &&
SecurityOrigin::Create(url_)->IsPotentiallyTrustworthy())
GetMutableSecurityOrigin()->SetOpaqueOriginIsPotentiallyTrustworthy(true);
ApplyFeaturePolicy({});
InitSecureContextState();
}
| 172,616 |
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 IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
Commit Message: Block modifier-letter-voicing character from domain names
This character (ˬ) is easy to miss between other characters. It's one of the three characters from Spacing-Modifier-Letters block that ICU lists in its recommended set in uspoof.cpp. Two of these characters (modifier-letter-turned-comma and modifier-letter-apostrophe) are already blocked in crbug/678812.
Bug: 896717
Change-Id: I24b2b591de8cc7822cd55aa005b15676be91175e
Reviewed-on: https://chromium-review.googlesource.com/c/1303037
Commit-Queue: Mustafa Emre Acer <[email protected]>
Reviewed-by: Tommy Li <[email protected]>
Cr-Commit-Position: refs/heads/master@{#604128}
CWE ID: CWE-20 | void IDNSpoofChecker::SetAllowedUnicodeSet(UErrorCode* status) {
if (U_FAILURE(*status))
return;
const icu::UnicodeSet* recommended_set =
uspoof_getRecommendedUnicodeSet(status);
icu::UnicodeSet allowed_set;
allowed_set.addAll(*recommended_set);
const icu::UnicodeSet* inclusion_set = uspoof_getInclusionUnicodeSet(status);
allowed_set.addAll(*inclusion_set);
allowed_set.remove(0x338u);
allowed_set.remove(0x58au); // Armenian Hyphen
allowed_set.remove(0x2010u);
allowed_set.remove(0x2019u); // Right Single Quotation Mark
allowed_set.remove(0x2027u);
allowed_set.remove(0x30a0u); // Katakana-Hiragana Double Hyphen
allowed_set.remove(0x2bbu); // Modifier Letter Turned Comma
allowed_set.remove(0x2bcu); // Modifier Letter Apostrophe
// Block modifier letter voicing.
allowed_set.remove(0x2ecu);
#if defined(OS_MACOSX)
allowed_set.remove(0x0620u);
allowed_set.remove(0x0F8Cu);
allowed_set.remove(0x0F8Du);
allowed_set.remove(0x0F8Eu);
allowed_set.remove(0x0F8Fu);
#endif
allowed_set.remove(0x01CDu, 0x01DCu); // Latin Ext B; Pinyin
allowed_set.remove(0x1C80u, 0x1C8Fu); // Cyrillic Extended-C
allowed_set.remove(0x1E00u, 0x1E9Bu); // Latin Extended Additional
allowed_set.remove(0x1F00u, 0x1FFFu); // Greek Extended
allowed_set.remove(0xA640u, 0xA69Fu); // Cyrillic Extended-B
allowed_set.remove(0xA720u, 0xA7FFu); // Latin Extended-D
uspoof_setAllowedUnicodeSet(checker_, &allowed_set, status);
}
| 172,638 |
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 WebRequestPermissions::CanExtensionAccessURL(
const extensions::InfoMap* extension_info_map,
const std::string& extension_id,
const GURL& url,
bool crosses_incognito,
HostPermissionsCheck host_permissions_check) {
if (!extension_info_map)
return true;
const extensions::Extension* extension =
extension_info_map->extensions().GetByID(extension_id);
if (!extension)
return false;
if (crosses_incognito && !extension_info_map->CanCrossIncognito(extension))
return false;
switch (host_permissions_check) {
case DO_NOT_CHECK_HOST:
break;
case REQUIRE_HOST_PERMISSION:
if (!((url.SchemeIs(url::kAboutScheme) ||
extension->permissions_data()->HasHostPermission(url) ||
url.GetOrigin() == extension->url()))) {
return false;
}
break;
case REQUIRE_ALL_URLS:
if (!extension->permissions_data()->HasEffectiveAccessToAllHosts())
return false;
break;
}
return true;
}
Commit Message: Make extensions use a correct same-origin check.
GURL::GetOrigin does not do the right thing for all types of URLs.
BUG=573317
Review URL: https://codereview.chromium.org/1658913002
Cr-Commit-Position: refs/heads/master@{#373381}
CWE ID: CWE-284 | bool WebRequestPermissions::CanExtensionAccessURL(
const extensions::InfoMap* extension_info_map,
const std::string& extension_id,
const GURL& url,
bool crosses_incognito,
HostPermissionsCheck host_permissions_check) {
if (!extension_info_map)
return true;
const extensions::Extension* extension =
extension_info_map->extensions().GetByID(extension_id);
if (!extension)
return false;
if (crosses_incognito && !extension_info_map->CanCrossIncognito(extension))
return false;
switch (host_permissions_check) {
case DO_NOT_CHECK_HOST:
break;
case REQUIRE_HOST_PERMISSION:
if (!url.SchemeIs(url::kAboutScheme) &&
!extension->permissions_data()->HasHostPermission(url) &&
!url::IsSameOriginWith(url, extension->url())) {
return false;
}
break;
case REQUIRE_ALL_URLS:
if (!extension->permissions_data()->HasEffectiveAccessToAllHosts())
return false;
break;
}
return true;
}
| 172,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: static void* lookupOpenGLFunctionAddress(const char* functionName, bool* success = 0)
{
if (success && !*success)
return 0;
void* target = getProcAddress(functionName);
if (target)
return target;
String fullFunctionName(functionName);
fullFunctionName.append("ARB");
target = getProcAddress(fullFunctionName.utf8().data());
if (target)
return target;
fullFunctionName = functionName;
fullFunctionName.append("EXT");
target = getProcAddress(fullFunctionName.utf8().data());
#if defined(GL_ES_VERSION_2_0)
fullFunctionName = functionName;
fullFunctionName.append("ANGLE");
target = getProcAddress(fullFunctionName.utf8().data());
fullFunctionName = functionName;
fullFunctionName.append("APPLE");
target = getProcAddress(fullFunctionName.utf8().data());
#endif
if (!target && success)
*success = false;
return target;
}
Commit Message: OpenGLShims: fix check for ANGLE GLES2 extensions
https://bugs.webkit.org/show_bug.cgi?id=111656
Patch by Sergio Correia <[email protected]> on 2013-03-07
Reviewed by Simon Hausmann.
The check for ANGLE GLES2 extensions is currently being overriden
with checks for APPLE extensions in lookupOpenGLFunctionAddress().
No new tests. No user visible behavior changed.
* platform/graphics/OpenGLShims.cpp:
(WebCore::lookupOpenGLFunctionAddress):
git-svn-id: svn://svn.chromium.org/blink/trunk@145079 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | static void* lookupOpenGLFunctionAddress(const char* functionName, bool* success = 0)
{
if (success && !*success)
return 0;
void* target = getProcAddress(functionName);
if (target)
return target;
String fullFunctionName(functionName);
fullFunctionName.append("ARB");
target = getProcAddress(fullFunctionName.utf8().data());
if (target)
return target;
fullFunctionName = functionName;
fullFunctionName.append("EXT");
target = getProcAddress(fullFunctionName.utf8().data());
#if defined(GL_ES_VERSION_2_0)
fullFunctionName = functionName;
fullFunctionName.append("ANGLE");
target = getProcAddress(fullFunctionName.utf8().data());
if (target)
return target;
fullFunctionName = functionName;
fullFunctionName.append("APPLE");
target = getProcAddress(fullFunctionName.utf8().data());
#endif
if (!target && success)
*success = false;
return target;
}
| 170,779 |
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: logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask)
{
char *mask2, *mask_decoded, *mask_decoded2, *mask_decoded3, *mask_decoded4;
char *mask_decoded5;
const char *dir_separator;
int length;
time_t seconds;
struct tm *date_tmp;
mask2 = NULL;
mask_decoded = NULL;
mask_decoded2 = NULL;
mask_decoded3 = NULL;
mask_decoded4 = NULL;
mask_decoded5 = NULL;
dir_separator = weechat_info_get ("dir_separator", "");
if (!dir_separator)
return NULL;
/*
* we first replace directory separator (commonly '/') by \01 because
* buffer mask can contain this char, and will be replaced by replacement
* char ('_' by default)
*/
mask2 = weechat_string_replace (mask, dir_separator, "\01");
if (!mask2)
goto end;
mask_decoded = weechat_buffer_string_replace_local_var (buffer, mask2);
if (!mask_decoded)
goto end;
mask_decoded2 = weechat_string_replace (mask_decoded,
dir_separator,
weechat_config_string (logger_config_file_replacement_char));
if (!mask_decoded2)
goto end;
#ifdef __CYGWIN__
mask_decoded3 = weechat_string_replace (mask_decoded2, "\\",
weechat_config_string (logger_config_file_replacement_char));
#else
mask_decoded3 = strdup (mask_decoded2);
#endif /* __CYGWIN__ */
if (!mask_decoded3)
goto end;
/* restore directory separator */
mask_decoded4 = weechat_string_replace (mask_decoded3,
"\01", dir_separator);
if (!mask_decoded4)
goto end;
/* replace date/time specifiers in mask */
length = strlen (mask_decoded4) + 256 + 1;
mask_decoded5 = malloc (length);
if (!mask_decoded5)
goto end;
seconds = time (NULL);
date_tmp = localtime (&seconds);
mask_decoded5[0] = '\0';
strftime (mask_decoded5, length - 1, mask_decoded4, date_tmp);
/* convert to lower case? */
if (weechat_config_boolean (logger_config_file_name_lower_case))
weechat_string_tolower (mask_decoded5);
if (weechat_logger_plugin->debug)
{
weechat_printf_date_tags (NULL, 0, "no_log",
"%s: buffer = \"%s\", mask = \"%s\", "
"decoded mask = \"%s\"",
LOGGER_PLUGIN_NAME,
weechat_buffer_get_string (buffer, "name"),
mask, mask_decoded5);
}
end:
if (mask2)
free (mask2);
if (mask_decoded)
free (mask_decoded);
if (mask_decoded2)
free (mask_decoded2);
if (mask_decoded3)
free (mask_decoded3);
if (mask_decoded4)
free (mask_decoded4);
return mask_decoded5;
}
Commit Message: logger: call strftime before replacing buffer local variables
CWE ID: CWE-119 | logger_get_mask_expanded (struct t_gui_buffer *buffer, const char *mask)
{
char *mask2, *mask3, *mask4, *mask5, *mask6, *mask7;
const char *dir_separator;
int length;
time_t seconds;
struct tm *date_tmp;
mask2 = NULL;
mask3 = NULL;
mask4 = NULL;
mask5 = NULL;
mask6 = NULL;
mask7 = NULL;
dir_separator = weechat_info_get ("dir_separator", "");
if (!dir_separator)
return NULL;
/* replace date/time specifiers in mask */
length = strlen (mask) + 256 + 1;
mask2 = malloc (length);
if (!mask2)
goto end;
seconds = time (NULL);
date_tmp = localtime (&seconds);
mask2[0] = '\0';
if (strftime (mask2, length - 1, mask, date_tmp) == 0)
mask2[0] = '\0';
/*
* we first replace directory separator (commonly '/') by \01 because
* buffer mask can contain this char, and will be replaced by replacement
* char ('_' by default)
*/
mask3 = weechat_string_replace (mask2, dir_separator, "\01");
if (!mask3)
goto end;
mask4 = weechat_buffer_string_replace_local_var (buffer, mask3);
if (!mask4)
goto end;
mask5 = weechat_string_replace (mask4,
dir_separator,
weechat_config_string (logger_config_file_replacement_char));
if (!mask5)
goto end;
#ifdef __CYGWIN__
mask6 = weechat_string_replace (mask5, "\\",
weechat_config_string (logger_config_file_replacement_char));
#else
mask6 = strdup (mask5);
#endif /* __CYGWIN__ */
if (!mask6)
goto end;
/* restore directory separator */
mask7 = weechat_string_replace (mask6,
"\01", dir_separator);
if (!mask7)
goto end;
/* convert to lower case? */
if (weechat_config_boolean (logger_config_file_name_lower_case))
weechat_string_tolower (mask7);
if (weechat_logger_plugin->debug)
{
weechat_printf_date_tags (NULL, 0, "no_log",
"%s: buffer = \"%s\", mask = \"%s\", "
"decoded mask = \"%s\"",
LOGGER_PLUGIN_NAME,
weechat_buffer_get_string (buffer, "name"),
mask, mask7);
}
end:
if (mask2)
free (mask2);
if (mask3)
free (mask3);
if (mask4)
free (mask4);
if (mask5)
free (mask5);
if (mask6)
free (mask6);
return mask7;
}
| 167,745 |
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 check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
/* high 32 bits are known zero. */
regs[insn->dst_reg].var_off = tnum_cast(
regs[insn->dst_reg].var_off, 4);
__update_reg_bounds(®s[insn->dst_reg]);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
__mark_reg_known(regs + insn->dst_reg, insn->imm);
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
Commit Message: bpf: fix incorrect sign extension in check_alu_op()
Distinguish between
BPF_ALU64|BPF_MOV|BPF_K (load 32-bit immediate, sign-extended to 64-bit)
and BPF_ALU|BPF_MOV|BPF_K (load 32-bit immediate, zero-padded to 64-bit);
only perform sign extension in the first case.
Starting with v4.14, this is exploitable by unprivileged users as long as
the unprivileged_bpf_disabled sysctl isn't set.
Debian assigned CVE-2017-16995 for this issue.
v3:
- add CVE number (Ben Hutchings)
Fixes: 484611357c19 ("bpf: allow access into map value arrays")
Signed-off-by: Jann Horn <[email protected]>
Acked-by: Edward Cree <[email protected]>
Signed-off-by: Alexei Starovoitov <[email protected]>
Signed-off-by: Daniel Borkmann <[email protected]>
CWE ID: CWE-119 | static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn)
{
struct bpf_reg_state *regs = cur_regs(env);
u8 opcode = BPF_OP(insn->code);
int err;
if (opcode == BPF_END || opcode == BPF_NEG) {
if (opcode == BPF_NEG) {
if (BPF_SRC(insn->code) != 0 ||
insn->src_reg != BPF_REG_0 ||
insn->off != 0 || insn->imm != 0) {
verbose(env, "BPF_NEG uses reserved fields\n");
return -EINVAL;
}
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0 ||
(insn->imm != 16 && insn->imm != 32 && insn->imm != 64) ||
BPF_CLASS(insn->code) == BPF_ALU64) {
verbose(env, "BPF_END uses reserved fields\n");
return -EINVAL;
}
}
/* check src operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if (is_pointer_value(env, insn->dst_reg)) {
verbose(env, "R%d pointer arithmetic prohibited\n",
insn->dst_reg);
return -EACCES;
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
} else if (opcode == BPF_MOV) {
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
/* check src operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_MOV uses reserved fields\n");
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP);
if (err)
return err;
if (BPF_SRC(insn->code) == BPF_X) {
if (BPF_CLASS(insn->code) == BPF_ALU64) {
/* case: R1 = R2
* copy register state to dest reg
*/
regs[insn->dst_reg] = regs[insn->src_reg];
regs[insn->dst_reg].live |= REG_LIVE_WRITTEN;
} else {
/* R1 = (u32) R2 */
if (is_pointer_value(env, insn->src_reg)) {
verbose(env,
"R%d partial copy of pointer\n",
insn->src_reg);
return -EACCES;
}
mark_reg_unknown(env, regs, insn->dst_reg);
/* high 32 bits are known zero. */
regs[insn->dst_reg].var_off = tnum_cast(
regs[insn->dst_reg].var_off, 4);
__update_reg_bounds(®s[insn->dst_reg]);
}
} else {
/* case: R = imm
* remember the value we stored into this reg
*/
regs[insn->dst_reg].type = SCALAR_VALUE;
if (BPF_CLASS(insn->code) == BPF_ALU64) {
__mark_reg_known(regs + insn->dst_reg,
insn->imm);
} else {
__mark_reg_known(regs + insn->dst_reg,
(u32)insn->imm);
}
}
} else if (opcode > BPF_END) {
verbose(env, "invalid BPF_ALU opcode %x\n", opcode);
return -EINVAL;
} else { /* all other ALU ops: and, sub, xor, add, ... */
if (BPF_SRC(insn->code) == BPF_X) {
if (insn->imm != 0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
/* check src1 operand */
err = check_reg_arg(env, insn->src_reg, SRC_OP);
if (err)
return err;
} else {
if (insn->src_reg != BPF_REG_0 || insn->off != 0) {
verbose(env, "BPF_ALU uses reserved fields\n");
return -EINVAL;
}
}
/* check src2 operand */
err = check_reg_arg(env, insn->dst_reg, SRC_OP);
if (err)
return err;
if ((opcode == BPF_MOD || opcode == BPF_DIV) &&
BPF_SRC(insn->code) == BPF_K && insn->imm == 0) {
verbose(env, "div by zero\n");
return -EINVAL;
}
if ((opcode == BPF_LSH || opcode == BPF_RSH ||
opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) {
int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32;
if (insn->imm < 0 || insn->imm >= size) {
verbose(env, "invalid shift %d\n", insn->imm);
return -EINVAL;
}
}
/* check dest operand */
err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
if (err)
return err;
return adjust_reg_min_max_vals(env, insn);
}
return 0;
}
| 167,660 |
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 ssl_parse_certificate( ssl_context *ssl )
{
int ret;
size_t i, n;
SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->authmode == SSL_VERIFY_NONE )
{
ssl->verify_result = BADCERT_SKIP_VERIFY;
SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
ssl->state++;
return( 0 );
}
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
ssl->state++;
/*
* Check if the client sent an empty certificate
*/
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( ssl->in_msglen == 2 &&
ssl->in_msgtype == SSL_MSG_ALERT &&
ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING &&
ssl->in_msg[1] == SSL_ALERT_MSG_NO_CERT )
{
SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_OPTIONAL )
return( 0 );
else
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
}
}
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver != SSL_MINOR_VERSION_0 )
{
if( ssl->in_hslen == 7 &&
ssl->in_msgtype == SSL_MSG_HANDSHAKE &&
ssl->in_msg[0] == SSL_HS_CERTIFICATE &&
memcmp( ssl->in_msg + 4, "\0\0\0", 3 ) == 0 )
{
SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_REQUIRED )
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
else
return( 0 );
}
}
if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_msg[0] != SSL_HS_CERTIFICATE || ssl->in_hslen < 10 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
/*
* Same message structure as in ssl_write_certificate()
*/
n = ( ssl->in_msg[5] << 8 ) | ssl->in_msg[6];
if( ssl->in_msg[4] != 0 || ssl->in_hslen != 7 + n )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
if( ( ssl->session_negotiate->peer_cert = (x509_cert *) malloc(
sizeof( x509_cert ) ) ) == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
sizeof( x509_cert ) ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memset( ssl->session_negotiate->peer_cert, 0, sizeof( x509_cert ) );
i = 7;
while( i < ssl->in_hslen )
{
if( ssl->in_msg[i] != 0 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
| (unsigned int) ssl->in_msg[i + 2];
i += 3;
if( n < 128 || i + n > ssl->in_hslen )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
ret = x509parse_crt( ssl->session_negotiate->peer_cert, ssl->in_msg + i,
n );
if( ret != 0 )
{
SSL_DEBUG_RET( 1, " x509parse_crt", ret );
return( ret );
}
i += n;
}
SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
if( ssl->authmode != SSL_VERIFY_NONE )
{
if( ssl->ca_chain == NULL )
{
SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
return( POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED );
}
ret = x509parse_verify( ssl->session_negotiate->peer_cert,
ssl->ca_chain, ssl->ca_crl,
ssl->peer_cn, &ssl->verify_result,
ssl->f_vrfy, ssl->p_vrfy );
if( ret != 0 )
SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
if( ssl->authmode != SSL_VERIFY_REQUIRED )
ret = 0;
}
SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
return( ret );
}
Commit Message: ssl_parse_certificate() now calls x509parse_crt_der() directly
CWE ID: CWE-20 | int ssl_parse_certificate( ssl_context *ssl )
{
int ret;
size_t i, n;
SSL_DEBUG_MSG( 2, ( "=> parse certificate" ) );
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->authmode == SSL_VERIFY_NONE )
{
ssl->verify_result = BADCERT_SKIP_VERIFY;
SSL_DEBUG_MSG( 2, ( "<= skip parse certificate" ) );
ssl->state++;
return( 0 );
}
if( ( ret = ssl_read_record( ssl ) ) != 0 )
{
SSL_DEBUG_RET( 1, "ssl_read_record", ret );
return( ret );
}
ssl->state++;
/*
* Check if the client sent an empty certificate
*/
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver == SSL_MINOR_VERSION_0 )
{
if( ssl->in_msglen == 2 &&
ssl->in_msgtype == SSL_MSG_ALERT &&
ssl->in_msg[0] == SSL_ALERT_LEVEL_WARNING &&
ssl->in_msg[1] == SSL_ALERT_MSG_NO_CERT )
{
SSL_DEBUG_MSG( 1, ( "SSLv3 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_OPTIONAL )
return( 0 );
else
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
}
}
if( ssl->endpoint == SSL_IS_SERVER &&
ssl->minor_ver != SSL_MINOR_VERSION_0 )
{
if( ssl->in_hslen == 7 &&
ssl->in_msgtype == SSL_MSG_HANDSHAKE &&
ssl->in_msg[0] == SSL_HS_CERTIFICATE &&
memcmp( ssl->in_msg + 4, "\0\0\0", 3 ) == 0 )
{
SSL_DEBUG_MSG( 1, ( "TLSv1 client has no certificate" ) );
ssl->verify_result = BADCERT_MISSING;
if( ssl->authmode == SSL_VERIFY_REQUIRED )
return( POLARSSL_ERR_SSL_NO_CLIENT_CERTIFICATE );
else
return( 0 );
}
}
if( ssl->in_msgtype != SSL_MSG_HANDSHAKE )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_UNEXPECTED_MESSAGE );
}
if( ssl->in_msg[0] != SSL_HS_CERTIFICATE || ssl->in_hslen < 10 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
/*
* Same message structure as in ssl_write_certificate()
*/
n = ( ssl->in_msg[5] << 8 ) | ssl->in_msg[6];
if( ssl->in_msg[4] != 0 || ssl->in_hslen != 7 + n )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
if( ( ssl->session_negotiate->peer_cert = (x509_cert *) malloc(
sizeof( x509_cert ) ) ) == NULL )
{
SSL_DEBUG_MSG( 1, ( "malloc(%d bytes) failed",
sizeof( x509_cert ) ) );
return( POLARSSL_ERR_SSL_MALLOC_FAILED );
}
memset( ssl->session_negotiate->peer_cert, 0, sizeof( x509_cert ) );
i = 7;
while( i < ssl->in_hslen )
{
if( ssl->in_msg[i] != 0 )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
n = ( (unsigned int) ssl->in_msg[i + 1] << 8 )
| (unsigned int) ssl->in_msg[i + 2];
i += 3;
if( n < 128 || i + n > ssl->in_hslen )
{
SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
return( POLARSSL_ERR_SSL_BAD_HS_CERTIFICATE );
}
ret = x509parse_crt_der( ssl->session_negotiate->peer_cert,
ssl->in_msg + i, n );
if( ret != 0 )
{
SSL_DEBUG_RET( 1, " x509parse_crt", ret );
return( ret );
}
i += n;
}
SSL_DEBUG_CRT( 3, "peer certificate", ssl->session_negotiate->peer_cert );
if( ssl->authmode != SSL_VERIFY_NONE )
{
if( ssl->ca_chain == NULL )
{
SSL_DEBUG_MSG( 1, ( "got no CA chain" ) );
return( POLARSSL_ERR_SSL_CA_CHAIN_REQUIRED );
}
ret = x509parse_verify( ssl->session_negotiate->peer_cert,
ssl->ca_chain, ssl->ca_crl,
ssl->peer_cn, &ssl->verify_result,
ssl->f_vrfy, ssl->p_vrfy );
if( ret != 0 )
SSL_DEBUG_RET( 1, "x509_verify_cert", ret );
if( ssl->authmode != SSL_VERIFY_REQUIRED )
ret = 0;
}
SSL_DEBUG_MSG( 2, ( "<= parse certificate" ) );
return( ret );
}
| 165,954 |
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 SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
Commit Message:
CWE ID: CWE-189 | void SplashOutputDev::drawImage(GfxState *state, Object *ref, Stream *str,
int width, int height,
GfxImageColorMap *colorMap,
int *maskColors, GBool inlineImg) {
double *ctm;
SplashCoord mat[6];
SplashOutImageData imgData;
SplashColorMode srcMode;
SplashImageSource src;
GfxGray gray;
GfxRGB rgb;
#if SPLASH_CMYK
GfxCMYK cmyk;
#endif
Guchar pix;
int n, i;
ctm = state->getCTM();
mat[0] = ctm[0];
mat[1] = ctm[1];
mat[2] = -ctm[2];
mat[3] = -ctm[3];
mat[4] = ctm[2] + ctm[4];
mat[5] = ctm[3] + ctm[5];
imgData.imgStr = new ImageStream(str, width,
colorMap->getNumPixelComps(),
colorMap->getBits());
imgData.imgStr->reset();
imgData.colorMap = colorMap;
imgData.maskColors = maskColors;
imgData.colorMode = colorMode;
imgData.width = width;
imgData.height = height;
imgData.y = 0;
imgData.lookup = NULL;
if (colorMap->getNumPixelComps() == 1) {
n = 1 << colorMap->getBits();
switch (colorMode) {
case splashModeMono1:
case splashModeMono8:
imgData.lookup = (SplashColorPtr)gmalloc(n);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getGray(&pix, &gray);
imgData.lookup[i] = colToByte(gray);
}
break;
case splashModeRGB8:
case splashModeBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 3);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[3*i] = colToByte(rgb.r);
imgData.lookup[3*i+1] = colToByte(rgb.g);
imgData.lookup[3*i+2] = colToByte(rgb.b);
}
break;
case splashModeXBGR8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getRGB(&pix, &rgb);
imgData.lookup[4*i] = colToByte(rgb.r);
imgData.lookup[4*i+1] = colToByte(rgb.g);
imgData.lookup[4*i+2] = colToByte(rgb.b);
imgData.lookup[4*i+3] = 255;
}
break;
#if SPLASH_CMYK
case splashModeCMYK8:
imgData.lookup = (SplashColorPtr)gmallocn(n, 4);
for (i = 0; i < n; ++i) {
pix = (Guchar)i;
colorMap->getCMYK(&pix, &cmyk);
imgData.lookup[4*i] = colToByte(cmyk.c);
imgData.lookup[4*i+1] = colToByte(cmyk.m);
imgData.lookup[4*i+2] = colToByte(cmyk.y);
imgData.lookup[4*i+3] = colToByte(cmyk.k);
}
break;
#endif
break;
}
}
if (colorMode == splashModeMono1) {
srcMode = splashModeMono8;
} else {
srcMode = colorMode;
}
src = maskColors ? &alphaImageSrc : &imageSrc;
splash->drawImage(src, &imgData, srcMode, maskColors ? gTrue : gFalse,
width, height, mat);
if (inlineImg) {
while (imgData.y < height) {
imgData.imgStr->getLine();
++imgData.y;
}
}
gfree(imgData.lookup);
delete imgData.imgStr;
str->close();
}
| 164,602 |
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_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) {
ipfix_template_record_t *ipfix_template_record;
while ( size_left ) {
uint32_t id;
ipfix_template_record = (ipfix_template_record_t *)DataPtr;
size_left -= 4;
id = ntohs(ipfix_template_record->TemplateID);
if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) {
remove_all_translation_tables(exporter);
ReInitExtensionMapList(fs);
} else {
remove_translation_table(fs, exporter, id);
}
DataPtr = DataPtr + 4;
if ( size_left < 4 ) {
dbg_printf("Skip %u bytes padding\n", size_left);
size_left = 0;
}
}
} // End of Process_ipfix_template_withdraw
Commit Message: Fix potential unsigned integer underflow
CWE ID: CWE-190 | static void Process_ipfix_template_withdraw(exporter_ipfix_domain_t *exporter, void *DataPtr, uint32_t size_left, FlowSource_t *fs) {
ipfix_template_record_t *ipfix_template_record;
while ( size_left ) {
uint32_t id;
if ( size_left < 4 ) {
LogError("Process_ipfix [%u] Template withdraw size error at %s line %u" ,
exporter->info.id, __FILE__, __LINE__, strerror (errno));
size_left = 0;
continue;
}
ipfix_template_record = (ipfix_template_record_t *)DataPtr;
size_left -= 4;
id = ntohs(ipfix_template_record->TemplateID);
if ( id == IPFIX_TEMPLATE_FLOWSET_ID ) {
remove_all_translation_tables(exporter);
ReInitExtensionMapList(fs);
} else {
remove_translation_table(fs, exporter, id);
}
DataPtr = DataPtr + 4;
if ( size_left < 4 ) {
dbg_printf("Skip %u bytes padding\n", size_left);
size_left = 0;
}
}
} // End of Process_ipfix_template_withdraw
| 169,583 |
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 BROTLI_INLINE BrotliResult ProcessCommandsInternal(int safe,
BrotliState* s) {
int pos = s->pos;
int i = s->loop_counter;
BrotliResult result = BROTLI_RESULT_SUCCESS;
BrotliBitReader* br = &s->br;
if (!CheckInputAmount(safe, br, 28) || !WarmupBitReader(safe, br)) {
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
/* Jump into state machine. */
if (s->state == BROTLI_STATE_COMMAND_BEGIN) {
goto CommandBegin;
} else if (s->state == BROTLI_STATE_COMMAND_INNER) {
goto CommandInner;
} else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
goto CommandPostDecodeLiterals;
} else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
goto CommandPostWrapCopy;
} else {
return BROTLI_FAILURE();
}
CommandBegin:
if (safe) {
s->state = BROTLI_STATE_COMMAND_BEGIN;
}
if (!CheckInputAmount(safe, br, 28)) { /* 156 bits + 7 bytes */
s->state = BROTLI_STATE_COMMAND_BEGIN;
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
if (PREDICT_FALSE(s->block_length[1] == 0)) {
BROTLI_SAFE(DecodeCommandBlockSwitch(s));
goto CommandBegin;
}
/* Read the insert/copy length in the command */
BROTLI_SAFE(ReadCommand(s, br, &i));
BROTLI_LOG_UINT(i);
BROTLI_LOG_UINT(s->copy_length);
BROTLI_LOG_UINT(s->distance_code);
if (i == 0) {
goto CommandPostDecodeLiterals;
}
s->meta_block_remaining_len -= i;
CommandInner:
if (safe) {
s->state = BROTLI_STATE_COMMAND_INNER;
}
/* Read the literals in the command */
if (s->trivial_literal_context) {
uint32_t bits;
uint32_t value;
PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
do {
if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
s->state = BROTLI_STATE_COMMAND_INNER;
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
if (PREDICT_FALSE(s->block_length[0] == 0)) {
BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
}
if (!safe) {
s->ringbuffer[pos] = (uint8_t)ReadPreloadedSymbol(
s->literal_htree, br, &bits, &value);
} else {
uint32_t literal;
if (!SafeReadSymbol(s->literal_htree, br, &literal)) {
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
s->ringbuffer[pos] = (uint8_t)literal;
}
--s->block_length[0];
BROTLI_LOG_UINT(s->literal_htree_index);
BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
++pos;
if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
--i;
goto saveStateAndReturn;
}
} while (--i != 0);
} else {
uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
do {
const HuffmanCode* hc;
uint8_t context;
if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
s->state = BROTLI_STATE_COMMAND_INNER;
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
if (PREDICT_FALSE(s->block_length[0] == 0)) {
BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
}
context = s->context_lookup1[p1] | s->context_lookup2[p2];
BROTLI_LOG_UINT(context);
hc = s->literal_hgroup.htrees[s->context_map_slice[context]];
p2 = p1;
if (!safe) {
p1 = (uint8_t)ReadSymbol(hc, br);
} else {
uint32_t literal;
if (!SafeReadSymbol(hc, br, &literal)) {
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
p1 = (uint8_t)literal;
}
s->ringbuffer[pos] = p1;
--s->block_length[0];
BROTLI_LOG_UINT(s->context_map_slice[context]);
BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask);
++pos;
if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
--i;
goto saveStateAndReturn;
}
} while (--i != 0);
}
if (s->meta_block_remaining_len <= 0) {
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
}
CommandPostDecodeLiterals:
if (safe) {
s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
}
if (s->distance_code >= 0) {
--s->dist_rb_idx;
s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
goto postReadDistance; /* We already have the implicit distance */
}
/* Read distance code in the command, unless it was implicitly zero. */
if (PREDICT_FALSE(s->block_length[2] == 0)) {
BROTLI_SAFE(DecodeDistanceBlockSwitch(s));
}
BROTLI_SAFE(ReadDistance(s, br));
postReadDistance:
BROTLI_LOG_UINT(s->distance_code);
if (s->max_distance != s->max_backward_distance) {
if (pos < s->max_backward_distance_minus_custom_dict_size) {
s->max_distance = pos + s->custom_dict_size;
} else {
s->max_distance = s->max_backward_distance;
}
}
i = s->copy_length;
/* Apply copy of LZ77 back-reference, or static dictionary reference if
the distance is larger than the max LZ77 distance */
if (s->distance_code > s->max_distance) {
if (i >= kBrotliMinDictionaryWordLength &&
i <= kBrotliMaxDictionaryWordLength) {
int offset = kBrotliDictionaryOffsetsByLength[i];
int word_id = s->distance_code - s->max_distance - 1;
uint32_t shift = kBrotliDictionarySizeBitsByLength[i];
int mask = (int)BitMask(shift);
int word_idx = word_id & mask;
int transform_idx = word_id >> shift;
offset += word_idx * i;
if (transform_idx < kNumTransforms) {
const uint8_t* word = &kBrotliDictionary[offset];
int len = i;
if (transform_idx == 0) {
memcpy(&s->ringbuffer[pos], word, (size_t)len);
} else {
len = TransformDictionaryWord(
&s->ringbuffer[pos], word, len, transform_idx);
}
pos += len;
s->meta_block_remaining_len -= len;
if (pos >= s->ringbuffer_size) {
/*s->partial_pos_rb += (size_t)s->ringbuffer_size;*/
s->state = BROTLI_STATE_COMMAND_POST_WRITE_1;
goto saveStateAndReturn;
}
} else {
BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
"len: %d bytes left: %d\n",
pos, s->distance_code, i,
s->meta_block_remaining_len));
return BROTLI_FAILURE();
}
} else {
BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
"len: %d bytes left: %d\n", pos, s->distance_code, i,
s->meta_block_remaining_len));
return BROTLI_FAILURE();
}
} else {
const uint8_t *ringbuffer_end_minus_copy_length =
s->ringbuffer_end - i;
uint8_t* copy_src = &s->ringbuffer[
(pos - s->distance_code) & s->ringbuffer_mask];
uint8_t* copy_dst = &s->ringbuffer[pos];
/* update the recent distances cache */
s->dist_rb[s->dist_rb_idx & 3] = s->distance_code;
++s->dist_rb_idx;
s->meta_block_remaining_len -= i;
if (PREDICT_FALSE(s->meta_block_remaining_len < 0)) {
BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
"len: %d bytes left: %d\n", pos, s->distance_code, i,
s->meta_block_remaining_len));
return BROTLI_FAILURE();
}
/* There is 128+ bytes of slack in the ringbuffer allocation.
Also, we have 16 short codes, that make these 16 bytes irrelevant
in the ringbuffer. Let's copy over them as a first guess.
*/
memmove16(copy_dst, copy_src);
/* Now check if the copy extends over the ringbuffer end,
or if the copy overlaps with itself, if yes, do wrap-copy. */
if (copy_src < copy_dst) {
if (copy_dst >= ringbuffer_end_minus_copy_length) {
goto CommandPostWrapCopy;
}
if (copy_src + i > copy_dst) {
goto postSelfintersecting;
}
} else {
if (copy_src >= ringbuffer_end_minus_copy_length) {
goto CommandPostWrapCopy;
}
if (copy_dst + i > copy_src) {
goto postSelfintersecting;
}
}
pos += i;
if (i > 16) {
if (i > 32) {
memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16));
} else {
/* This branch covers about 45% cases.
Fixed size short copy allows more compiler optimizations. */
memmove16(copy_dst + 16, copy_src + 16);
}
}
}
if (s->meta_block_remaining_len <= 0) {
/* Next metablock, if any */
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
} else {
goto CommandBegin;
}
postSelfintersecting:
while (--i >= 0) {
s->ringbuffer[pos] =
s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
++pos;
}
if (s->meta_block_remaining_len <= 0) {
/* Next metablock, if any */
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
} else {
goto CommandBegin;
}
CommandPostWrapCopy:
s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY;
while (--i >= 0) {
s->ringbuffer[pos] =
s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
++pos;
if (pos == s->ringbuffer_size) {
/*s->partial_pos_rb += (size_t)s->ringbuffer_size;*/
s->state = BROTLI_STATE_COMMAND_POST_WRITE_2;
goto saveStateAndReturn;
}
}
if (s->meta_block_remaining_len <= 0) {
/* Next metablock, if any */
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
} else {
goto CommandBegin;
}
saveStateAndReturn:
s->pos = pos;
s->loop_counter = i;
return result;
}
Commit Message: Cherry pick underflow fix.
BUG=583607
Review URL: https://codereview.chromium.org/1662313002
Cr-Commit-Position: refs/heads/master@{#373736}
CWE ID: CWE-119 | static BROTLI_INLINE BrotliResult ProcessCommandsInternal(int safe,
BrotliState* s) {
int pos = s->pos;
int i = s->loop_counter;
BrotliResult result = BROTLI_RESULT_SUCCESS;
BrotliBitReader* br = &s->br;
if (!CheckInputAmount(safe, br, 28) || !WarmupBitReader(safe, br)) {
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
/* Jump into state machine. */
if (s->state == BROTLI_STATE_COMMAND_BEGIN) {
goto CommandBegin;
} else if (s->state == BROTLI_STATE_COMMAND_INNER) {
goto CommandInner;
} else if (s->state == BROTLI_STATE_COMMAND_POST_DECODE_LITERALS) {
goto CommandPostDecodeLiterals;
} else if (s->state == BROTLI_STATE_COMMAND_POST_WRAP_COPY) {
goto CommandPostWrapCopy;
} else {
return BROTLI_FAILURE();
}
CommandBegin:
if (safe) {
s->state = BROTLI_STATE_COMMAND_BEGIN;
}
if (!CheckInputAmount(safe, br, 28)) { /* 156 bits + 7 bytes */
s->state = BROTLI_STATE_COMMAND_BEGIN;
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
if (PREDICT_FALSE(s->block_length[1] == 0)) {
BROTLI_SAFE(DecodeCommandBlockSwitch(s));
goto CommandBegin;
}
/* Read the insert/copy length in the command */
BROTLI_SAFE(ReadCommand(s, br, &i));
BROTLI_LOG_UINT(i);
BROTLI_LOG_UINT(s->copy_length);
BROTLI_LOG_UINT(s->distance_code);
if (i == 0) {
goto CommandPostDecodeLiterals;
}
s->meta_block_remaining_len -= i;
CommandInner:
if (safe) {
s->state = BROTLI_STATE_COMMAND_INNER;
}
/* Read the literals in the command */
if (s->trivial_literal_context) {
uint32_t bits;
uint32_t value;
PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
do {
if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
s->state = BROTLI_STATE_COMMAND_INNER;
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
if (PREDICT_FALSE(s->block_length[0] == 0)) {
BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
PreloadSymbol(safe, s->literal_htree, br, &bits, &value);
}
if (!safe) {
s->ringbuffer[pos] = (uint8_t)ReadPreloadedSymbol(
s->literal_htree, br, &bits, &value);
} else {
uint32_t literal;
if (!SafeReadSymbol(s->literal_htree, br, &literal)) {
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
s->ringbuffer[pos] = (uint8_t)literal;
}
--s->block_length[0];
BROTLI_LOG_UINT(s->literal_htree_index);
BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos);
++pos;
if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
--i;
goto saveStateAndReturn;
}
} while (--i != 0);
} else {
uint8_t p1 = s->ringbuffer[(pos - 1) & s->ringbuffer_mask];
uint8_t p2 = s->ringbuffer[(pos - 2) & s->ringbuffer_mask];
do {
const HuffmanCode* hc;
uint8_t context;
if (!CheckInputAmount(safe, br, 28)) { /* 162 bits + 7 bytes */
s->state = BROTLI_STATE_COMMAND_INNER;
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
if (PREDICT_FALSE(s->block_length[0] == 0)) {
BROTLI_SAFE(DecodeLiteralBlockSwitch(s));
}
context = s->context_lookup1[p1] | s->context_lookup2[p2];
BROTLI_LOG_UINT(context);
hc = s->literal_hgroup.htrees[s->context_map_slice[context]];
p2 = p1;
if (!safe) {
p1 = (uint8_t)ReadSymbol(hc, br);
} else {
uint32_t literal;
if (!SafeReadSymbol(hc, br, &literal)) {
result = BROTLI_RESULT_NEEDS_MORE_INPUT;
goto saveStateAndReturn;
}
p1 = (uint8_t)literal;
}
s->ringbuffer[pos] = p1;
--s->block_length[0];
BROTLI_LOG_UINT(s->context_map_slice[context]);
BROTLI_LOG_ARRAY_INDEX(s->ringbuffer, pos & s->ringbuffer_mask);
++pos;
if (PREDICT_FALSE(pos == s->ringbuffer_size)) {
s->state = BROTLI_STATE_COMMAND_INNER_WRITE;
--i;
goto saveStateAndReturn;
}
} while (--i != 0);
}
if (s->meta_block_remaining_len <= 0) {
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
}
CommandPostDecodeLiterals:
if (safe) {
s->state = BROTLI_STATE_COMMAND_POST_DECODE_LITERALS;
}
if (s->distance_code >= 0) {
--s->dist_rb_idx;
s->distance_code = s->dist_rb[s->dist_rb_idx & 3];
goto postReadDistance; /* We already have the implicit distance */
}
/* Read distance code in the command, unless it was implicitly zero. */
if (PREDICT_FALSE(s->block_length[2] == 0)) {
BROTLI_SAFE(DecodeDistanceBlockSwitch(s));
}
BROTLI_SAFE(ReadDistance(s, br));
postReadDistance:
BROTLI_LOG_UINT(s->distance_code);
if (s->max_distance != s->max_backward_distance) {
if (pos < s->max_backward_distance_minus_custom_dict_size) {
s->max_distance = pos + s->custom_dict_size;
} else {
s->max_distance = s->max_backward_distance;
}
}
i = s->copy_length;
/* Apply copy of LZ77 back-reference, or static dictionary reference if
the distance is larger than the max LZ77 distance */
if (s->distance_code > s->max_distance) {
if (i >= kBrotliMinDictionaryWordLength &&
i <= kBrotliMaxDictionaryWordLength) {
int offset = kBrotliDictionaryOffsetsByLength[i];
int word_id = s->distance_code - s->max_distance - 1;
uint32_t shift = kBrotliDictionarySizeBitsByLength[i];
int mask = (int)BitMask(shift);
int word_idx = word_id & mask;
int transform_idx = word_id >> shift;
offset += word_idx * i;
if (transform_idx < kNumTransforms) {
const uint8_t* word = &kBrotliDictionary[offset];
int len = i;
if (transform_idx == 0) {
memcpy(&s->ringbuffer[pos], word, (size_t)len);
} else {
len = TransformDictionaryWord(
&s->ringbuffer[pos], word, len, transform_idx);
}
pos += len;
s->meta_block_remaining_len -= len;
if (pos >= s->ringbuffer_size) {
/*s->partial_pos_rb += (size_t)s->ringbuffer_size;*/
s->state = BROTLI_STATE_COMMAND_POST_WRITE_1;
goto saveStateAndReturn;
}
} else {
BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
"len: %d bytes left: %d\n",
pos, s->distance_code, i,
s->meta_block_remaining_len));
return BROTLI_FAILURE();
}
} else {
BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
"len: %d bytes left: %d\n", pos, s->distance_code, i,
s->meta_block_remaining_len));
return BROTLI_FAILURE();
}
} else {
const uint8_t *ringbuffer_end_minus_copy_length =
s->ringbuffer_end - i;
uint8_t* copy_src = &s->ringbuffer[
(pos - s->distance_code) & s->ringbuffer_mask];
uint8_t* copy_dst = &s->ringbuffer[pos];
/* Check for possible underflow and clamp the pointer to 0. */
if (PREDICT_FALSE(s->ringbuffer_end < (const uint8_t*)0 + i)) {
ringbuffer_end_minus_copy_length = 0;
}
/* update the recent distances cache */
s->dist_rb[s->dist_rb_idx & 3] = s->distance_code;
++s->dist_rb_idx;
s->meta_block_remaining_len -= i;
if (PREDICT_FALSE(s->meta_block_remaining_len < 0)) {
BROTLI_LOG(("Invalid backward reference. pos: %d distance: %d "
"len: %d bytes left: %d\n", pos, s->distance_code, i,
s->meta_block_remaining_len));
return BROTLI_FAILURE();
}
/* There is 128+ bytes of slack in the ringbuffer allocation.
Also, we have 16 short codes, that make these 16 bytes irrelevant
in the ringbuffer. Let's copy over them as a first guess.
*/
memmove16(copy_dst, copy_src);
/* Now check if the copy extends over the ringbuffer end,
or if the copy overlaps with itself, if yes, do wrap-copy. */
if (copy_src < copy_dst) {
if (copy_dst >= ringbuffer_end_minus_copy_length) {
goto CommandPostWrapCopy;
}
if (copy_src + i > copy_dst) {
goto postSelfintersecting;
}
} else {
if (copy_src >= ringbuffer_end_minus_copy_length) {
goto CommandPostWrapCopy;
}
if (copy_dst + i > copy_src) {
goto postSelfintersecting;
}
}
pos += i;
if (i > 16) {
if (i > 32) {
memcpy(copy_dst + 16, copy_src + 16, (size_t)(i - 16));
} else {
/* This branch covers about 45% cases.
Fixed size short copy allows more compiler optimizations. */
memmove16(copy_dst + 16, copy_src + 16);
}
}
}
if (s->meta_block_remaining_len <= 0) {
/* Next metablock, if any */
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
} else {
goto CommandBegin;
}
postSelfintersecting:
while (--i >= 0) {
s->ringbuffer[pos] =
s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
++pos;
}
if (s->meta_block_remaining_len <= 0) {
/* Next metablock, if any */
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
} else {
goto CommandBegin;
}
CommandPostWrapCopy:
s->state = BROTLI_STATE_COMMAND_POST_WRAP_COPY;
while (--i >= 0) {
s->ringbuffer[pos] =
s->ringbuffer[(pos - s->distance_code) & s->ringbuffer_mask];
++pos;
if (pos == s->ringbuffer_size) {
/*s->partial_pos_rb += (size_t)s->ringbuffer_size;*/
s->state = BROTLI_STATE_COMMAND_POST_WRITE_2;
goto saveStateAndReturn;
}
}
if (s->meta_block_remaining_len <= 0) {
/* Next metablock, if any */
s->state = BROTLI_STATE_METABLOCK_DONE;
goto saveStateAndReturn;
} else {
goto CommandBegin;
}
saveStateAndReturn:
s->pos = pos;
s->loop_counter = i;
return result;
}
| 172,288 |
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 CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl2", CVAR_ARCHIVE | CVAR_LATCH);
Com_sprintf(dllName, sizeof(dllName), "renderer_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_opengl2_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Malloc = CL_RefMalloc;
ri.Free = Z_Free;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_SetDescription = Cvar_SetDescription;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
#if defined __USEA3D && defined __A3D_GEOM
hA3Dg_ExportRenderGeom (ret);
#endif
Com_Printf( "-------------------------------\n");
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Cvar_Set( "cl_paused", "0" );
}
Commit Message: Don't load .pk3s as .dlls, and don't load user config files from .pk3s.
CWE ID: CWE-269 | void CL_InitRef( void ) {
refimport_t ri;
refexport_t *ret;
#ifdef USE_RENDERER_DLOPEN
GetRefAPI_t GetRefAPI;
char dllName[MAX_OSPATH];
#endif
Com_Printf( "----- Initializing Renderer ----\n" );
#ifdef USE_RENDERER_DLOPEN
cl_renderer = Cvar_Get("cl_renderer", "opengl2", CVAR_ARCHIVE | CVAR_LATCH | CVAR_PROTECTED);
Com_sprintf(dllName, sizeof(dllName), "renderer_%s_" ARCH_STRING DLL_EXT, cl_renderer->string);
if(!(rendererLib = Sys_LoadDll(dllName, qfalse)) && strcmp(cl_renderer->string, cl_renderer->resetString))
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Cvar_ForceReset("cl_renderer");
Com_sprintf(dllName, sizeof(dllName), "renderer_opengl2_" ARCH_STRING DLL_EXT);
rendererLib = Sys_LoadDll(dllName, qfalse);
}
if(!rendererLib)
{
Com_Printf("failed:\n\"%s\"\n", Sys_LibraryError());
Com_Error(ERR_FATAL, "Failed to load renderer");
}
GetRefAPI = Sys_LoadFunction(rendererLib, "GetRefAPI");
if(!GetRefAPI)
{
Com_Error(ERR_FATAL, "Can't load symbol GetRefAPI: '%s'", Sys_LibraryError());
}
#endif
ri.Cmd_AddCommand = Cmd_AddCommand;
ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
ri.Cmd_Argc = Cmd_Argc;
ri.Cmd_Argv = Cmd_Argv;
ri.Cmd_ExecuteText = Cbuf_ExecuteText;
ri.Printf = CL_RefPrintf;
ri.Error = Com_Error;
ri.Milliseconds = CL_ScaledMilliseconds;
ri.Malloc = CL_RefMalloc;
ri.Free = Z_Free;
#ifdef HUNK_DEBUG
ri.Hunk_AllocDebug = Hunk_AllocDebug;
#else
ri.Hunk_Alloc = Hunk_Alloc;
#endif
ri.Hunk_AllocateTempMemory = Hunk_AllocateTempMemory;
ri.Hunk_FreeTempMemory = Hunk_FreeTempMemory;
ri.CM_ClusterPVS = CM_ClusterPVS;
ri.CM_DrawDebugSurface = CM_DrawDebugSurface;
ri.FS_ReadFile = FS_ReadFile;
ri.FS_FreeFile = FS_FreeFile;
ri.FS_WriteFile = FS_WriteFile;
ri.FS_FreeFileList = FS_FreeFileList;
ri.FS_ListFiles = FS_ListFiles;
ri.FS_FileIsInPAK = FS_FileIsInPAK;
ri.FS_FileExists = FS_FileExists;
ri.Cvar_Get = Cvar_Get;
ri.Cvar_Set = Cvar_Set;
ri.Cvar_SetValue = Cvar_SetValue;
ri.Cvar_CheckRange = Cvar_CheckRange;
ri.Cvar_SetDescription = Cvar_SetDescription;
ri.Cvar_VariableIntegerValue = Cvar_VariableIntegerValue;
ri.CIN_UploadCinematic = CIN_UploadCinematic;
ri.CIN_PlayCinematic = CIN_PlayCinematic;
ri.CIN_RunCinematic = CIN_RunCinematic;
ri.CL_WriteAVIVideoFrame = CL_WriteAVIVideoFrame;
ri.IN_Init = IN_Init;
ri.IN_Shutdown = IN_Shutdown;
ri.IN_Restart = IN_Restart;
ri.ftol = Q_ftol;
ri.Sys_SetEnv = Sys_SetEnv;
ri.Sys_GLimpSafeInit = Sys_GLimpSafeInit;
ri.Sys_GLimpInit = Sys_GLimpInit;
ri.Sys_LowPhysicalMemory = Sys_LowPhysicalMemory;
ret = GetRefAPI( REF_API_VERSION, &ri );
#if defined __USEA3D && defined __A3D_GEOM
hA3Dg_ExportRenderGeom (ret);
#endif
Com_Printf( "-------------------------------\n");
if ( !ret ) {
Com_Error (ERR_FATAL, "Couldn't initialize refresh" );
}
re = *ret;
Cvar_Set( "cl_paused", "0" );
}
| 170,089 |
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 RenameFile(const DownloadId& id,
const FilePath& new_path,
const FilePath& unique_path,
net::Error rename_error,
RenameFileState state,
RenameFileOverwrite should_overwrite) {
MockDownloadFile* file = download_file_factory_->GetExistingFile(id);
ASSERT_TRUE(file != NULL);
EXPECT_CALL(*file, Rename(unique_path))
.Times(1)
.WillOnce(Return(rename_error));
if (rename_error != net::OK) {
EXPECT_CALL(*file, BytesSoFar())
.Times(AtLeast(1))
.WillRepeatedly(Return(byte_count_[id]));
EXPECT_CALL(*file, GetHashState())
.Times(AtLeast(1));
EXPECT_CALL(*file, GetDownloadManager())
.Times(AtLeast(1));
} else if (state == COMPLETE) {
#if defined(OS_MACOSX)
EXPECT_CALL(*file, AnnotateWithSourceInformation());
#endif
}
if (state == IN_PROGRESS) {
download_file_manager_->RenameInProgressDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
} else { // state == COMPLETE
download_file_manager_->RenameCompletingDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
}
if (rename_error != net::OK) {
EXPECT_CALL(*download_manager_,
OnDownloadInterrupted(
id.local(),
byte_count_[id],
"",
content::ConvertNetErrorToInterruptReason(
rename_error,
content::DOWNLOAD_INTERRUPT_FROM_DISK)));
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), FilePath()));
ProcessAllPendingMessages();
++error_count_[id];
} else {
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), unique_path));
ProcessAllPendingMessages();
}
}
Commit Message: Refactors to simplify rename pathway in DownloadFileManager.
This is https://chromiumcodereview.appspot.com/10668004 / r144817 (reverted
due to CrOS failure) with the completion logic moved to after the
auto-opening. The tests that test the auto-opening (for web store install)
were waiting for download completion to check install, and hence were
failing when completion was moved earlier.
Doing this right would probably require another state (OPENED).
BUG=123998
BUG-134930
[email protected]
Review URL: https://chromiumcodereview.appspot.com/10701040
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@145157 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | void RenameFile(const DownloadId& id,
const FilePath& new_path,
const FilePath& unique_path,
net::Error rename_error,
RenameFileState state,
RenameFileOverwrite should_overwrite) {
MockDownloadFile* file = download_file_factory_->GetExistingFile(id);
ASSERT_TRUE(file != NULL);
EXPECT_CALL(*file, Rename(unique_path))
.Times(1)
.WillOnce(Return(rename_error));
if (rename_error != net::OK) {
EXPECT_CALL(*file, BytesSoFar())
.Times(AtLeast(1))
.WillRepeatedly(Return(byte_count_[id]));
EXPECT_CALL(*file, GetHashState())
.Times(AtLeast(1));
EXPECT_CALL(*file, GetDownloadManager())
.Times(AtLeast(1));
}
download_file_manager_->RenameDownloadFile(
id, new_path, (should_overwrite == OVERWRITE),
base::Bind(&TestDownloadManager::OnDownloadRenamed,
download_manager_, id.local()));
if (rename_error != net::OK) {
EXPECT_CALL(*download_manager_,
OnDownloadInterrupted(
id.local(),
byte_count_[id],
"",
content::ConvertNetErrorToInterruptReason(
rename_error,
content::DOWNLOAD_INTERRUPT_FROM_DISK)));
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), FilePath()));
ProcessAllPendingMessages();
++error_count_[id];
} else {
EXPECT_CALL(*download_manager_,
OnDownloadRenamed(id.local(), unique_path));
ProcessAllPendingMessages();
}
}
| 170,881 |
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 FillRandom(uint8_t *data, int stride) {
for (int h = 0; h < height_; ++h) {
for (int w = 0; w < width_; ++w) {
data[h * stride + w] = rnd_.Rand8();
}
}
}
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 | void FillRandom(uint8_t *data, int stride) {
uint8_t *data8 = data;
#if CONFIG_VP9_HIGHBITDEPTH
uint16_t *data16 = CONVERT_TO_SHORTPTR(data);
#endif // CONFIG_VP9_HIGHBITDEPTH
for (int h = 0; h < height_; ++h) {
for (int w = 0; w < width_; ++w) {
if (!use_high_bit_depth_) {
data8[h * stride + w] = rnd_.Rand8();
#if CONFIG_VP9_HIGHBITDEPTH
} else {
data16[h * stride + w] = rnd_.Rand16() & mask_;
#endif // CONFIG_VP9_HIGHBITDEPTH
}
}
}
}
| 174,572 |
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 BluetoothDeviceChromeOS::ExpectingPasskey() const {
return !passkey_callback_.is_null();
}
Commit Message: Refactor to support default Bluetooth pairing delegate
In order to support a default pairing delegate we need to move the agent
service provider delegate implementation from BluetoothDevice to
BluetoothAdapter while retaining the existing API.
BUG=338492
TEST=device_unittests, unit_tests, browser_tests
Review URL: https://codereview.chromium.org/148293003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@252216 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | bool BluetoothDeviceChromeOS::ExpectingPasskey() const {
return pairing_context_.get() && pairing_context_->ExpectingPasskey();
}
| 171,225 |
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 SampleTable::isValid() const {
return mChunkOffsetOffset >= 0
&& mSampleToChunkOffset >= 0
&& mSampleSizeOffset >= 0
&& mTimeToSample != NULL;
}
Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release
Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d
CWE ID: CWE-20 | bool SampleTable::isValid() const {
return mChunkOffsetOffset >= 0
&& mSampleToChunkOffset >= 0
&& mSampleSizeOffset >= 0
&& !mTimeToSample.empty();
}
| 174,172 |
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 dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
DTLS1_RECORD_DATA *rdata;
while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL)
{
rdata = (DTLS1_RECORD_DATA *) item->data;
if (rdata->rbuf.buf)
{
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL)
{
rdata = (DTLS1_RECORD_DATA *) item->data;
if (rdata->rbuf.buf)
{
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
}
Commit Message: Free up s->d1->buffered_app_data.q properly.
PR#3286
CWE ID: CWE-119 | static void dtls1_clear_queues(SSL *s)
{
pitem *item = NULL;
hm_fragment *frag = NULL;
DTLS1_RECORD_DATA *rdata;
while( (item = pqueue_pop(s->d1->unprocessed_rcds.q)) != NULL)
{
rdata = (DTLS1_RECORD_DATA *) item->data;
if (rdata->rbuf.buf)
{
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while( (item = pqueue_pop(s->d1->processed_rcds.q)) != NULL)
{
rdata = (DTLS1_RECORD_DATA *) item->data;
if (rdata->rbuf.buf)
{
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
while( (item = pqueue_pop(s->d1->buffered_messages)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
while ( (item = pqueue_pop(s->d1->sent_messages)) != NULL)
{
frag = (hm_fragment *)item->data;
OPENSSL_free(frag->fragment);
OPENSSL_free(frag);
pitem_free(item);
}
while ( (item = pqueue_pop(s->d1->buffered_app_data.q)) != NULL)
{
rdata = (DTLS1_RECORD_DATA *) item->data;
if (rdata->rbuf.buf)
{
OPENSSL_free(rdata->rbuf.buf);
}
OPENSSL_free(item->data);
pitem_free(item);
}
}
| 166,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: static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
one=1;
image=AcquireImage(image_info);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=BitmapHeader1.HorzRes/470.0;
image->y_resolution=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->x_resolution=BitmapHeader2.HorzRes/470.0;
image->y_resolution=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=0;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(BImgBuff,i,image,bpp);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);;
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
Commit Message: Fixed out-of-bounds write reported in: https://github.com/ImageMagick/ImageMagick/issues/102
CWE ID: CWE-787 | static Image *ReadWPGImage(const ImageInfo *image_info,
ExceptionInfo *exception)
{
typedef struct
{
size_t FileId;
MagickOffsetType DataOffset;
unsigned int ProductType;
unsigned int FileType;
unsigned char MajorVersion;
unsigned char MinorVersion;
unsigned int EncryptKey;
unsigned int Reserved;
} WPGHeader;
typedef struct
{
unsigned char RecType;
size_t RecordLength;
} WPGRecord;
typedef struct
{
unsigned char Class;
unsigned char RecType;
size_t Extension;
size_t RecordLength;
} WPG2Record;
typedef struct
{
unsigned HorizontalUnits;
unsigned VerticalUnits;
unsigned char PosSizePrecision;
} WPG2Start;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType1;
typedef struct
{
unsigned int Width;
unsigned int Height;
unsigned char Depth;
unsigned char Compression;
} WPG2BitmapType1;
typedef struct
{
unsigned int RotAngle;
unsigned int LowLeftX;
unsigned int LowLeftY;
unsigned int UpRightX;
unsigned int UpRightY;
unsigned int Width;
unsigned int Height;
unsigned int Depth;
unsigned int HorzRes;
unsigned int VertRes;
} WPGBitmapType2;
typedef struct
{
unsigned int StartIndex;
unsigned int NumOfEntries;
} WPGColorMapRec;
/*
typedef struct {
size_t PS_unknown1;
unsigned int PS_unknown2;
unsigned int PS_unknown3;
} WPGPSl1Record;
*/
Image
*image;
unsigned int
status;
WPGHeader
Header;
WPGRecord
Rec;
WPG2Record
Rec2;
WPG2Start StartWPG;
WPGBitmapType1
BitmapHeader1;
WPG2BitmapType1
Bitmap2Header1;
WPGBitmapType2
BitmapHeader2;
WPGColorMapRec
WPG_Palette;
int
i,
bpp,
WPG2Flags;
ssize_t
ldblk;
size_t
one;
unsigned char
*BImgBuff;
tCTM CTM; /*current transform matrix*/
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickSignature);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickSignature);
one=1;
image=AcquireImage(image_info);
image->depth=8;
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
Read WPG image.
*/
Header.FileId=ReadBlobLSBLong(image);
Header.DataOffset=(MagickOffsetType) ReadBlobLSBLong(image);
Header.ProductType=ReadBlobLSBShort(image);
Header.FileType=ReadBlobLSBShort(image);
Header.MajorVersion=ReadBlobByte(image);
Header.MinorVersion=ReadBlobByte(image);
Header.EncryptKey=ReadBlobLSBShort(image);
Header.Reserved=ReadBlobLSBShort(image);
if (Header.FileId!=0x435057FF || (Header.ProductType>>8)!=0x16)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
if (Header.EncryptKey!=0)
ThrowReaderException(CoderError,"EncryptedWPGImageFileNotSupported");
image->columns = 1;
image->rows = 1;
image->colors = 0;
bpp=0;
BitmapHeader2.RotAngle=0;
switch(Header.FileType)
{
case 1: /* WPG level 1 */
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec.RecordLength;
switch(Rec.RecType)
{
case 0x0B: /* bitmap type 1 */
BitmapHeader1.Width=ReadBlobLSBShort(image);
BitmapHeader1.Height=ReadBlobLSBShort(image);
if ((BitmapHeader1.Width == 0) || (BitmapHeader1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader1.Depth=ReadBlobLSBShort(image);
BitmapHeader1.HorzRes=ReadBlobLSBShort(image);
BitmapHeader1.VertRes=ReadBlobLSBShort(image);
if(BitmapHeader1.HorzRes && BitmapHeader1.VertRes)
{
image->units=PixelsPerCentimeterResolution;
image->x_resolution=BitmapHeader1.HorzRes/470.0;
image->y_resolution=BitmapHeader1.VertRes/470.0;
}
image->columns=BitmapHeader1.Width;
image->rows=BitmapHeader1.Height;
bpp=BitmapHeader1.Depth;
goto UnpackRaster;
case 0x0E: /*Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((unsigned char)
ReadBlobByte(image));
}
break;
case 0x11: /* Start PS l1 */
if(Rec.RecordLength > 8)
image=ExtractPostscript(image,image_info,
TellBlob(image)+8, /* skip PS header in the wpg */
(ssize_t) Rec.RecordLength-8,exception);
break;
case 0x14: /* bitmap type 2 */
BitmapHeader2.RotAngle=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftX=ReadBlobLSBShort(image);
BitmapHeader2.LowLeftY=ReadBlobLSBShort(image);
BitmapHeader2.UpRightX=ReadBlobLSBShort(image);
BitmapHeader2.UpRightY=ReadBlobLSBShort(image);
BitmapHeader2.Width=ReadBlobLSBShort(image);
BitmapHeader2.Height=ReadBlobLSBShort(image);
if ((BitmapHeader2.Width == 0) || (BitmapHeader2.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
BitmapHeader2.Depth=ReadBlobLSBShort(image);
BitmapHeader2.HorzRes=ReadBlobLSBShort(image);
BitmapHeader2.VertRes=ReadBlobLSBShort(image);
image->units=PixelsPerCentimeterResolution;
image->page.width=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightX)/470.0);
image->page.height=(unsigned int)
((BitmapHeader2.LowLeftX-BitmapHeader2.UpRightY)/470.0);
image->page.x=(int) (BitmapHeader2.LowLeftX/470.0);
image->page.y=(int) (BitmapHeader2.LowLeftX/470.0);
if(BitmapHeader2.HorzRes && BitmapHeader2.VertRes)
{
image->x_resolution=BitmapHeader2.HorzRes/470.0;
image->y_resolution=BitmapHeader2.VertRes/470.0;
}
image->columns=BitmapHeader2.Width;
image->rows=BitmapHeader2.Height;
bpp=BitmapHeader2.Depth;
UnpackRaster:
if ((image->colors == 0) && (bpp != 24))
{
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
{
NoMemory:
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
}
/* printf("Load default colormap \n"); */
for (i=0; (i < (int) image->colors) && (i < 256); i++)
{
image->colormap[i].red=ScaleCharToQuantum(WPG1_Palette[i].Red);
image->colormap[i].green=ScaleCharToQuantum(WPG1_Palette[i].Green);
image->colormap[i].blue=ScaleCharToQuantum(WPG1_Palette[i].Blue);
}
}
else
{
if (bpp < 24)
if ( (image->colors < (one << bpp)) && (bpp != 24) )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
if (bpp == 1)
{
if(image->colormap[0].red==0 &&
image->colormap[0].green==0 &&
image->colormap[0].blue==0 &&
image->colormap[1].red==0 &&
image->colormap[1].green==0 &&
image->colormap[1].blue==0)
{ /* fix crippled monochrome palette */
image->colormap[1].red =
image->colormap[1].green =
image->colormap[1].blue = QuantumRange;
}
}
if(UnpackWPGRaster(image,bpp) < 0)
/* The raster cannot be unpacked */
{
DecompressionFailed:
ThrowReaderException(CoderError,"UnableToDecompressImage");
}
if(Rec.RecType==0x14 && BitmapHeader2.RotAngle!=0 && !image_info->ping)
{
/* flop command */
if(BitmapHeader2.RotAngle & 0x8000)
{
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
}
/* flip command */
if(BitmapHeader2.RotAngle & 0x2000)
{
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
}
/* rotate command */
if(BitmapHeader2.RotAngle & 0x0FFF)
{
Image
*rotate_image;
rotate_image=RotateImage(image,(BitmapHeader2.RotAngle &
0x0FFF), exception);
if (rotate_image != (Image *) NULL) {
DuplicateBlob(rotate_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,rotate_image);
}
}
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x1B: /* Postscript l2 */
if(Rec.RecordLength>0x3C)
image=ExtractPostscript(image,image_info,
TellBlob(image)+0x3C, /* skip PS l2 header in the wpg */
(ssize_t) Rec.RecordLength-0x3C,exception);
break;
}
}
break;
case 2: /* WPG level 2 */
(void) memset(CTM,0,sizeof(CTM));
StartWPG.PosSizePrecision = 0;
while(!EOFBlob(image)) /* object parser loop */
{
(void) SeekBlob(image,Header.DataOffset,SEEK_SET);
if(EOFBlob(image))
break;
Rec2.Class=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rec2.RecType=(i=ReadBlobByte(image));
if(i==EOF)
break;
Rd_WP_DWORD(image,&Rec2.Extension);
Rd_WP_DWORD(image,&Rec2.RecordLength);
if(EOFBlob(image))
break;
Header.DataOffset=TellBlob(image)+Rec2.RecordLength;
switch(Rec2.RecType)
{
case 1:
StartWPG.HorizontalUnits=ReadBlobLSBShort(image);
StartWPG.VerticalUnits=ReadBlobLSBShort(image);
StartWPG.PosSizePrecision=ReadBlobByte(image);
break;
case 0x0C: /* Color palette */
WPG_Palette.StartIndex=ReadBlobLSBShort(image);
WPG_Palette.NumOfEntries=ReadBlobLSBShort(image);
image->colors=WPG_Palette.NumOfEntries;
if (AcquireImageColormap(image,image->colors) == MagickFalse)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=WPG_Palette.StartIndex;
i < (int)WPG_Palette.NumOfEntries; i++)
{
image->colormap[i].red=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].green=ScaleCharToQuantum((char)
ReadBlobByte(image));
image->colormap[i].blue=ScaleCharToQuantum((char)
ReadBlobByte(image));
(void) ReadBlobByte(image); /*Opacity??*/
}
break;
case 0x0E:
Bitmap2Header1.Width=ReadBlobLSBShort(image);
Bitmap2Header1.Height=ReadBlobLSBShort(image);
if ((Bitmap2Header1.Width == 0) || (Bitmap2Header1.Height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
Bitmap2Header1.Depth=ReadBlobByte(image);
Bitmap2Header1.Compression=ReadBlobByte(image);
if(Bitmap2Header1.Compression > 1)
continue; /*Unknown compression method */
switch(Bitmap2Header1.Depth)
{
case 1:
bpp=1;
break;
case 2:
bpp=2;
break;
case 3:
bpp=4;
break;
case 4:
bpp=8;
break;
case 8:
bpp=24;
break;
default:
continue; /*Ignore raster with unknown depth*/
}
image->columns=Bitmap2Header1.Width;
image->rows=Bitmap2Header1.Height;
if ((image->colors == 0) && (bpp != 24))
{
size_t
one;
one=1;
image->colors=one << bpp;
if (!AcquireImageColormap(image,image->colors))
goto NoMemory;
}
else
{
if(bpp < 24)
if( image->colors<(one << bpp) && bpp!=24 )
image->colormap=(PixelPacket *) ResizeQuantumMemory(
image->colormap,(size_t) (one << bpp),
sizeof(*image->colormap));
}
switch(Bitmap2Header1.Compression)
{
case 0: /*Uncompressed raster*/
{
ldblk=(ssize_t) ((bpp*image->columns+7)/8);
BImgBuff=(unsigned char *) AcquireQuantumMemory((size_t)
ldblk,sizeof(*BImgBuff));
if (BImgBuff == (unsigned char *) NULL)
goto NoMemory;
for(i=0; i< (ssize_t) image->rows; i++)
{
(void) ReadBlob(image,ldblk,BImgBuff);
InsertRow(BImgBuff,i,image,bpp);
}
if(BImgBuff)
BImgBuff=(unsigned char *) RelinquishMagickMemory(BImgBuff);
break;
}
case 1: /*RLE for WPG2 */
{
if( UnpackWPG2Raster(image,bpp) < 0)
goto DecompressionFailed;
break;
}
}
if(CTM[0][0]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flop_image;
flop_image = FlopImage(image, exception);
if (flop_image != (Image *) NULL) {
DuplicateBlob(flop_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flop_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
Tx(0,0)=-1; Tx(1,0)=0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=1; Tx(2,1)=0;
Tx(0,2)=(WPG._2Rect.X_ur+WPG._2Rect.X_ll);
Tx(1,2)=0; Tx(2,2)=1; */
}
if(CTM[1][1]<0 && !image_info->ping)
{ /*?? RotAngle=360-RotAngle;*/
Image
*flip_image;
flip_image = FlipImage(image, exception);
if (flip_image != (Image *) NULL) {
DuplicateBlob(flip_image,image);
(void) RemoveLastImageFromList(&image);
AppendImageToList(&image,flip_image);
}
/* Try to change CTM according to Flip - I am not sure, must be checked.
float_matrix Tx(3,3);
Tx(0,0)= 1; Tx(1,0)= 0; Tx(2,0)=0;
Tx(0,1)= 0; Tx(1,1)=-1; Tx(2,1)=0;
Tx(0,2)= 0; Tx(1,2)=(WPG._2Rect.Y_ur+WPG._2Rect.Y_ll);
Tx(2,2)=1; */
}
/* Allocate next image structure. */
AcquireNextImage(image_info,image);
image->depth=8;
if (image->next == (Image *) NULL)
goto Finish;
image=SyncNextImageInList(image);
image->columns=image->rows=1;
image->colors=0;
break;
case 0x12: /* Postscript WPG2*/
i=ReadBlobLSBShort(image);
if(Rec2.RecordLength > (unsigned int) i)
image=ExtractPostscript(image,image_info,
TellBlob(image)+i, /*skip PS header in the wpg2*/
(ssize_t) (Rec2.RecordLength-i-2),exception);
break;
case 0x1B: /*bitmap rectangle*/
WPG2Flags = LoadWPG2Flags(image,StartWPG.PosSizePrecision,NULL,&CTM);
(void) WPG2Flags;
break;
}
}
break;
default:
{
ThrowReaderException(CoderError,"DataEncodingSchemeIsNotSupported");
}
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
Finish:
(void) CloseBlob(image);
{
Image
*p;
ssize_t
scene=0;
/*
Rewind list, removing any empty images while rewinding.
*/
p=image;
image=NULL;
while (p != (Image *) NULL)
{
Image *tmp=p;
if ((p->rows == 0) || (p->columns == 0)) {
p=p->previous;
DeleteImageFromList(&tmp);
} else {
image=p;
p=p->previous;
}
}
/*
Fix scene numbers.
*/
for (p=image; p != (Image *) NULL; p=p->next)
p->scene=(size_t) scene++;
}
if (image == (Image *) NULL)
ThrowReaderException(CorruptImageError,
"ImageFileDoesNotContainAnyImageData");
return(image);
}
| 170,115 |
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: HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) {
if (address < payload())
return nullptr;
if (!m_objectStartBitMapComputed)
populateObjectStartBitMap();
size_t objectOffset = address - payload();
size_t objectStartNumber = objectOffset / allocationGranularity;
size_t mapIndex = objectStartNumber / 8;
ASSERT(mapIndex < objectStartBitMapSize);
size_t bit = objectStartNumber & 7;
uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1);
while (!byte) {
ASSERT(mapIndex > 0);
byte = m_objectStartBitMap[--mapIndex];
}
int leadingZeroes = numberOfLeadingZeroes(byte);
objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes;
objectOffset = objectStartNumber * allocationGranularity;
Address objectAddress = objectOffset + payload();
HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress);
if (header->isFree())
return nullptr;
ASSERT(header->checkHeader());
return header;
}
Commit Message: Call HeapObjectHeader::checkHeader solely for its side-effect.
This requires changing its signature. This is a preliminary stage to making it
private.
BUG=633030
Review-Url: https://codereview.chromium.org/2698673003
Cr-Commit-Position: refs/heads/master@{#460489}
CWE ID: CWE-119 | HeapObjectHeader* NormalPage::findHeaderFromAddress(Address address) {
if (address < payload())
return nullptr;
if (!m_objectStartBitMapComputed)
populateObjectStartBitMap();
size_t objectOffset = address - payload();
size_t objectStartNumber = objectOffset / allocationGranularity;
size_t mapIndex = objectStartNumber / 8;
ASSERT(mapIndex < objectStartBitMapSize);
size_t bit = objectStartNumber & 7;
uint8_t byte = m_objectStartBitMap[mapIndex] & ((1 << (bit + 1)) - 1);
while (!byte) {
ASSERT(mapIndex > 0);
byte = m_objectStartBitMap[--mapIndex];
}
int leadingZeroes = numberOfLeadingZeroes(byte);
objectStartNumber = (mapIndex * 8) + 7 - leadingZeroes;
objectOffset = objectStartNumber * allocationGranularity;
Address objectAddress = objectOffset + payload();
HeapObjectHeader* header = reinterpret_cast<HeapObjectHeader*>(objectAddress);
if (header->isFree())
return nullptr;
header->checkHeader();
return header;
}
| 172,711 |
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: poly_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
POLYGON *poly;
int npts;
int size;
int isopen;
char *s;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
size = offsetof(POLYGON, p[0]) +sizeof(poly->p[0]) * npts;
poly = (POLYGON *) palloc0(size); /* zero any holes */
SET_VARSIZE(poly, size);
poly->npts = npts;
if ((!path_decode(FALSE, npts, str, &isopen, &s, &(poly->p[0])))
|| (*s != '\0'))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
make_bound_box(poly);
PG_RETURN_POLYGON_P(poly);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | poly_in(PG_FUNCTION_ARGS)
{
char *str = PG_GETARG_CSTRING(0);
POLYGON *poly;
int npts;
int size;
int base_size;
int isopen;
char *s;
if ((npts = pair_count(str, ',')) <= 0)
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
base_size = sizeof(poly->p[0]) * npts;
size = offsetof(POLYGON, p[0]) + base_size;
/* Check for integer overflow */
if (base_size / npts != sizeof(poly->p[0]) || size <= base_size)
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("too many points requested")));
poly = (POLYGON *) palloc0(size); /* zero any holes */
SET_VARSIZE(poly, size);
poly->npts = npts;
if ((!path_decode(FALSE, npts, str, &isopen, &s, &(poly->p[0])))
|| (*s != '\0'))
ereport(ERROR,
(errcode(ERRCODE_INVALID_TEXT_REPRESENTATION),
errmsg("invalid input syntax for type polygon: \"%s\"", str)));
make_bound_box(poly);
PG_RETURN_POLYGON_P(poly);
}
| 166,411 |
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: fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)
{
struct mrb_context *c = fiber_check(mrb, self);
struct mrb_context *old_c = mrb->c;
mrb_value value;
fiber_check_cfunc(mrb, c);
if (resume && c->status == MRB_FIBER_TRANSFERRED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber");
}
if (c->status == MRB_FIBER_RUNNING || c->status == MRB_FIBER_RESUMED) {
mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)");
}
if (c->status == MRB_FIBER_TERMINATED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber");
}
mrb->c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;
c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);
if (c->status == MRB_FIBER_CREATED) {
mrb_value *b, *e;
if (len >= c->stend - c->stack) {
mrb_raise(mrb, E_FIBER_ERROR, "too many arguments to fiber");
}
b = c->stack+1;
e = b + len;
while (b<e) {
*b++ = *a++;
}
c->cibase->argc = (int)len;
value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];
}
else {
value = fiber_result(mrb, a, len);
}
fiber_switch_context(mrb, c);
if (vmexec) {
c->vmexec = TRUE;
value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);
mrb->c = old_c;
}
else {
MARK_CONTEXT_MODIFY(c);
}
return value;
}
Commit Message: Extend stack when pushing arguments that does not fit in; fix #4038
CWE ID: CWE-125 | fiber_switch(mrb_state *mrb, mrb_value self, mrb_int len, const mrb_value *a, mrb_bool resume, mrb_bool vmexec)
{
struct mrb_context *c = fiber_check(mrb, self);
struct mrb_context *old_c = mrb->c;
enum mrb_fiber_state status;
mrb_value value;
fiber_check_cfunc(mrb, c);
status = c->status;
if (resume && status == MRB_FIBER_TRANSFERRED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming transferred fiber");
}
if (status == MRB_FIBER_RUNNING || status == MRB_FIBER_RESUMED) {
mrb_raise(mrb, E_FIBER_ERROR, "double resume (fib)");
}
if (status == MRB_FIBER_TERMINATED) {
mrb_raise(mrb, E_FIBER_ERROR, "resuming dead fiber");
}
old_c->status = resume ? MRB_FIBER_RESUMED : MRB_FIBER_TRANSFERRED;
c->prev = resume ? mrb->c : (c->prev ? c->prev : mrb->root_c);
fiber_switch_context(mrb, c);
if (status == MRB_FIBER_CREATED) {
mrb_value *b, *e;
mrb_stack_extend(mrb, len+2); /* for receiver and (optional) block */
b = c->stack+1;
e = b + len;
while (b<e) {
*b++ = *a++;
}
c->cibase->argc = (int)len;
value = c->stack[0] = MRB_PROC_ENV(c->ci->proc)->stack[0];
}
else {
value = fiber_result(mrb, a, len);
}
if (vmexec) {
c->vmexec = TRUE;
value = mrb_vm_exec(mrb, c->ci[-1].proc, c->ci->pc);
mrb->c = old_c;
}
else {
MARK_CONTEXT_MODIFY(c);
}
return value;
}
| 169,201 |
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 RenderProcessHostImpl::RegisterProcessHostForSite(
BrowserContext* browser_context,
RenderProcessHost* process,
const GURL& url) {
SiteProcessMap* map =
GetSiteProcessMapForBrowserContext(browser_context);
std::string site = SiteInstance::GetSiteForURL(browser_context, url)
.possibly_invalid_spec();
map->RegisterProcess(site, process);
}
Commit Message: Check for appropriate bindings in process-per-site mode.
BUG=174059
TEST=See bug for repro steps.
Review URL: https://chromiumcodereview.appspot.com/12188025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@181386 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void RenderProcessHostImpl::RegisterProcessHostForSite(
BrowserContext* browser_context,
RenderProcessHost* process,
const GURL& url) {
SiteProcessMap* map =
GetSiteProcessMapForBrowserContext(browser_context);
// Only register valid, non-empty sites. Empty or invalid sites will not
// use process-per-site mode. We cannot check whether the process has
// appropriate bindings here, because the bindings have not yet been granted.
std::string site = SiteInstance::GetSiteForURL(browser_context, url)
.possibly_invalid_spec();
if (!site.empty())
map->RegisterProcess(site, process);
}
| 171,468 |
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 impeg2d_next_code(dec_state_t *ps_dec, UWORD32 u4_start_code_val)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush_to_byte_boundary(ps_stream);
while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != u4_start_code_val)
&& (ps_dec->s_bit_stream.u4_offset <= ps_dec->s_bit_stream.u4_max_offset))
{
if (impeg2d_bit_stream_get(ps_stream,8) != 0)
{
/* Ignore stuffing bit errors. */
}
}
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 | void impeg2d_next_code(dec_state_t *ps_dec, UWORD32 u4_start_code_val)
{
stream_t *ps_stream;
ps_stream = &ps_dec->s_bit_stream;
impeg2d_bit_stream_flush_to_byte_boundary(ps_stream);
while ((impeg2d_bit_stream_nxt(ps_stream,START_CODE_LEN) != u4_start_code_val) &&
(ps_dec->s_bit_stream.u4_offset < ps_dec->s_bit_stream.u4_max_offset))
{
if (impeg2d_bit_stream_get(ps_stream,8) != 0)
{
/* Ignore stuffing bit errors. */
}
}
return;
}
| 173,950 |
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: hstore_from_arrays(PG_FUNCTION_ARGS)
{
int32 buflen;
HStore *out;
Pairs *pairs;
Datum *key_datums;
bool *key_nulls;
int key_count;
Datum *value_datums;
bool *value_nulls;
int value_count;
ArrayType *key_array;
ArrayType *value_array;
int i;
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
key_array = PG_GETARG_ARRAYTYPE_P(0);
Assert(ARR_ELEMTYPE(key_array) == TEXTOID);
/*
* must check >1 rather than != 1 because empty arrays have 0 dimensions,
* not 1
*/
if (ARR_NDIM(key_array) > 1)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
deconstruct_array(key_array,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
/* value_array might be NULL */
if (PG_ARGISNULL(1))
{
value_array = NULL;
value_count = key_count;
value_datums = NULL;
value_nulls = NULL;
}
else
{
value_array = PG_GETARG_ARRAYTYPE_P(1);
Assert(ARR_ELEMTYPE(value_array) == TEXTOID);
if (ARR_NDIM(value_array) > 1)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
if ((ARR_NDIM(key_array) > 0 || ARR_NDIM(value_array) > 0) &&
(ARR_NDIM(key_array) != ARR_NDIM(value_array) ||
ARR_DIMS(key_array)[0] != ARR_DIMS(value_array)[0] ||
ARR_LBOUND(key_array)[0] != ARR_LBOUND(value_array)[0]))
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("arrays must have same bounds")));
deconstruct_array(value_array,
TEXTOID, -1, false, 'i',
&value_datums, &value_nulls, &value_count);
Assert(key_count == value_count);
}
pairs = palloc(key_count * sizeof(Pairs));
for (i = 0; i < key_count; ++i)
{
if (key_nulls[i])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
if (!value_nulls || value_nulls[i])
{
pairs[i].key = VARDATA_ANY(key_datums[i]);
pairs[i].val = NULL;
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i]));
pairs[i].vallen = 4;
pairs[i].isnull = true;
pairs[i].needfree = false;
}
else
{
pairs[i].key = VARDATA_ANY(key_datums[i]);
pairs[i].val = VARDATA_ANY(value_datums[i]);
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i]));
pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(value_datums[i]));
pairs[i].isnull = false;
pairs[i].needfree = false;
}
}
key_count = hstoreUniquePairs(pairs, key_count, &buflen);
out = hstorePairs(pairs, key_count, buflen);
PG_RETURN_POINTER(out);
}
Commit Message: Predict integer overflow to avoid buffer overruns.
Several functions, mostly type input functions, calculated an allocation
size such that the calculation wrapped to a small positive value when
arguments implied a sufficiently-large requirement. Writes past the end
of the inadvertent small allocation followed shortly thereafter.
Coverity identified the path_in() vulnerability; code inspection led to
the rest. In passing, add check_stack_depth() to prevent stack overflow
in related functions.
Back-patch to 8.4 (all supported versions). The non-comment hstore
changes touch code that did not exist in 8.4, so that part stops at 9.0.
Noah Misch and Heikki Linnakangas, reviewed by Tom Lane.
Security: CVE-2014-0064
CWE ID: CWE-189 | hstore_from_arrays(PG_FUNCTION_ARGS)
{
int32 buflen;
HStore *out;
Pairs *pairs;
Datum *key_datums;
bool *key_nulls;
int key_count;
Datum *value_datums;
bool *value_nulls;
int value_count;
ArrayType *key_array;
ArrayType *value_array;
int i;
if (PG_ARGISNULL(0))
PG_RETURN_NULL();
key_array = PG_GETARG_ARRAYTYPE_P(0);
Assert(ARR_ELEMTYPE(key_array) == TEXTOID);
/*
* must check >1 rather than != 1 because empty arrays have 0 dimensions,
* not 1
*/
if (ARR_NDIM(key_array) > 1)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
deconstruct_array(key_array,
TEXTOID, -1, false, 'i',
&key_datums, &key_nulls, &key_count);
/* see discussion in hstoreArrayToPairs() */
if (key_count > MaxAllocSize / sizeof(Pairs))
ereport(ERROR,
(errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
errmsg("number of pairs (%d) exceeds the maximum allowed (%d)",
key_count, (int) (MaxAllocSize / sizeof(Pairs)))));
/* value_array might be NULL */
if (PG_ARGISNULL(1))
{
value_array = NULL;
value_count = key_count;
value_datums = NULL;
value_nulls = NULL;
}
else
{
value_array = PG_GETARG_ARRAYTYPE_P(1);
Assert(ARR_ELEMTYPE(value_array) == TEXTOID);
if (ARR_NDIM(value_array) > 1)
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("wrong number of array subscripts")));
if ((ARR_NDIM(key_array) > 0 || ARR_NDIM(value_array) > 0) &&
(ARR_NDIM(key_array) != ARR_NDIM(value_array) ||
ARR_DIMS(key_array)[0] != ARR_DIMS(value_array)[0] ||
ARR_LBOUND(key_array)[0] != ARR_LBOUND(value_array)[0]))
ereport(ERROR,
(errcode(ERRCODE_ARRAY_SUBSCRIPT_ERROR),
errmsg("arrays must have same bounds")));
deconstruct_array(value_array,
TEXTOID, -1, false, 'i',
&value_datums, &value_nulls, &value_count);
Assert(key_count == value_count);
}
pairs = palloc(key_count * sizeof(Pairs));
for (i = 0; i < key_count; ++i)
{
if (key_nulls[i])
ereport(ERROR,
(errcode(ERRCODE_NULL_VALUE_NOT_ALLOWED),
errmsg("null value not allowed for hstore key")));
if (!value_nulls || value_nulls[i])
{
pairs[i].key = VARDATA_ANY(key_datums[i]);
pairs[i].val = NULL;
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i]));
pairs[i].vallen = 4;
pairs[i].isnull = true;
pairs[i].needfree = false;
}
else
{
pairs[i].key = VARDATA_ANY(key_datums[i]);
pairs[i].val = VARDATA_ANY(value_datums[i]);
pairs[i].keylen = hstoreCheckKeyLen(VARSIZE_ANY_EXHDR(key_datums[i]));
pairs[i].vallen = hstoreCheckValLen(VARSIZE_ANY_EXHDR(value_datums[i]));
pairs[i].isnull = false;
pairs[i].needfree = false;
}
}
key_count = hstoreUniquePairs(pairs, key_count, &buflen);
out = hstorePairs(pairs, key_count, buflen);
PG_RETURN_POINTER(out);
}
| 166,397 |
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: ExtensionsGuestViewMessageFilter::FrameNavigationHelper::GetGuestView() const {
return MimeHandlerViewGuest::From(
parent_site_instance_->GetProcess()->GetID(), guest_instance_id_)
->As<MimeHandlerViewGuest>();
}
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 | ExtensionsGuestViewMessageFilter::FrameNavigationHelper::GetGuestView() const {
| 173,042 |
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 char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc)
{
const char *it = s;
const char *end = s + len;
if (enc == ENCQUOTEDPRINTABLE)
{
struct Buffer buf = { 0 };
for (; it < end; ++it)
{
if (*it == '_')
{
mutt_buffer_addch(&buf, ' ');
}
else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) &&
(!(it[2] & ~127) && hexval(it[2]) != -1))
{
mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2]));
it += 2;
}
else
{
mutt_buffer_addch(&buf, *it);
}
}
mutt_buffer_addch(&buf, '\0');
return buf.data;
}
else if (enc == ENCBASE64)
{
char *out = mutt_mem_malloc(3 * len / 4 + 1);
int dlen = mutt_b64_decode(out, it);
if (dlen == -1)
{
FREE(&out);
return NULL;
}
out[dlen] = '\0';
return out;
}
assert(0); /* The enc parameter has an invalid value */
return NULL;
}
Commit Message: Check outbuf length in mutt_to_base64()
The obuf can be overflowed in auth_cram.c, and possibly auth_gss.c.
Thanks to Jeriko One for the bug report.
CWE ID: CWE-119 | static char *rfc2047_decode_word(const char *s, size_t len, enum ContentEncoding enc)
{
const char *it = s;
const char *end = s + len;
if (enc == ENCQUOTEDPRINTABLE)
{
struct Buffer buf = { 0 };
for (; it < end; ++it)
{
if (*it == '_')
{
mutt_buffer_addch(&buf, ' ');
}
else if ((*it == '=') && (!(it[1] & ~127) && hexval(it[1]) != -1) &&
(!(it[2] & ~127) && hexval(it[2]) != -1))
{
mutt_buffer_addch(&buf, (hexval(it[1]) << 4) | hexval(it[2]));
it += 2;
}
else
{
mutt_buffer_addch(&buf, *it);
}
}
mutt_buffer_addch(&buf, '\0');
return buf.data;
}
else if (enc == ENCBASE64)
{
const int olen = 3 * len / 4 + 1;
char *out = mutt_mem_malloc(olen);
int dlen = mutt_b64_decode(out, it, olen);
if (dlen == -1)
{
FREE(&out);
return NULL;
}
out[dlen] = '\0';
return out;
}
assert(0); /* The enc parameter has an invalid value */
return NULL;
}
| 169,129 |
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::CreateBlock(
long long id,
long long pos, //absolute pos of payload
long long size,
long long discard_padding)
{
assert((id == 0x20) || (id == 0x23)); //BlockGroup or SimpleBlock
if (m_entries_count < 0) //haven't parsed anything yet
{
assert(m_entries == NULL);
assert(m_entries_size == 0);
m_entries_size = 1024;
m_entries = new BlockEntry*[m_entries_size];
m_entries_count = 0;
}
else
{
assert(m_entries);
assert(m_entries_size > 0);
assert(m_entries_count <= m_entries_size);
if (m_entries_count >= m_entries_size)
{
const long entries_size = 2 * m_entries_size;
BlockEntry** const entries = new BlockEntry*[entries_size];
assert(entries);
BlockEntry** src = m_entries;
BlockEntry** const src_end = src + m_entries_count;
BlockEntry** dst = entries;
while (src != src_end)
*dst++ = *src++;
delete[] m_entries;
m_entries = entries;
m_entries_size = entries_size;
}
}
if (id == 0x20) //BlockGroup ID
return CreateBlockGroup(pos, size, discard_padding);
else //SimpleBlock ID
return CreateSimpleBlock(pos, size);
}
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::CreateBlock(
if (status < 0) { // error
pFirst = NULL;
return status;
}
if (m_entries_count <= 0) { // empty cluster
pFirst = NULL;
return 0;
}
}
assert(m_entries);
pFirst = m_entries[0];
assert(pFirst);
return 0; // success
}
| 174,257 |
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 RenderViewImpl::NavigateBackForwardSoon(int offset) {
history_navigation_virtual_time_pauser_ =
RenderThreadImpl::current()
->GetWebMainThreadScheduler()
->CreateWebScopedVirtualTimePauser(
"NavigateBackForwardSoon",
blink::WebScopedVirtualTimePauser::VirtualTaskDuration::kInstant);
history_navigation_virtual_time_pauser_.PauseVirtualTime();
Send(new ViewHostMsg_GoToEntryAtOffset(GetRoutingID(), offset));
}
Commit Message: Prevent renderer initiated back navigation to cancel a browser one.
Renderer initiated back/forward navigations must not be able to cancel ongoing
browser initiated navigation if they are not user initiated.
Note: 'normal' renderer initiated navigation uses the
FrameHost::BeginNavigation() path. A code similar to this patch is done
in NavigatorImpl::OnBeginNavigation().
Test:
-----
Added: NavigationBrowserTest.
* HistoryBackInBeforeUnload
* HistoryBackInBeforeUnloadAfterSetTimeout
* HistoryBackCancelPendingNavigationNoUserGesture
* HistoryBackCancelPendingNavigationUserGesture
Fixed:
* (WPT) .../the-history-interface/traverse_the_history_2.html
* (WPT) .../the-history-interface/traverse_the_history_3.html
* (WPT) .../the-history-interface/traverse_the_history_4.html
* (WPT) .../the-history-interface/traverse_the_history_5.html
Bug: 879965
Change-Id: I1a9bfaaea1ffc219e6c32f6e676b660e746c578c
Reviewed-on: https://chromium-review.googlesource.com/1209744
Commit-Queue: Arthur Sonzogni <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: Mustaq Ahmed <[email protected]>
Reviewed-by: Camille Lamy <[email protected]>
Reviewed-by: Charlie Reis <[email protected]>
Cr-Commit-Position: refs/heads/master@{#592823}
CWE ID: CWE-254 | void RenderViewImpl::NavigateBackForwardSoon(int offset) {
void RenderViewImpl::NavigateBackForwardSoon(int offset,
bool has_user_gesture) {
history_navigation_virtual_time_pauser_ =
RenderThreadImpl::current()
->GetWebMainThreadScheduler()
->CreateWebScopedVirtualTimePauser(
"NavigateBackForwardSoon",
blink::WebScopedVirtualTimePauser::VirtualTaskDuration::kInstant);
history_navigation_virtual_time_pauser_.PauseVirtualTime();
Send(new ViewHostMsg_GoToEntryAtOffset(GetRoutingID(), offset,
has_user_gesture));
}
| 172,648 |
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: ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState(
VisibilityState visibility_state) const {
if (visibility_state != AUTO_HIDE || !launcher_widget())
return AUTO_HIDE_HIDDEN;
Shell* shell = Shell::GetInstance();
if (shell->GetAppListTargetVisibility())
return AUTO_HIDE_SHOWN;
if (shell->system_tray() && shell->system_tray()->should_show_launcher())
return AUTO_HIDE_SHOWN;
if (launcher_ && launcher_->IsShowingMenu())
return AUTO_HIDE_SHOWN;
if (launcher_widget()->IsActive() || status_->IsActive())
return AUTO_HIDE_SHOWN;
if (event_filter_.get() && event_filter_->in_mouse_drag())
return AUTO_HIDE_HIDDEN;
aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow();
bool mouse_over_launcher =
launcher_widget()->GetWindowScreenBounds().Contains(
root->last_mouse_location());
return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN;
}
Commit Message: ash: Add launcher overflow bubble.
- Host a LauncherView in bubble to display overflown items;
- Mouse wheel and two-finger scroll to scroll the LauncherView in bubble in case overflow bubble is overflown;
- Fit bubble when items are added/removed;
- Keep launcher bar on screen when the bubble is shown;
BUG=128054
TEST=Verify launcher overflown items are in a bubble instead of menu.
Review URL: https://chromiumcodereview.appspot.com/10659003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@146460 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | ShelfLayoutManager::AutoHideState ShelfLayoutManager::CalculateAutoHideState(
VisibilityState visibility_state) const {
if (visibility_state != AUTO_HIDE || !launcher_widget())
return AUTO_HIDE_HIDDEN;
Shell* shell = Shell::GetInstance();
if (shell->GetAppListTargetVisibility())
return AUTO_HIDE_SHOWN;
if (shell->system_tray() && shell->system_tray()->should_show_launcher())
return AUTO_HIDE_SHOWN;
if (launcher_ && launcher_->IsShowingMenu())
return AUTO_HIDE_SHOWN;
if (launcher_ && launcher_->IsShowingOverflowBubble())
return AUTO_HIDE_SHOWN;
if (launcher_widget()->IsActive() || status_->IsActive())
return AUTO_HIDE_SHOWN;
if (event_filter_.get() && event_filter_->in_mouse_drag())
return AUTO_HIDE_HIDDEN;
aura::RootWindow* root = launcher_widget()->GetNativeView()->GetRootWindow();
bool mouse_over_launcher =
launcher_widget()->GetWindowScreenBounds().Contains(
root->last_mouse_location());
return mouse_over_launcher ? AUTO_HIDE_SHOWN : AUTO_HIDE_HIDDEN;
}
| 170,898 |
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 PixelBufferRasterWorkerPool::OnRasterTasksRequiredForActivationFinished() {
if (!should_notify_client_if_no_tasks_required_for_activation_are_pending_)
return;
CheckForCompletedRasterTasks();
}
Commit Message: cc: Simplify raster task completion notification logic
(Relanding after missing activation bug fixed in https://codereview.chromium.org/131763003/)
Previously the pixel buffer raster worker pool used a combination of
polling and explicit notifications from the raster worker pool to decide
when to tell the client about the completion of 1) all tasks or 2) the
subset of tasks required for activation. This patch simplifies the logic
by only triggering the notification based on the OnRasterTasksFinished
and OnRasterTasksRequiredForActivationFinished calls from the worker
pool.
BUG=307841,331534
Review URL: https://codereview.chromium.org/99873007
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@243991 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void PixelBufferRasterWorkerPool::OnRasterTasksRequiredForActivationFinished() {
if (!should_notify_client_if_no_tasks_required_for_activation_are_pending_)
return;
raster_required_for_activation_finished_task_pending_ = false;
CheckForCompletedRasterTasks();
}
| 171,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: base::string16 IDNToUnicodeWithAdjustments(
base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments) {
if (adjustments)
adjustments->clear();
base::string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
base::string16 out16;
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
component_end = input16.find('.', component_start);
if (component_end == base::string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
converted_idn =
IDNToUnicodeOneComponent(input16.data() + component_start,
component_length, &out16);
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && adjustments) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
component_start, component_length, new_component_length));
}
if (component_end < input16.length())
out16.push_back('.');
}
return out16;
}
Commit Message: Block domain labels made of Cyrillic letters that look alike Latin
Block a label made entirely of Latin-look-alike Cyrillic letters when the TLD is not an IDN (i.e. this check is ON only for TLDs like 'com', 'net', 'uk', but not applied for IDN TLDs like рф.
BUG=683314
TEST=components_unittests --gtest_filter=U*IDN*
Review-Url: https://codereview.chromium.org/2683793010
Cr-Commit-Position: refs/heads/master@{#459226}
CWE ID: CWE-20 | base::string16 IDNToUnicodeWithAdjustments(
base::StringPiece host, base::OffsetAdjuster::Adjustments* adjustments) {
if (adjustments)
adjustments->clear();
base::string16 input16;
input16.reserve(host.length());
input16.insert(input16.end(), host.begin(), host.end());
bool is_tld_ascii = true;
size_t last_dot = host.rfind('.');
if (last_dot != base::StringPiece::npos &&
host.substr(last_dot).starts_with(".xn--")) {
is_tld_ascii = false;
}
base::string16 out16;
for (size_t component_start = 0, component_end;
component_start < input16.length();
component_start = component_end + 1) {
component_end = input16.find('.', component_start);
if (component_end == base::string16::npos)
component_end = input16.length(); // For getting the last component.
size_t component_length = component_end - component_start;
size_t new_component_start = out16.length();
bool converted_idn = false;
if (component_end > component_start) {
converted_idn =
IDNToUnicodeOneComponent(input16.data() + component_start,
component_length, is_tld_ascii, &out16);
}
size_t new_component_length = out16.length() - new_component_start;
if (converted_idn && adjustments) {
adjustments->push_back(base::OffsetAdjuster::Adjustment(
component_start, component_length, new_component_length));
}
if (component_end < input16.length())
out16.push_back('.');
}
return out16;
}
| 172,391 |
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 FindBarController::MaybeSetPrepopulateText() {
#if !defined(OS_MACOSX)
FindManager* find_manager = tab_contents_->GetFindManager();
string16 find_string = find_manager->find_text();
if (find_string.empty())
find_string = find_manager->previous_find_text();
if (find_string.empty()) {
find_string =
FindBarState::GetLastPrepopulateText(tab_contents_->profile());
}
find_bar_->SetFindText(find_string);
#else
#endif
}
Commit Message: Rename the TabContentWrapper pieces to be "TabHelper"s. (Except for the PasswordManager... for now.) Also, just pre-create them up-front. It saves us effort, as they're all going to be eventually created anyway, so being lazy saves us nothing and creates headaches since the rules about what can be lazy differ from feature to feature.
BUG=71097
TEST=zero visible change
Review URL: http://codereview.chromium.org/6480117
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@75170 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void FindBarController::MaybeSetPrepopulateText() {
#if !defined(OS_MACOSX)
FindTabHelper* find_tab_helper = tab_contents_->find_tab_helper();
string16 find_string = find_tab_helper->find_text();
if (find_string.empty())
find_string = find_tab_helper->previous_find_text();
if (find_string.empty()) {
find_string =
FindBarState::GetLastPrepopulateText(tab_contents_->profile());
}
find_bar_->SetFindText(find_string);
#else
#endif
}
| 170,659 |
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 char *get_pid_environ_val(pid_t pid,char *val){
char temp[500];
int i=0;
int foundit=0;
FILE *fp;
sprintf(temp,"/proc/%d/environ",pid);
fp=fopen(temp,"r");
if(fp==NULL)
return NULL;
for(;;){
temp[i]=fgetc(fp);
if(foundit==1 && (temp[i]==0 || temp[i]=='\0' || temp[i]==EOF)){
char *ret;
temp[i]=0;
ret=malloc(strlen(temp)+10);
sprintf(ret,"%s",temp);
fclose(fp);
return ret;
}
switch(temp[i]){
case EOF:
fclose(fp);
return NULL;
case '=':
temp[i]=0;
if(!strcmp(temp,val)){
foundit=1;
}
i=0;
break;
case '\0':
i=0;
break;
default:
i++;
}
}
}
Commit Message: Fix memory overflow if the name of an environment is larger than 500 characters. Bug found by Adam Sampson.
CWE ID: CWE-119 | static char *get_pid_environ_val(pid_t pid,char *val){
int temp_size = 500;
char *temp = malloc(temp_size);
int i=0;
int foundit=0;
FILE *fp;
sprintf(temp,"/proc/%d/environ",pid);
fp=fopen(temp,"r");
if(fp==NULL)
return NULL;
for(;;){
if (i >= temp_size) {
temp_size *= 2;
temp = realloc(temp, temp_size);
}
temp[i]=fgetc(fp);
if(foundit==1 && (temp[i]==0 || temp[i]=='\0' || temp[i]==EOF)){
char *ret;
temp[i]=0;
ret=malloc(strlen(temp)+10);
sprintf(ret,"%s",temp);
fclose(fp);
return ret;
}
switch(temp[i]){
case EOF:
fclose(fp);
return NULL;
case '=':
temp[i]=0;
if(!strcmp(temp,val)){
foundit=1;
}
i=0;
break;
case '\0':
i=0;
break;
default:
i++;
}
}
}
| 166,639 |
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 DownloadController::CreateGETDownload(
const content::ResourceRequestInfo::WebContentsGetter& wc_getter,
bool must_download,
const DownloadInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::IO);
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&DownloadController::StartAndroidDownload,
base::Unretained(this),
wc_getter, must_download, info));
}
Commit Message: Clean up Android DownloadManager code as most download now go through Chrome Network stack
The only exception is OMA DRM download.
And it only applies to context menu download interception.
Clean up the remaining unused code now.
BUG=647755
Review-Url: https://codereview.chromium.org/2371773003
Cr-Commit-Position: refs/heads/master@{#421332}
CWE ID: CWE-254 | void DownloadController::CreateGETDownload(
| 171,881 |
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 Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
Commit Message: All: Merge some file writing extension checks
CWE ID: CWE-269 | void Com_WriteConfig_f( void ) {
char filename[MAX_QPATH];
if ( Cmd_Argc() != 2 ) {
Com_Printf( "Usage: writeconfig <filename>\n" );
return;
}
if (!COM_CompareExtension(filename, ".cfg"))
{
Com_Printf("Com_WriteConfig_f: Only the \".cfg\" extension is supported by this command!\n");
return;
}
Q_strncpyz( filename, Cmd_Argv( 1 ), sizeof( filename ) );
COM_DefaultExtension( filename, sizeof( filename ), ".cfg" );
Com_Printf( "Writing %s.\n", filename );
Com_WriteConfigToFile( filename );
}
| 170,080 |
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 Image *ReadWMFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
double
bounding_height,
bounding_width,
image_height,
image_height_inch,
image_width,
image_width_inch,
resolution_y,
resolution_x,
units_per_inch;
float
wmf_width,
wmf_height;
Image
*image;
unsigned long
wmf_options_flags = 0;
wmf_error_t
wmf_error;
wmf_magick_t
*ddata = 0;
wmfAPI
*API = 0;
wmfAPI_Options
wmf_api_options;
wmfD_Rect
bbox;
image=AcquireImage(image_info);
if (OpenBlob(image_info,image,ReadBinaryBlobMode,exception) == MagickFalse)
{
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OpenBlob failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Create WMF API
*
*/
/* Register callbacks */
wmf_options_flags |= WMF_OPT_FUNCTION;
(void) ResetMagickMemory(&wmf_api_options, 0, sizeof(wmf_api_options));
wmf_api_options.function = ipa_functions;
/* Ignore non-fatal errors */
wmf_options_flags |= WMF_OPT_IGNORE_NONFATAL;
wmf_error = wmf_api_create(&API, wmf_options_flags, &wmf_api_options);
if (wmf_error != wmf_E_None)
{
if (API)
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_api_create failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"UnableToInitializeWMFLibrary");
}
/* Register progress monitor */
wmf_status_function(API,image,magick_progress_callback);
ddata=WMF_MAGICK_GetData(API);
ddata->image=image;
ddata->image_info=image_info;
ddata->draw_info=CloneDrawInfo(image_info,(const DrawInfo *) NULL);
ddata->draw_info->font=(char *)
RelinquishMagickMemory(ddata->draw_info->font);
ddata->draw_info->text=(char *)
RelinquishMagickMemory(ddata->draw_info->text);
#if defined(MAGICKCORE_WMFLITE_DELEGATE)
/* Must initialize font subystem for WMFlite interface */
lite_font_init (API,&wmf_api_options); /* similar to wmf_ipa_font_init in src/font.c */
/* wmf_arg_fontdirs (API,options); */ /* similar to wmf_arg_fontdirs in src/wmf.c */
#endif
/*
* Open BLOB input via libwmf API
*
*/
wmf_error = wmf_bbuf_input(API,ipa_blob_read,ipa_blob_seek,
ipa_blob_tell,(void*)image);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_bbuf_input failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Scan WMF file
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scanning WMF to obtain bounding box");
wmf_error=wmf_scan(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_scan failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToScanFile");
}
/*
* Compute dimensions and scale factors
*
*/
ddata->bbox=bbox;
/* User specified resolution */
resolution_y=DefaultResolution;
if (image->y_resolution != 0.0)
{
resolution_y = image->y_resolution;
if (image->units == PixelsPerCentimeterResolution)
resolution_y *= CENTIMETERS_PER_INCH;
}
resolution_x=DefaultResolution;
if (image->x_resolution != 0.0)
{
resolution_x = image->x_resolution;
if (image->units == PixelsPerCentimeterResolution)
resolution_x *= CENTIMETERS_PER_INCH;
}
/* Obtain output size expressed in metafile units */
wmf_error=wmf_size(API,&wmf_width,&wmf_height);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_size failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToComputeOutputSize");
}
/* Obtain (or guess) metafile units */
if ((API)->File->placeable)
units_per_inch=(API)->File->pmh->Inch;
else if ( (wmf_width*wmf_height) < 1024*1024)
units_per_inch=POINTS_PER_INCH; /* MM_TEXT */
else
units_per_inch=TWIPS_PER_INCH; /* MM_TWIPS */
/* Calculate image width and height based on specified DPI
resolution */
image_width_inch = (double) wmf_width / units_per_inch;
image_height_inch = (double) wmf_height / units_per_inch;
image_width = image_width_inch * resolution_x;
image_height = image_height_inch * resolution_y;
/* Compute bounding box scale factors and origin translations
*
* This all just a hack since libwmf does not currently seem to
* provide the mapping between LOGICAL coordinates and DEVICE
* coordinates. This mapping is necessary in order to know
* where to place the logical bounding box within the image.
*
*/
bounding_width = bbox.BR.x - bbox.TL.x;
bounding_height = bbox.BR.y - bbox.TL.y;
ddata->scale_x = image_width/bounding_width;
ddata->translate_x = 0-bbox.TL.x;
ddata->rotate = 0;
/* Heuristic: guess that if the vertical coordinates mostly span
negative values, then the image must be inverted. */
if ( fabs(bbox.BR.y) > fabs(bbox.TL.y) )
{
/* Normal (Origin at top left of image) */
ddata->scale_y = (image_height/bounding_height);
ddata->translate_y = 0-bbox.TL.y;
}
else
{
/* Inverted (Origin at bottom left of image) */
ddata->scale_y = (-image_height/bounding_height);
ddata->translate_y = 0-bbox.BR.y;
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Placeable metafile: %s",
(API)->File->placeable ? "Yes" : "No");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in metafile units: %gx%g",wmf_width,wmf_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Metafile units/inch: %g",units_per_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in inches: %gx%g",
image_width_inch,image_height_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding Box: %g,%g %g,%g",
bbox.TL.x, bbox.TL.y, bbox.BR.x, bbox.BR.y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding width x height: %gx%g",bounding_width,
bounding_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Output resolution: %gx%g",resolution_x,resolution_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image size: %gx%g",image_width,image_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding box scale factor: %g,%g",ddata->scale_x,
ddata->scale_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Translation: %g,%g",
ddata->translate_x, ddata->translate_y);
}
#if 0
#if 0
{
typedef struct _wmfPlayer_t wmfPlayer_t;
struct _wmfPlayer_t
{
wmfPen default_pen;
wmfBrush default_brush;
wmfFont default_font;
wmfDC* dc; /* current dc */
};
wmfDC
*dc;
#define WMF_ELICIT_DC(API) (((wmfPlayer_t*)((API)->player_data))->dc)
dc = WMF_ELICIT_DC(API);
printf("dc->Window.Ox = %d\n", dc->Window.Ox);
printf("dc->Window.Oy = %d\n", dc->Window.Oy);
printf("dc->Window.width = %d\n", dc->Window.width);
printf("dc->Window.height = %d\n", dc->Window.height);
printf("dc->pixel_width = %g\n", dc->pixel_width);
printf("dc->pixel_height = %g\n", dc->pixel_height);
#if defined(MAGICKCORE_WMFLITE_DELEGATE) /* Only in libwmf 0.3 */
printf("dc->Ox = %.d\n", dc->Ox);
printf("dc->Oy = %.d\n", dc->Oy);
printf("dc->width = %.d\n", dc->width);
printf("dc->height = %.d\n", dc->height);
#endif
}
#endif
#endif
/*
* Create canvas image
*
*/
image->rows=(unsigned long) ceil(image_height);
image->columns=(unsigned long) ceil(image_width);
if (image_info->ping != MagickFalse)
{
wmf_api_destroy(API);
(void) CloseBlob(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
return(GetFirstImageInList(image));
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating canvas image with size %lux%lu",(unsigned long) image->rows,
(unsigned long) image->columns);
/*
* Set solid background color
*/
{
image->background_color = image_info->background_color;
if (image->background_color.opacity != OpaqueOpacity)
image->matte = MagickTrue;
(void) SetImageBackgroundColor(image);
}
/*
* Play file to generate Vector drawing commands
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF to prepare vectors");
wmf_error = wmf_play(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToRenderFile");
}
/*
* Scribble on canvas image
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Rendering WMF vectors");
DrawRender(ddata->draw_wand);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"leave ReadWMFImage()");
/* Cleanup allocated data */
wmf_api_destroy(API);
(void) CloseBlob(image);
/* Return image */
return image;
}
Commit Message:
CWE ID: CWE-119 | static Image *ReadWMFImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
double
bounding_height,
bounding_width,
image_height,
image_height_inch,
image_width,
image_width_inch,
resolution_y,
resolution_x,
units_per_inch;
float
wmf_width,
wmf_height;
Image
*image;
MagickBooleanType
status;
unsigned long
wmf_options_flags = 0;
wmf_error_t
wmf_error;
wmf_magick_t
*ddata = 0;
wmfAPI
*API = 0;
wmfAPI_Options
wmf_api_options;
wmfD_Rect
bbox;
image=AcquireImage(image_info);
if (OpenBlob(image_info,image,ReadBinaryBlobMode,exception) == MagickFalse)
{
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" OpenBlob failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Create WMF API
*
*/
/* Register callbacks */
wmf_options_flags |= WMF_OPT_FUNCTION;
(void) ResetMagickMemory(&wmf_api_options, 0, sizeof(wmf_api_options));
wmf_api_options.function = ipa_functions;
/* Ignore non-fatal errors */
wmf_options_flags |= WMF_OPT_IGNORE_NONFATAL;
wmf_error = wmf_api_create(&API, wmf_options_flags, &wmf_api_options);
if (wmf_error != wmf_E_None)
{
if (API)
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_api_create failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"UnableToInitializeWMFLibrary");
}
/* Register progress monitor */
wmf_status_function(API,image,magick_progress_callback);
ddata=WMF_MAGICK_GetData(API);
ddata->image=image;
ddata->image_info=image_info;
ddata->draw_info=CloneDrawInfo(image_info,(const DrawInfo *) NULL);
ddata->draw_info->font=(char *)
RelinquishMagickMemory(ddata->draw_info->font);
ddata->draw_info->text=(char *)
RelinquishMagickMemory(ddata->draw_info->text);
#if defined(MAGICKCORE_WMFLITE_DELEGATE)
/* Must initialize font subystem for WMFlite interface */
lite_font_init (API,&wmf_api_options); /* similar to wmf_ipa_font_init in src/font.c */
/* wmf_arg_fontdirs (API,options); */ /* similar to wmf_arg_fontdirs in src/wmf.c */
#endif
/*
* Open BLOB input via libwmf API
*
*/
wmf_error = wmf_bbuf_input(API,ipa_blob_read,ipa_blob_seek,
ipa_blob_tell,(void*)image);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_bbuf_input failed");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowFileException(exception,FileOpenError,"UnableToOpenFile",
image->filename);
image=DestroyImageList(image);
return((Image *) NULL);
}
/*
* Scan WMF file
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scanning WMF to obtain bounding box");
wmf_error=wmf_scan(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_scan failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToScanFile");
}
/*
* Compute dimensions and scale factors
*
*/
ddata->bbox=bbox;
/* User specified resolution */
resolution_y=DefaultResolution;
if (image->y_resolution != 0.0)
{
resolution_y = image->y_resolution;
if (image->units == PixelsPerCentimeterResolution)
resolution_y *= CENTIMETERS_PER_INCH;
}
resolution_x=DefaultResolution;
if (image->x_resolution != 0.0)
{
resolution_x = image->x_resolution;
if (image->units == PixelsPerCentimeterResolution)
resolution_x *= CENTIMETERS_PER_INCH;
}
/* Obtain output size expressed in metafile units */
wmf_error=wmf_size(API,&wmf_width,&wmf_height);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" wmf_size failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToComputeOutputSize");
}
/* Obtain (or guess) metafile units */
if ((API)->File->placeable)
units_per_inch=(API)->File->pmh->Inch;
else if ( (wmf_width*wmf_height) < 1024*1024)
units_per_inch=POINTS_PER_INCH; /* MM_TEXT */
else
units_per_inch=TWIPS_PER_INCH; /* MM_TWIPS */
/* Calculate image width and height based on specified DPI
resolution */
image_width_inch = (double) wmf_width / units_per_inch;
image_height_inch = (double) wmf_height / units_per_inch;
image_width = image_width_inch * resolution_x;
image_height = image_height_inch * resolution_y;
/* Compute bounding box scale factors and origin translations
*
* This all just a hack since libwmf does not currently seem to
* provide the mapping between LOGICAL coordinates and DEVICE
* coordinates. This mapping is necessary in order to know
* where to place the logical bounding box within the image.
*
*/
bounding_width = bbox.BR.x - bbox.TL.x;
bounding_height = bbox.BR.y - bbox.TL.y;
ddata->scale_x = image_width/bounding_width;
ddata->translate_x = 0-bbox.TL.x;
ddata->rotate = 0;
/* Heuristic: guess that if the vertical coordinates mostly span
negative values, then the image must be inverted. */
if ( fabs(bbox.BR.y) > fabs(bbox.TL.y) )
{
/* Normal (Origin at top left of image) */
ddata->scale_y = (image_height/bounding_height);
ddata->translate_y = 0-bbox.TL.y;
}
else
{
/* Inverted (Origin at bottom left of image) */
ddata->scale_y = (-image_height/bounding_height);
ddata->translate_y = 0-bbox.BR.y;
}
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Placeable metafile: %s",
(API)->File->placeable ? "Yes" : "No");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in metafile units: %gx%g",wmf_width,wmf_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Metafile units/inch: %g",units_per_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Size in inches: %gx%g",
image_width_inch,image_height_inch);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding Box: %g,%g %g,%g",
bbox.TL.x, bbox.TL.y, bbox.BR.x, bbox.BR.y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding width x height: %gx%g",bounding_width,
bounding_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Output resolution: %gx%g",resolution_x,resolution_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image size: %gx%g",image_width,image_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Bounding box scale factor: %g,%g",ddata->scale_x,
ddata->scale_y);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Translation: %g,%g",
ddata->translate_x, ddata->translate_y);
}
#if 0
#if 0
{
typedef struct _wmfPlayer_t wmfPlayer_t;
struct _wmfPlayer_t
{
wmfPen default_pen;
wmfBrush default_brush;
wmfFont default_font;
wmfDC* dc; /* current dc */
};
wmfDC
*dc;
#define WMF_ELICIT_DC(API) (((wmfPlayer_t*)((API)->player_data))->dc)
dc = WMF_ELICIT_DC(API);
printf("dc->Window.Ox = %d\n", dc->Window.Ox);
printf("dc->Window.Oy = %d\n", dc->Window.Oy);
printf("dc->Window.width = %d\n", dc->Window.width);
printf("dc->Window.height = %d\n", dc->Window.height);
printf("dc->pixel_width = %g\n", dc->pixel_width);
printf("dc->pixel_height = %g\n", dc->pixel_height);
#if defined(MAGICKCORE_WMFLITE_DELEGATE) /* Only in libwmf 0.3 */
printf("dc->Ox = %.d\n", dc->Ox);
printf("dc->Oy = %.d\n", dc->Oy);
printf("dc->width = %.d\n", dc->width);
printf("dc->height = %.d\n", dc->height);
#endif
}
#endif
#endif
/*
* Create canvas image
*
*/
image->rows=(unsigned long) ceil(image_height);
image->columns=(unsigned long) ceil(image_width);
if (image_info->ping != MagickFalse)
{
wmf_api_destroy(API);
(void) CloseBlob(image);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
return(GetFirstImageInList(image));
}
status=SetImageExtent(image,image->columns,image->rows);
if (status == MagickFalse)
{
InheritException(exception,&image->exception);
return(DestroyImageList(image));
}
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Creating canvas image with size %lux%lu",(unsigned long) image->rows,
(unsigned long) image->columns);
/*
* Set solid background color
*/
{
image->background_color = image_info->background_color;
if (image->background_color.opacity != OpaqueOpacity)
image->matte = MagickTrue;
(void) SetImageBackgroundColor(image);
}
/*
* Play file to generate Vector drawing commands
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF to prepare vectors");
wmf_error = wmf_play(API, 0, &bbox);
if (wmf_error != wmf_E_None)
{
wmf_api_destroy(API);
if (image->debug != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Playing WMF failed with wmf_error %d", wmf_error);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"leave ReadWMFImage()");
}
ThrowReaderException(DelegateError,"FailedToRenderFile");
}
/*
* Scribble on canvas image
*
*/
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Rendering WMF vectors");
DrawRender(ddata->draw_wand);
if (image->debug != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),"leave ReadWMFImage()");
/* Cleanup allocated data */
wmf_api_destroy(API);
(void) CloseBlob(image);
/* Return image */
return image;
}
| 168,621 |
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 get_socket_name( char* buf, int len )
{
char* dpy = g_strdup(g_getenv("DISPLAY"));
if(dpy && *dpy)
{
char* p = strchr(dpy, ':');
for(++p; *p && *p != '.' && *p != '\n';)
++p;
if(*p)
*p = '\0';
}
g_snprintf( buf, len, "%s/.menu-cached-%s-%s", g_get_tmp_dir(),
dpy ? dpy : ":0", g_get_user_name() );
g_free(dpy);
}
Commit Message:
CWE ID: CWE-20 | static void get_socket_name( char* buf, int len )
{
char* dpy = g_strdup(g_getenv("DISPLAY"));
if(dpy && *dpy)
{
char* p = strchr(dpy, ':');
for(++p; *p && *p != '.' && *p != '\n';)
++p;
if(*p)
*p = '\0';
}
#if GLIB_CHECK_VERSION(2, 28, 0)
g_snprintf( buf, len, "%s/menu-cached-%s", g_get_user_runtime_dir(),
dpy ? dpy : ":0" );
#else
g_snprintf( buf, len, "%s/.menu-cached-%s-%s", g_get_tmp_dir(),
dpy ? dpy : ":0", g_get_user_name() );
#endif
g_free(dpy);
}
| 164,817 |
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 ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
unsigned long src = *ppos;
int ret = 0;
struct mm_struct *mm = file->private_data;
unsigned long env_start, env_end;
if (!mm)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
ret = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
down_read(&mm->mmap_sem);
env_start = mm->env_start;
env_end = mm->env_end;
up_read(&mm->mmap_sem);
while (count > 0) {
size_t this_len, max_len;
int retval;
if (src >= (env_end - env_start))
break;
this_len = env_end - (env_start + src);
max_len = min_t(size_t, PAGE_SIZE, count);
this_len = min(max_len, this_len);
retval = access_remote_vm(mm, (env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
free:
free_page((unsigned long) page);
return ret;
}
Commit Message: proc: prevent accessing /proc/<PID>/environ until it's ready
If /proc/<PID>/environ gets read before the envp[] array is fully set up
in create_{aout,elf,elf_fdpic,flat}_tables(), we might end up trying to
read more bytes than are actually written, as env_start will already be
set but env_end will still be zero, making the range calculation
underflow, allowing to read beyond the end of what has been written.
Fix this as it is done for /proc/<PID>/cmdline by testing env_end for
zero. It is, apparently, intentionally set last in create_*_tables().
This bug was found by the PaX size_overflow plugin that detected the
arithmetic underflow of 'this_len = env_end - (env_start + src)' when
env_end is still zero.
The expected consequence is that userland trying to access
/proc/<PID>/environ of a not yet fully set up process may get
inconsistent data as we're in the middle of copying in the environment
variables.
Fixes: https://forums.grsecurity.net/viewtopic.php?f=3&t=4363
Fixes: https://bugzilla.kernel.org/show_bug.cgi?id=116461
Signed-off-by: Mathias Krause <[email protected]>
Cc: Emese Revfy <[email protected]>
Cc: Pax Team <[email protected]>
Cc: Al Viro <[email protected]>
Cc: Mateusz Guzik <[email protected]>
Cc: Alexey Dobriyan <[email protected]>
Cc: Cyrill Gorcunov <[email protected]>
Cc: Jarod Wilson <[email protected]>
Signed-off-by: Andrew Morton <[email protected]>
Signed-off-by: Linus Torvalds <[email protected]>
CWE ID: CWE-362 | static ssize_t environ_read(struct file *file, char __user *buf,
size_t count, loff_t *ppos)
{
char *page;
unsigned long src = *ppos;
int ret = 0;
struct mm_struct *mm = file->private_data;
unsigned long env_start, env_end;
/* Ensure the process spawned far enough to have an environment. */
if (!mm || !mm->env_end)
return 0;
page = (char *)__get_free_page(GFP_TEMPORARY);
if (!page)
return -ENOMEM;
ret = 0;
if (!atomic_inc_not_zero(&mm->mm_users))
goto free;
down_read(&mm->mmap_sem);
env_start = mm->env_start;
env_end = mm->env_end;
up_read(&mm->mmap_sem);
while (count > 0) {
size_t this_len, max_len;
int retval;
if (src >= (env_end - env_start))
break;
this_len = env_end - (env_start + src);
max_len = min_t(size_t, PAGE_SIZE, count);
this_len = min(max_len, this_len);
retval = access_remote_vm(mm, (env_start + src),
page, this_len, 0);
if (retval <= 0) {
ret = retval;
break;
}
if (copy_to_user(buf, page, retval)) {
ret = -EFAULT;
break;
}
ret += retval;
src += retval;
buf += retval;
count -= retval;
}
*ppos = src;
mmput(mm);
free:
free_page((unsigned long) page);
return ret;
}
| 166,920 |
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 parse_token(char **name, char **value, char **cp)
{
char *end;
if (!name || !value || !cp)
return -BLKID_ERR_PARAM;
if (!(*value = strchr(*cp, '=')))
return 0;
**value = '\0';
*name = strip_line(*cp);
*value = skip_over_blank(*value + 1);
if (**value == '"') {
end = strchr(*value + 1, '"');
if (!end) {
DBG(READ, ul_debug("unbalanced quotes at: %s", *value));
*cp = *value;
return -BLKID_ERR_CACHE;
}
(*value)++;
*end = '\0';
end++;
} else {
end = skip_over_word(*value);
if (*end) {
*end = '\0';
end++;
}
}
*cp = end;
return 1;
}
Commit Message: libblkid: care about unsafe chars in cache
The high-level libblkid API uses /run/blkid/blkid.tab cache to
store probing results. The cache format is
<device NAME="value" ...>devname</device>
and unfortunately the cache code does not escape quotation marks:
# mkfs.ext4 -L 'AAA"BBB'
# cat /run/blkid/blkid.tab
...
<device ... LABEL="AAA"BBB" ...>/dev/sdb1</device>
such string is later incorrectly parsed and blkid(8) returns
nonsenses. And for use-cases like
# eval $(blkid -o export /dev/sdb1)
it's also insecure.
Note that mount, udevd and blkid -p are based on low-level libblkid
API, it bypass the cache and directly read data from the devices.
The current udevd upstream does not depend on blkid(8) output at all,
it's directly linked with the library and all unsafe chars are encoded by
\x<hex> notation.
# mkfs.ext4 -L 'X"`/tmp/foo` "' /dev/sdb1
# udevadm info --export-db | grep LABEL
...
E: ID_FS_LABEL=X__/tmp/foo___
E: ID_FS_LABEL_ENC=X\x22\x60\x2ftmp\x2ffoo\x60\x20\x22
Signed-off-by: Karel Zak <[email protected]>
CWE ID: CWE-77 | static int parse_token(char **name, char **value, char **cp)
{
char *end;
if (!name || !value || !cp)
return -BLKID_ERR_PARAM;
if (!(*value = strchr(*cp, '=')))
return 0;
**value = '\0';
*name = strip_line(*cp);
*value = skip_over_blank(*value + 1);
if (**value == '"') {
char *p = end = *value + 1;
/* convert 'foo\"bar' to 'foo"bar' */
while (*p) {
if (*p == '\\') {
p++;
*end = *p;
} else {
*end = *p;
if (*p == '"')
break;
}
p++;
end++;
}
if (*end != '"') {
DBG(READ, ul_debug("unbalanced quotes at: %s", *value));
*cp = *value;
return -BLKID_ERR_CACHE;
}
(*value)++;
*end = '\0';
end = ++p;
} else {
end = skip_over_word(*value);
if (*end) {
*end = '\0';
end++;
}
}
*cp = end;
return 1;
}
| 168,909 |
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: zlib_advance(struct zlib *zlib, png_uint_32 nbytes)
/* Read nbytes compressed bytes; the stream will be initialized if required.
* Bytes are always being reread and errors are fatal. The return code is as
* follows:
*
* -1: saw the "too far back" error
* 0: ok, keep going
* 1: saw Z_STREAM_END (zlib->extra_bytes indicates too much data)
* 2: a zlib error that cannot be corrected (error message already
* output if required.)
*/
# define ZLIB_TOO_FAR_BACK (-1)
# define ZLIB_OK 0
# define ZLIB_STREAM_END 1
# define ZLIB_FATAL 2
{
int state = zlib->state;
int endrc = ZLIB_OK;
png_uint_32 in_bytes = 0;
struct file *file = zlib->file;
assert(state >= 0);
while (in_bytes < nbytes && endrc == ZLIB_OK)
{
png_uint_32 out_bytes;
int flush;
png_byte bIn = reread_byte(file);
png_byte bOut;
switch (state)
{
case 0: /* first header byte */
{
int file_bits = 8+(bIn >> 4);
int new_bits = zlib->window_bits;
zlib->file_bits = file_bits;
/* Check against the existing value - it may not need to be
* changed.
*/
if (new_bits == 0) /* no change */
zlib->window_bits = file_bits;
else if (new_bits != file_bits) /* rewrite required */
bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4));
}
zlib->header[0] = bIn;
zlib->state = state = 1;
break;
case 1: /* second header byte */
{
int b2 = bIn & 0xe0; /* top 3 bits */
/* The checksum calculation, on the first 11 bits: */
b2 += 0x1f - ((zlib->header[0] << 8) + b2) % 0x1f;
/* Update the checksum byte if required: */
if (bIn != b2)
{
/* If the first byte wasn't changed this indicates an error in
* the checksum calculation; signal this by setting file_bits
* (not window_bits) to 0.
*/
if (zlib->file_bits == zlib->window_bits)
zlib->cksum = 1;
bIn = (png_byte)b2;
}
}
zlib->header[1] = bIn;
zlib->state = state = 2;
break;
default: /* After the header bytes */
break;
}
/* For some streams, perhaps only those compressed with 'superfast
* compression' (which results in a lot of copying) Z_BUF_ERROR can happen
* immediately after all output has been flushed on the next input byte.
* This is handled below when Z_BUF_ERROR is detected by adding an output
* byte.
*/
zlib->z.next_in = &bIn;
zlib->z.avail_in = 1;
zlib->z.next_out = &bOut;
zlib->z.avail_out = 0; /* Initially */
/* Initially use Z_NO_FLUSH in an attempt to persuade zlib to look at this
* byte without confusing what is going on with output.
*/
flush = Z_NO_FLUSH;
out_bytes = 0;
/* NOTE: expression 3 is only evaluted on 'continue', because of the
* 'break' at the end of this loop below.
*/
for (;endrc == ZLIB_OK;
flush = Z_SYNC_FLUSH,
zlib->z.next_out = &bOut,
zlib->z.avail_out = 1,
++out_bytes)
{
zlib->rc = inflate(&zlib->z, flush);
out_bytes -= zlib->z.avail_out;
switch (zlib->rc)
{
case Z_BUF_ERROR:
if (zlib->z.avail_out == 0)
continue; /* Try another output byte. */
if (zlib->z.avail_in == 0)
break; /* Try another input byte */
/* Both avail_out and avail_in are 1 yet zlib returned a code
* indicating no progress was possible. This is unexpected.
*/
zlib_message(zlib, 1/*unexpected*/);
endrc = ZLIB_FATAL; /* stop processing */
break;
case Z_OK:
/* Zlib is supposed to have made progress: */
assert(zlib->z.avail_out == 0 || zlib->z.avail_in == 0);
continue;
case Z_STREAM_END:
/* This is the successful end. */
zlib->state = 3; /* end of stream */
endrc = ZLIB_STREAM_END;
break;
case Z_NEED_DICT:
zlib_message(zlib, 0/*stream error*/);
endrc = ZLIB_FATAL;
break;
case Z_DATA_ERROR:
/* The too far back error can be corrected, others cannot: */
if (zlib->z.msg != NULL &&
strcmp(zlib->z.msg, "invalid distance too far back") == 0)
{
endrc = ZLIB_TOO_FAR_BACK;
break;
}
/* FALL THROUGH */
default:
zlib_message(zlib, 0/*stream error*/);
endrc = ZLIB_FATAL;
break;
} /* switch (inflate rc) */
/* Control gets here when further output is not possible; endrc may
* still be ZLIB_OK if more input is required.
*/
break;
} /* for (output bytes) */
/* Keep a running count of output byte produced: */
zlib->uncompressed_digits = uarb_add32(zlib->uncompressed_bytes,
zlib->uncompressed_digits, out_bytes);
/* Keep going, the loop will terminate when endrc is no longer set to
* ZLIB_OK or all the input bytes have been consumed; meanwhile keep
* adding input bytes.
*/
assert(zlib->z.avail_in == 0 || endrc != ZLIB_OK);
in_bytes += 1 - zlib->z.avail_in;
} /* while (input bytes) */
assert(in_bytes == nbytes || endrc != ZLIB_OK);
/* Update the running total of input bytes consumed */
zlib->compressed_digits = uarb_add32(zlib->compressed_bytes,
zlib->compressed_digits, in_bytes - zlib->z.avail_in);
/* At the end of the stream update the chunk with the accumulated
* information if it is an improvement:
*/
if (endrc == ZLIB_STREAM_END && zlib->window_bits < zlib->ok_bits)
{
struct chunk *chunk = zlib->chunk;
chunk->uncompressed_digits = uarb_copy(chunk->uncompressed_bytes,
zlib->uncompressed_bytes, zlib->uncompressed_digits);
chunk->compressed_digits = uarb_copy(chunk->compressed_bytes,
zlib->compressed_bytes, zlib->compressed_digits);
chunk->rewrite_buffer[0] = zlib->header[0];
chunk->rewrite_buffer[1] = zlib->header[1];
if (zlib->window_bits != zlib->file_bits || zlib->cksum)
{
/* A rewrite is required */
chunk->rewrite_offset = zlib->rewrite_offset;
chunk->rewrite_length = 2;
}
else
{
chunk->rewrite_offset = 0;
chunk->rewrite_length = 0;
}
if (in_bytes < nbytes)
chunk_message(chunk, "extra compressed data");
zlib->extra_bytes = nbytes - in_bytes;
zlib->ok_bits = zlib->window_bits;
}
return endrc;
}
Commit Message: DO NOT MERGE Update libpng to 1.6.20
BUG:23265085
Change-Id: I85199805636d771f3597b691b63bc0bf46084833
(cherry picked from commit bbe98b40cda082024b669fa508931042eed18f82)
CWE ID: | zlib_advance(struct zlib *zlib, png_uint_32 nbytes)
/* Read nbytes compressed bytes; the stream will be initialized if required.
* Bytes are always being reread and errors are fatal. The return code is as
* follows:
*
* -1: saw the "too far back" error
* 0: ok, keep going
* 1: saw Z_STREAM_END (zlib->extra_bytes indicates too much data)
* 2: a zlib error that cannot be corrected (error message already
* output if required.)
*/
# define ZLIB_TOO_FAR_BACK (-1)
# define ZLIB_OK 0
# define ZLIB_STREAM_END 1
# define ZLIB_FATAL 2
{
int state = zlib->state;
int endrc = ZLIB_OK;
png_uint_32 in_bytes = 0;
struct file *file = zlib->file;
assert(state >= 0);
while (in_bytes < nbytes && endrc == ZLIB_OK)
{
png_uint_32 out_bytes;
int flush;
png_byte bIn = reread_byte(file);
png_byte bOut;
switch (state)
{
case 0: /* first header byte */
{
int file_bits = 8+(bIn >> 4);
int new_bits = zlib->window_bits;
zlib->file_bits = file_bits;
/* Check against the existing value - it may not need to be
* changed. Note that a bogus file_bits is allowed through once,
* to see if it works, but the window_bits value is set to 15,
* the maximum.
*/
if (new_bits == 0) /* no change */
zlib->window_bits = ((file_bits > 15) ? 15 : file_bits);
else if (new_bits != file_bits) /* rewrite required */
bIn = (png_byte)((bIn & 0xf) + ((new_bits-8) << 4));
}
zlib->header[0] = bIn;
zlib->state = state = 1;
break;
case 1: /* second header byte */
{
int b2 = bIn & 0xe0; /* top 3 bits */
/* The checksum calculation, on the first 11 bits: */
b2 += 0x1f - ((zlib->header[0] << 8) + b2) % 0x1f;
/* Update the checksum byte if required: */
if (bIn != b2)
{
/* If the first byte wasn't changed this indicates an error in
* the checksum calculation; signal this by setting 'cksum'.
*/
if (zlib->file_bits == zlib->window_bits)
zlib->cksum = 1;
bIn = (png_byte)b2;
}
}
zlib->header[1] = bIn;
zlib->state = state = 2;
break;
default: /* After the header bytes */
break;
}
/* For some streams, perhaps only those compressed with 'superfast
* compression' (which results in a lot of copying) Z_BUF_ERROR can happen
* immediately after all output has been flushed on the next input byte.
* This is handled below when Z_BUF_ERROR is detected by adding an output
* byte.
*/
zlib->z.next_in = &bIn;
zlib->z.avail_in = 1;
zlib->z.next_out = &bOut;
zlib->z.avail_out = 0; /* Initially */
/* Initially use Z_NO_FLUSH in an attempt to persuade zlib to look at this
* byte without confusing what is going on with output.
*/
flush = Z_NO_FLUSH;
out_bytes = 0;
/* NOTE: expression 3 is only evaluted on 'continue', because of the
* 'break' at the end of this loop below.
*/
for (;endrc == ZLIB_OK;
flush = Z_SYNC_FLUSH,
zlib->z.next_out = &bOut,
zlib->z.avail_out = 1,
++out_bytes)
{
zlib->rc = inflate(&zlib->z, flush);
out_bytes -= zlib->z.avail_out;
switch (zlib->rc)
{
case Z_BUF_ERROR:
if (zlib->z.avail_out == 0)
continue; /* Try another output byte. */
if (zlib->z.avail_in == 0)
break; /* Try another input byte */
/* Both avail_out and avail_in are 1 yet zlib returned a code
* indicating no progress was possible. This is unexpected.
*/
zlib_message(zlib, 1/*unexpected*/);
endrc = ZLIB_FATAL; /* stop processing */
break;
case Z_OK:
/* Zlib is supposed to have made progress: */
assert(zlib->z.avail_out == 0 || zlib->z.avail_in == 0);
continue;
case Z_STREAM_END:
/* This is the successful end. */
zlib->state = 3; /* end of stream */
endrc = ZLIB_STREAM_END;
break;
case Z_NEED_DICT:
zlib_message(zlib, 0/*stream error*/);
endrc = ZLIB_FATAL;
break;
case Z_DATA_ERROR:
/* The too far back error can be corrected, others cannot: */
if (zlib->z.msg != NULL &&
strcmp(zlib->z.msg, "invalid distance too far back") == 0)
{
endrc = ZLIB_TOO_FAR_BACK;
break;
}
/* FALL THROUGH */
default:
zlib_message(zlib, 0/*stream error*/);
endrc = ZLIB_FATAL;
break;
} /* switch (inflate rc) */
/* Control gets here when further output is not possible; endrc may
* still be ZLIB_OK if more input is required.
*/
break;
} /* for (output bytes) */
/* Keep a running count of output byte produced: */
zlib->uncompressed_digits = uarb_add32(zlib->uncompressed_bytes,
zlib->uncompressed_digits, out_bytes);
/* Keep going, the loop will terminate when endrc is no longer set to
* ZLIB_OK or all the input bytes have been consumed; meanwhile keep
* adding input bytes.
*/
assert(zlib->z.avail_in == 0 || endrc != ZLIB_OK);
in_bytes += 1 - zlib->z.avail_in;
} /* while (input bytes) */
assert(in_bytes == nbytes || endrc != ZLIB_OK);
/* Update the running total of input bytes consumed */
zlib->compressed_digits = uarb_add32(zlib->compressed_bytes,
zlib->compressed_digits, in_bytes - zlib->z.avail_in);
/* At the end of the stream update the chunk with the accumulated
* information if it is an improvement:
*/
if (endrc == ZLIB_STREAM_END && zlib->window_bits < zlib->ok_bits)
{
struct chunk *chunk = zlib->chunk;
chunk->uncompressed_digits = uarb_copy(chunk->uncompressed_bytes,
zlib->uncompressed_bytes, zlib->uncompressed_digits);
chunk->compressed_digits = uarb_copy(chunk->compressed_bytes,
zlib->compressed_bytes, zlib->compressed_digits);
chunk->rewrite_buffer[0] = zlib->header[0];
chunk->rewrite_buffer[1] = zlib->header[1];
if (zlib->window_bits != zlib->file_bits || zlib->cksum)
{
/* A rewrite is required */
chunk->rewrite_offset = zlib->rewrite_offset;
chunk->rewrite_length = 2;
}
else
{
chunk->rewrite_offset = 0;
chunk->rewrite_length = 0;
}
if (in_bytes < nbytes)
chunk_message(chunk, "extra compressed data");
zlib->extra_bytes = nbytes - in_bytes;
zlib->ok_bits = zlib->window_bits;
}
return endrc;
}
| 173,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: void RuntimeCustomBindings::GetExtensionViews(
const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 2)
return;
if (!args[0]->IsInt32() || !args[1]->IsString())
return;
int browser_window_id = args[0]->Int32Value();
std::string view_type_string =
base::ToUpperASCII(*v8::String::Utf8Value(args[1]));
ViewType view_type = VIEW_TYPE_INVALID;
if (view_type_string == kViewTypeBackgroundPage) {
view_type = VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
} else if (view_type_string == kViewTypeTabContents) {
view_type = VIEW_TYPE_TAB_CONTENTS;
} else if (view_type_string == kViewTypePopup) {
view_type = VIEW_TYPE_EXTENSION_POPUP;
} else if (view_type_string == kViewTypeExtensionDialog) {
view_type = VIEW_TYPE_EXTENSION_DIALOG;
} else if (view_type_string == kViewTypeAppWindow) {
view_type = VIEW_TYPE_APP_WINDOW;
} else if (view_type_string == kViewTypeLauncherPage) {
view_type = VIEW_TYPE_LAUNCHER_PAGE;
} else if (view_type_string == kViewTypePanel) {
view_type = VIEW_TYPE_PANEL;
} else if (view_type_string != kViewTypeAll) {
return;
}
std::string extension_id = context()->GetExtensionID();
if (extension_id.empty())
return;
std::vector<content::RenderFrame*> frames =
ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id,
view_type);
v8::Local<v8::Array> v8_views = v8::Array::New(args.GetIsolate());
int v8_index = 0;
for (content::RenderFrame* frame : frames) {
if (frame->GetWebFrame()->top() != frame->GetWebFrame())
continue;
v8::Local<v8::Context> context =
frame->GetWebFrame()->mainWorldScriptContext();
if (!context.IsEmpty()) {
v8::Local<v8::Value> window = context->Global();
DCHECK(!window.IsEmpty());
v8_views->Set(v8::Integer::New(args.GetIsolate(), v8_index++), window);
}
}
args.GetReturnValue().Set(v8_views);
}
Commit Message: Create array of extension views without side effects
BUG=608104
Review-Url: https://codereview.chromium.org/1935953002
Cr-Commit-Position: refs/heads/master@{#390961}
CWE ID: | void RuntimeCustomBindings::GetExtensionViews(
const v8::FunctionCallbackInfo<v8::Value>& args) {
if (args.Length() != 2)
return;
if (!args[0]->IsInt32() || !args[1]->IsString())
return;
int browser_window_id = args[0]->Int32Value();
std::string view_type_string =
base::ToUpperASCII(*v8::String::Utf8Value(args[1]));
ViewType view_type = VIEW_TYPE_INVALID;
if (view_type_string == kViewTypeBackgroundPage) {
view_type = VIEW_TYPE_EXTENSION_BACKGROUND_PAGE;
} else if (view_type_string == kViewTypeTabContents) {
view_type = VIEW_TYPE_TAB_CONTENTS;
} else if (view_type_string == kViewTypePopup) {
view_type = VIEW_TYPE_EXTENSION_POPUP;
} else if (view_type_string == kViewTypeExtensionDialog) {
view_type = VIEW_TYPE_EXTENSION_DIALOG;
} else if (view_type_string == kViewTypeAppWindow) {
view_type = VIEW_TYPE_APP_WINDOW;
} else if (view_type_string == kViewTypeLauncherPage) {
view_type = VIEW_TYPE_LAUNCHER_PAGE;
} else if (view_type_string == kViewTypePanel) {
view_type = VIEW_TYPE_PANEL;
} else if (view_type_string != kViewTypeAll) {
return;
}
std::string extension_id = context()->GetExtensionID();
if (extension_id.empty())
return;
std::vector<content::RenderFrame*> frames =
ExtensionFrameHelper::GetExtensionFrames(extension_id, browser_window_id,
view_type);
v8::Local<v8::Context> v8_context = args.GetIsolate()->GetCurrentContext();
v8::Local<v8::Array> v8_views = v8::Array::New(args.GetIsolate());
int v8_index = 0;
for (content::RenderFrame* frame : frames) {
if (frame->GetWebFrame()->top() != frame->GetWebFrame())
continue;
v8::Local<v8::Context> context =
frame->GetWebFrame()->mainWorldScriptContext();
if (!context.IsEmpty()) {
v8::Local<v8::Value> window = context->Global();
DCHECK(!window.IsEmpty());
v8::Maybe<bool> maybe =
v8_views->CreateDataProperty(v8_context, v8_index++, window);
DCHECK(maybe.IsJust() && maybe.FromJust());
}
}
args.GetReturnValue().Set(v8_views);
}
| 172,260 |
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 tcp_disconnect(struct sock *sk, int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
int err = 0;
int old_state = sk->sk_state;
if (old_state != TCP_CLOSE)
tcp_set_state(sk, TCP_CLOSE);
/* ABORT function of RFC793 */
if (old_state == TCP_LISTEN) {
inet_csk_listen_stop(sk);
} else if (unlikely(tp->repair)) {
sk->sk_err = ECONNABORTED;
} else if (tcp_need_reset(old_state) ||
(tp->snd_nxt != tp->write_seq &&
(1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
/* The last check adjusts for discrepancy of Linux wrt. RFC
* states
*/
tcp_send_active_reset(sk, gfp_any());
sk->sk_err = ECONNRESET;
} else if (old_state == TCP_SYN_SENT)
sk->sk_err = ECONNRESET;
tcp_clear_xmit_timers(sk);
__skb_queue_purge(&sk->sk_receive_queue);
tcp_write_queue_purge(sk);
tcp_fastopen_active_disable_ofo_check(sk);
skb_rbtree_purge(&tp->out_of_order_queue);
inet->inet_dport = 0;
if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
inet_reset_saddr(sk);
sk->sk_shutdown = 0;
sock_reset_flag(sk, SOCK_DONE);
tp->srtt_us = 0;
tp->write_seq += tp->max_window + 2;
if (tp->write_seq == 0)
tp->write_seq = 1;
icsk->icsk_backoff = 0;
tp->snd_cwnd = 2;
icsk->icsk_probes_out = 0;
tp->packets_out = 0;
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_cnt = 0;
tp->window_clamp = 0;
tcp_set_ca_state(sk, TCP_CA_Open);
tcp_clear_retrans(tp);
inet_csk_delack_init(sk);
tcp_init_send_head(sk);
memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
__sk_dst_reset(sk);
tcp_saved_syn_free(tp);
/* Clean up fastopen related fields */
tcp_free_fastopen_req(tp);
inet->defer_connect = 0;
WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
sk->sk_error_report(sk);
return err;
}
Commit Message: tcp: initialize rcv_mss to TCP_MIN_MSS instead of 0
When tcp_disconnect() is called, inet_csk_delack_init() sets
icsk->icsk_ack.rcv_mss to 0.
This could potentially cause tcp_recvmsg() => tcp_cleanup_rbuf() =>
__tcp_select_window() call path to have division by 0 issue.
So this patch initializes rcv_mss to TCP_MIN_MSS instead of 0.
Reported-by: Andrey Konovalov <[email protected]>
Signed-off-by: Wei Wang <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Signed-off-by: Neal Cardwell <[email protected]>
Signed-off-by: Yuchung Cheng <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-369 | int tcp_disconnect(struct sock *sk, int flags)
{
struct inet_sock *inet = inet_sk(sk);
struct inet_connection_sock *icsk = inet_csk(sk);
struct tcp_sock *tp = tcp_sk(sk);
int err = 0;
int old_state = sk->sk_state;
if (old_state != TCP_CLOSE)
tcp_set_state(sk, TCP_CLOSE);
/* ABORT function of RFC793 */
if (old_state == TCP_LISTEN) {
inet_csk_listen_stop(sk);
} else if (unlikely(tp->repair)) {
sk->sk_err = ECONNABORTED;
} else if (tcp_need_reset(old_state) ||
(tp->snd_nxt != tp->write_seq &&
(1 << old_state) & (TCPF_CLOSING | TCPF_LAST_ACK))) {
/* The last check adjusts for discrepancy of Linux wrt. RFC
* states
*/
tcp_send_active_reset(sk, gfp_any());
sk->sk_err = ECONNRESET;
} else if (old_state == TCP_SYN_SENT)
sk->sk_err = ECONNRESET;
tcp_clear_xmit_timers(sk);
__skb_queue_purge(&sk->sk_receive_queue);
tcp_write_queue_purge(sk);
tcp_fastopen_active_disable_ofo_check(sk);
skb_rbtree_purge(&tp->out_of_order_queue);
inet->inet_dport = 0;
if (!(sk->sk_userlocks & SOCK_BINDADDR_LOCK))
inet_reset_saddr(sk);
sk->sk_shutdown = 0;
sock_reset_flag(sk, SOCK_DONE);
tp->srtt_us = 0;
tp->write_seq += tp->max_window + 2;
if (tp->write_seq == 0)
tp->write_seq = 1;
icsk->icsk_backoff = 0;
tp->snd_cwnd = 2;
icsk->icsk_probes_out = 0;
tp->packets_out = 0;
tp->snd_ssthresh = TCP_INFINITE_SSTHRESH;
tp->snd_cwnd_cnt = 0;
tp->window_clamp = 0;
tcp_set_ca_state(sk, TCP_CA_Open);
tcp_clear_retrans(tp);
inet_csk_delack_init(sk);
/* Initialize rcv_mss to TCP_MIN_MSS to avoid division by 0
* issue in __tcp_select_window()
*/
icsk->icsk_ack.rcv_mss = TCP_MIN_MSS;
tcp_init_send_head(sk);
memset(&tp->rx_opt, 0, sizeof(tp->rx_opt));
__sk_dst_reset(sk);
tcp_saved_syn_free(tp);
/* Clean up fastopen related fields */
tcp_free_fastopen_req(tp);
inet->defer_connect = 0;
WARN_ON(inet->inet_num && !icsk->icsk_bind_hash);
sk->sk_error_report(sk);
return err;
}
| 167,772 |
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 l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
int transhdrlen = 4; /* zero session-id */
int ulen = len + transhdrlen;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (lsa) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6)
return -EAFNOSUPPORT;
daddr = &lsa->l2tp_addr;
if (np->sndflow) {
fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
lsa->l2tp_scope_id &&
ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL)
fl6.flowi6_oif = lsa->l2tp_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (opt == NULL)
opt = np->opt;
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = sk->sk_protocol;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
lock_sock(sk);
err = ip6_append_data(sk, ip_generic_getfrag, msg,
ulen, transhdrlen, hlimit, tclass, opt,
&fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = l2tp_ip6_push_pending_frames(sk);
release_sock(sk);
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
{
struct ipv6_txoptions opt_space;
DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name);
struct in6_addr *daddr, *final_p, final;
struct ipv6_pinfo *np = inet6_sk(sk);
struct ipv6_txoptions *opt_to_free = NULL;
struct ipv6_txoptions *opt = NULL;
struct ip6_flowlabel *flowlabel = NULL;
struct dst_entry *dst = NULL;
struct flowi6 fl6;
int addr_len = msg->msg_namelen;
int hlimit = -1;
int tclass = -1;
int dontfrag = -1;
int transhdrlen = 4; /* zero session-id */
int ulen = len + transhdrlen;
int err;
/* Rough check on arithmetic overflow,
better check is made in ip6_append_data().
*/
if (len > INT_MAX)
return -EMSGSIZE;
/* Mirror BSD error message compatibility */
if (msg->msg_flags & MSG_OOB)
return -EOPNOTSUPP;
/*
* Get and verify the address.
*/
memset(&fl6, 0, sizeof(fl6));
fl6.flowi6_mark = sk->sk_mark;
if (lsa) {
if (addr_len < SIN6_LEN_RFC2133)
return -EINVAL;
if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6)
return -EAFNOSUPPORT;
daddr = &lsa->l2tp_addr;
if (np->sndflow) {
fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK;
if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
}
/*
* Otherwise it will be difficult to maintain
* sk->sk_dst_cache.
*/
if (sk->sk_state == TCP_ESTABLISHED &&
ipv6_addr_equal(daddr, &sk->sk_v6_daddr))
daddr = &sk->sk_v6_daddr;
if (addr_len >= sizeof(struct sockaddr_in6) &&
lsa->l2tp_scope_id &&
ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL)
fl6.flowi6_oif = lsa->l2tp_scope_id;
} else {
if (sk->sk_state != TCP_ESTABLISHED)
return -EDESTADDRREQ;
daddr = &sk->sk_v6_daddr;
fl6.flowlabel = np->flow_label;
}
if (fl6.flowi6_oif == 0)
fl6.flowi6_oif = sk->sk_bound_dev_if;
if (msg->msg_controllen) {
opt = &opt_space;
memset(opt, 0, sizeof(struct ipv6_txoptions));
opt->tot_len = sizeof(struct ipv6_txoptions);
err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt,
&hlimit, &tclass, &dontfrag);
if (err < 0) {
fl6_sock_release(flowlabel);
return err;
}
if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) {
flowlabel = fl6_sock_lookup(sk, fl6.flowlabel);
if (flowlabel == NULL)
return -EINVAL;
}
if (!(opt->opt_nflen|opt->opt_flen))
opt = NULL;
}
if (!opt) {
opt = txopt_get(np);
opt_to_free = opt;
}
if (flowlabel)
opt = fl6_merge_options(&opt_space, flowlabel, opt);
opt = ipv6_fixup_options(&opt_space, opt);
fl6.flowi6_proto = sk->sk_protocol;
if (!ipv6_addr_any(daddr))
fl6.daddr = *daddr;
else
fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */
if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr))
fl6.saddr = np->saddr;
final_p = fl6_update_dst(&fl6, opt, &final);
if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr))
fl6.flowi6_oif = np->mcast_oif;
else if (!fl6.flowi6_oif)
fl6.flowi6_oif = np->ucast_oif;
security_sk_classify_flow(sk, flowi6_to_flowi(&fl6));
dst = ip6_dst_lookup_flow(sk, &fl6, final_p);
if (IS_ERR(dst)) {
err = PTR_ERR(dst);
goto out;
}
if (hlimit < 0)
hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst);
if (tclass < 0)
tclass = np->tclass;
if (dontfrag < 0)
dontfrag = np->dontfrag;
if (msg->msg_flags & MSG_CONFIRM)
goto do_confirm;
back_from_confirm:
lock_sock(sk);
err = ip6_append_data(sk, ip_generic_getfrag, msg,
ulen, transhdrlen, hlimit, tclass, opt,
&fl6, (struct rt6_info *)dst,
msg->msg_flags, dontfrag);
if (err)
ip6_flush_pending_frames(sk);
else if (!(msg->msg_flags & MSG_MORE))
err = l2tp_ip6_push_pending_frames(sk);
release_sock(sk);
done:
dst_release(dst);
out:
fl6_sock_release(flowlabel);
txopt_put(opt_to_free);
return err < 0 ? err : len;
do_confirm:
dst_confirm(dst);
if (!(msg->msg_flags & MSG_PROBE) || len)
goto back_from_confirm;
err = 0;
goto done;
}
| 167,344 |
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::didFocusOnControl()
{
element()->setFocus(true);
}
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::didFocusOnControl()
{
if (!containsFocusedShadowElement())
return;
element()->setFocus(true);
}
| 171,212 |
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 UnloadController::TabDetachedImpl(TabContents* contents) {
if (is_attempting_to_close_browser_)
ClearUnloadState(contents->web_contents(), false);
registrar_.Remove(
this,
content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::Source<content::WebContents>(contents->web_contents()));
}
Commit Message: Remove TabContents from TabStripModelObserver::TabDetachedAt.
BUG=107201
TEST=no visible change
Review URL: https://chromiumcodereview.appspot.com/11293205
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@167122 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void UnloadController::TabDetachedImpl(TabContents* contents) {
void UnloadController::TabDetachedImpl(content::WebContents* contents) {
if (is_attempting_to_close_browser_)
ClearUnloadState(contents, false);
registrar_.Remove(this,
content::NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
content::Source<content::WebContents>(contents));
}
| 171,520 |
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 mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns)
{
const char *userid = rock->userid;
int isadmin = rock->isadmin;
int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS);
char inbox[MAX_MAILBOX_BUFFER];
size_t inboxlen = 0;
size_t prefixlen, len;
size_t domainlen = 0;
size_t userlen = userid ? strlen(userid) : 0;
char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */
char commonpat[MAX_MAILBOX_BUFFER];
int r = 0;
int i;
const char *p;
if (patterns->count < 1) return 0; /* nothing to do */
for (i = 0; i < patterns->count; i++) {
glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep);
ptrarray_append(&rock->globs, g);
}
if (config_virtdomains && userid && (p = strchr(userid, '@'))) {
userlen = p - userid;
domainlen = strlen(p); /* includes separator */
snprintf(domainpat, sizeof(domainpat), "%s!", p+1);
}
else
domainpat[0] = '\0';
/* calculate the inbox (with trailing .INBOX. for later use) */
if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) ||
((p - userid) > (int)userlen)) &&
strlen(userid)+7 < MAX_MAILBOX_BUFFER) {
char *t, *tmpuser = NULL;
const char *inboxuser;
if (domainlen)
snprintf(inbox, sizeof(inbox), "%s!", userid+userlen+1);
if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) {
tmpuser = xmalloc(userlen);
memcpy(tmpuser, userid, userlen);
t = tmpuser + (p - userid);
while(t < (tmpuser + userlen)) {
if (*t == '.')
*t = '^';
t++;
}
inboxuser = tmpuser;
} else
inboxuser = userid;
snprintf(inbox+domainlen, sizeof(inbox)-domainlen,
"user.%.*s.INBOX.", (int)userlen, inboxuser);
free(tmpuser);
inboxlen = strlen(inbox) - 7;
}
else {
userid = 0;
}
/* Find the common search prefix of all patterns */
const char *firstpat = strarray_nth(patterns, 0);
for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) {
if (prefixlen >= MAX_MAILBOX_NAME) {
r = IMAP_MAILBOX_BADNAME;
goto done;
}
char c = firstpat[prefixlen];
for (i = 1; i < patterns->count; i++) {
const char *pat = strarray_nth(patterns, i);
if (pat[prefixlen] != c) break;
}
if (i < patterns->count) break;
if (c == '*' || c == '%' || c == '?') break;
commonpat[prefixlen] = c;
}
commonpat[prefixlen] = '\0';
if (patterns->count == 1) {
/* Skip pattern which matches shared namespace prefix */
if (!strcmp(firstpat+prefixlen, "%"))
rock->singlepercent = 2;
/* output prefix regardless */
if (!strcmp(firstpat+prefixlen, "*%"))
rock->singlepercent = 1;
}
/*
* Personal (INBOX) namespace (only if not admin)
*/
if (userid && !isadmin) {
/* first the INBOX */
rock->mb_category = MBNAME_INBOX;
r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
if (rock->namespace->isalt) {
/* do exact INBOX subs before resetting the namebuffer */
rock->mb_category = MBNAME_INBOXSUB;
r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
}
/* iterate through all the mailboxes under the user's inbox */
rock->mb_category = MBNAME_OWNER;
r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
/* "Alt Prefix" folders */
if (rock->namespace->isalt) {
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
rock->mb_category = MBNAME_ALTINBOX;
/* special case user.foo.INBOX. If we're singlepercent == 2, this could
return DONE, in which case we don't need to foreach the rest of the
altprefix space */
r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) goto skipalt;
if (r) goto done;
/* special case any other altprefix stuff */
rock->mb_category = MBNAME_ALTPREFIX;
r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL);
skipalt: /* we got a done, so skip out of the foreach early */
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
}
}
/*
* Other Users namespace
*
* If "Other Users*" can match pattern, search for those mailboxes next
*/
if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) {
len = strlen(rock->namespace->prefix[NAMESPACE_USER]);
if (len) len--; // trailing separator
if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) {
if (prefixlen < len) {
/* we match all users */
strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen);
}
else {
/* just those in this prefix */
strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen);
strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5);
}
rock->mb_category = MBNAME_OTHERUSER;
/* because of how domains work, with crossdomains or admin you can't prefix at all :( */
size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat);
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
r = mboxlist_find_category(rock, domainpat, thislen);
if (r) goto done;
}
}
/*
* Shared namespace
*
* search for all remaining mailboxes.
* just bother looking at the ones that have the same pattern prefix.
*/
if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) {
len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]);
if (len) len--; // trailing separator
if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) {
rock->mb_category = MBNAME_SHARED;
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
/* iterate through all the non-user folders on the server */
r = mboxlist_find_category(rock, domainpat, domainlen);
if (r) goto done;
}
}
/* finish with a reset call always */
r = (*rock->proc)(NULL, rock->procrock);
done:
for (i = 0; i < rock->globs.count; i++) {
glob *g = ptrarray_nth(&rock->globs, i);
glob_free(&g);
}
ptrarray_fini(&rock->globs);
return r;
}
Commit Message: mboxlist: fix uninitialised memory use where pattern is "Other Users"
CWE ID: CWE-20 | static int mboxlist_do_find(struct find_rock *rock, const strarray_t *patterns)
{
const char *userid = rock->userid;
int isadmin = rock->isadmin;
int crossdomains = config_getswitch(IMAPOPT_CROSSDOMAINS);
char inbox[MAX_MAILBOX_BUFFER];
size_t inboxlen = 0;
size_t prefixlen, len;
size_t domainlen = 0;
size_t userlen = userid ? strlen(userid) : 0;
char domainpat[MAX_MAILBOX_BUFFER]; /* do intra-domain fetches only */
char commonpat[MAX_MAILBOX_BUFFER];
int r = 0;
int i;
const char *p;
if (patterns->count < 1) return 0; /* nothing to do */
for (i = 0; i < patterns->count; i++) {
glob *g = glob_init(strarray_nth(patterns, i), rock->namespace->hier_sep);
ptrarray_append(&rock->globs, g);
}
if (config_virtdomains && userid && (p = strchr(userid, '@'))) {
userlen = p - userid;
domainlen = strlen(p); /* includes separator */
snprintf(domainpat, sizeof(domainpat), "%s!", p+1);
}
else
domainpat[0] = '\0';
/* calculate the inbox (with trailing .INBOX. for later use) */
if (userid && (!(p = strchr(userid, rock->namespace->hier_sep)) ||
((p - userid) > (int)userlen)) &&
strlen(userid)+7 < MAX_MAILBOX_BUFFER) {
char *t, *tmpuser = NULL;
const char *inboxuser;
if (domainlen)
snprintf(inbox, sizeof(inbox), "%s!", userid+userlen+1);
if (rock->namespace->hier_sep == '/' && (p = strchr(userid, '.'))) {
tmpuser = xmalloc(userlen);
memcpy(tmpuser, userid, userlen);
t = tmpuser + (p - userid);
while(t < (tmpuser + userlen)) {
if (*t == '.')
*t = '^';
t++;
}
inboxuser = tmpuser;
} else
inboxuser = userid;
snprintf(inbox+domainlen, sizeof(inbox)-domainlen,
"user.%.*s.INBOX.", (int)userlen, inboxuser);
free(tmpuser);
inboxlen = strlen(inbox) - 7;
}
else {
userid = 0;
}
/* Find the common search prefix of all patterns */
const char *firstpat = strarray_nth(patterns, 0);
for (prefixlen = 0; firstpat[prefixlen]; prefixlen++) {
if (prefixlen >= MAX_MAILBOX_NAME) {
r = IMAP_MAILBOX_BADNAME;
goto done;
}
char c = firstpat[prefixlen];
for (i = 1; i < patterns->count; i++) {
const char *pat = strarray_nth(patterns, i);
if (pat[prefixlen] != c) break;
}
if (i < patterns->count) break;
if (c == '*' || c == '%' || c == '?') break;
commonpat[prefixlen] = c;
}
commonpat[prefixlen] = '\0';
if (patterns->count == 1) {
/* Skip pattern which matches shared namespace prefix */
if (!strcmp(firstpat+prefixlen, "%"))
rock->singlepercent = 2;
/* output prefix regardless */
if (!strcmp(firstpat+prefixlen, "*%"))
rock->singlepercent = 1;
}
/*
* Personal (INBOX) namespace (only if not admin)
*/
if (userid && !isadmin) {
/* first the INBOX */
rock->mb_category = MBNAME_INBOX;
r = cyrusdb_forone(rock->db, inbox, inboxlen, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
if (rock->namespace->isalt) {
/* do exact INBOX subs before resetting the namebuffer */
rock->mb_category = MBNAME_INBOXSUB;
r = cyrusdb_foreach(rock->db, inbox, inboxlen+7, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
}
/* iterate through all the mailboxes under the user's inbox */
rock->mb_category = MBNAME_OWNER;
r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
/* "Alt Prefix" folders */
if (rock->namespace->isalt) {
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
rock->mb_category = MBNAME_ALTINBOX;
/* special case user.foo.INBOX. If we're singlepercent == 2, this could
return DONE, in which case we don't need to foreach the rest of the
altprefix space */
r = cyrusdb_forone(rock->db, inbox, inboxlen+6, &find_p, &find_cb, rock, NULL);
if (r == CYRUSDB_DONE) goto skipalt;
if (r) goto done;
/* special case any other altprefix stuff */
rock->mb_category = MBNAME_ALTPREFIX;
r = cyrusdb_foreach(rock->db, inbox, inboxlen+1, &find_p, &find_cb, rock, NULL);
skipalt: /* we got a done, so skip out of the foreach early */
if (r == CYRUSDB_DONE) r = 0;
if (r) goto done;
}
}
/*
* Other Users namespace
*
* If "Other Users*" can match pattern, search for those mailboxes next
*/
if (isadmin || rock->namespace->accessible[NAMESPACE_USER]) {
len = strlen(rock->namespace->prefix[NAMESPACE_USER]);
if (len) len--; // trailing separator
if (!strncmp(rock->namespace->prefix[NAMESPACE_USER], commonpat, MIN(len, prefixlen))) {
if (prefixlen <= len) {
/* we match all users */
strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen);
}
else {
/* just those in this prefix */
strlcpy(domainpat+domainlen, "user.", sizeof(domainpat)-domainlen);
strlcpy(domainpat+domainlen+5, commonpat+len+1, sizeof(domainpat)-domainlen-5);
}
rock->mb_category = MBNAME_OTHERUSER;
/* because of how domains work, with crossdomains or admin you can't prefix at all :( */
size_t thislen = (isadmin || crossdomains) ? 0 : strlen(domainpat);
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
r = mboxlist_find_category(rock, domainpat, thislen);
if (r) goto done;
}
}
/*
* Shared namespace
*
* search for all remaining mailboxes.
* just bother looking at the ones that have the same pattern prefix.
*/
if (isadmin || rock->namespace->accessible[NAMESPACE_SHARED]) {
len = strlen(rock->namespace->prefix[NAMESPACE_SHARED]);
if (len) len--; // trailing separator
if (!strncmp(rock->namespace->prefix[NAMESPACE_SHARED], commonpat, MIN(len, prefixlen))) {
rock->mb_category = MBNAME_SHARED;
/* reset the the namebuffer */
r = (*rock->proc)(NULL, rock->procrock);
if (r) goto done;
/* iterate through all the non-user folders on the server */
r = mboxlist_find_category(rock, domainpat, domainlen);
if (r) goto done;
}
}
/* finish with a reset call always */
r = (*rock->proc)(NULL, rock->procrock);
done:
for (i = 0; i < rock->globs.count; i++) {
glob *g = ptrarray_nth(&rock->globs, i);
glob_free(&g);
}
ptrarray_fini(&rock->globs);
return r;
}
| 167,757 |
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 ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
struct address_space *mapping = inode->i_mapping;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Write out all dirty pages to avoid race conditions
* Then release them.
*/
if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
ret = filemap_write_and_wait_range(mapping, offset,
offset + len - 1);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
mutex_lock(&inode->i_mutex);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
offset + len > i_size_read(inode)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags, mode);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/* Now release the pages and zero block aligned part of pages*/
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags, mode);
if (ret)
goto out_dio;
}
if (!partial_begin && !partial_end)
goto out_dio;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_dio;
}
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
Commit Message: ext4: fix races between page faults and hole punching
Currently, page faults and hole punching are completely unsynchronized.
This can result in page fault faulting in a page into a range that we
are punching after truncate_pagecache_range() has been called and thus
we can end up with a page mapped to disk blocks that will be shortly
freed. Filesystem corruption will shortly follow. Note that the same
race is avoided for truncate by checking page fault offset against
i_size but there isn't similar mechanism available for punching holes.
Fix the problem by creating new rw semaphore i_mmap_sem in inode and
grab it for writing over truncate, hole punching, and other functions
removing blocks from extent tree and for read over page faults. We
cannot easily use i_data_sem for this since that ranks below transaction
start and we need something ranking above it so that it can be held over
the whole truncate / hole punching operation. Also remove various
workarounds we had in the code to reduce race window when page fault
could have created pages with stale mapping information.
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Theodore Ts'o <[email protected]>
CWE ID: CWE-362 | static long ext4_zero_range(struct file *file, loff_t offset,
loff_t len, int mode)
{
struct inode *inode = file_inode(file);
handle_t *handle = NULL;
unsigned int max_blocks;
loff_t new_size = 0;
int ret = 0;
int flags;
int credits;
int partial_begin, partial_end;
loff_t start, end;
ext4_lblk_t lblk;
unsigned int blkbits = inode->i_blkbits;
trace_ext4_zero_range(inode, offset, len, mode);
if (!S_ISREG(inode->i_mode))
return -EINVAL;
/* Call ext4_force_commit to flush all data in case of data=journal. */
if (ext4_should_journal_data(inode)) {
ret = ext4_force_commit(inode->i_sb);
if (ret)
return ret;
}
/*
* Round up offset. This is not fallocate, we neet to zero out
* blocks, so convert interior block aligned part of the range to
* unwritten and possibly manually zero out unaligned parts of the
* range.
*/
start = round_up(offset, 1 << blkbits);
end = round_down((offset + len), 1 << blkbits);
if (start < offset || end > offset + len)
return -EINVAL;
partial_begin = offset & ((1 << blkbits) - 1);
partial_end = (offset + len) & ((1 << blkbits) - 1);
lblk = start >> blkbits;
max_blocks = (end >> blkbits);
if (max_blocks < lblk)
max_blocks = 0;
else
max_blocks -= lblk;
mutex_lock(&inode->i_mutex);
/*
* Indirect files do not support unwritten extnets
*/
if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
ret = -EOPNOTSUPP;
goto out_mutex;
}
if (!(mode & FALLOC_FL_KEEP_SIZE) &&
offset + len > i_size_read(inode)) {
new_size = offset + len;
ret = inode_newsize_ok(inode, new_size);
if (ret)
goto out_mutex;
}
flags = EXT4_GET_BLOCKS_CREATE_UNWRIT_EXT;
if (mode & FALLOC_FL_KEEP_SIZE)
flags |= EXT4_GET_BLOCKS_KEEP_SIZE;
/* Preallocate the range including the unaligned edges */
if (partial_begin || partial_end) {
ret = ext4_alloc_file_blocks(file,
round_down(offset, 1 << blkbits) >> blkbits,
(round_up((offset + len), 1 << blkbits) -
round_down(offset, 1 << blkbits)) >> blkbits,
new_size, flags, mode);
if (ret)
goto out_mutex;
}
/* Zero range excluding the unaligned edges */
if (max_blocks > 0) {
flags |= (EXT4_GET_BLOCKS_CONVERT_UNWRITTEN |
EXT4_EX_NOCACHE);
/* Wait all existing dio workers, newcomers will block on i_mutex */
ext4_inode_block_unlocked_dio(inode);
inode_dio_wait(inode);
/*
* Prevent page faults from reinstantiating pages we have
* released from page cache.
*/
down_write(&EXT4_I(inode)->i_mmap_sem);
/* Now release the pages and zero block aligned part of pages */
truncate_pagecache_range(inode, start, end - 1);
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
ret = ext4_alloc_file_blocks(file, lblk, max_blocks, new_size,
flags, mode);
up_write(&EXT4_I(inode)->i_mmap_sem);
if (ret)
goto out_dio;
}
if (!partial_begin && !partial_end)
goto out_dio;
/*
* In worst case we have to writeout two nonadjacent unwritten
* blocks and update the inode
*/
credits = (2 * ext4_ext_index_trans_blocks(inode, 2)) + 1;
if (ext4_should_journal_data(inode))
credits += 2;
handle = ext4_journal_start(inode, EXT4_HT_MISC, credits);
if (IS_ERR(handle)) {
ret = PTR_ERR(handle);
ext4_std_error(inode->i_sb, ret);
goto out_dio;
}
inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
if (new_size) {
ext4_update_inode_size(inode, new_size);
} else {
/*
* Mark that we allocate beyond EOF so the subsequent truncate
* can proceed even if the new size is the same as i_size.
*/
if ((offset + len) > i_size_read(inode))
ext4_set_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
}
ext4_mark_inode_dirty(handle, inode);
/* Zero out partial block at the edges of the range */
ret = ext4_zero_partial_blocks(handle, inode, offset, len);
if (file->f_flags & O_SYNC)
ext4_handle_sync(handle);
ext4_journal_stop(handle);
out_dio:
ext4_inode_resume_unlocked_dio(inode);
out_mutex:
mutex_unlock(&inode->i_mutex);
return ret;
}
| 167,485 |
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 inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct flowi6 fl6;
struct dst_entry *dst;
int res;
dst = inet6_csk_route_socket(sk, &fl6);
if (IS_ERR(dst)) {
sk->sk_err_soft = -PTR_ERR(dst);
sk->sk_route_caps = 0;
kfree_skb(skb);
return PTR_ERR(dst);
}
rcu_read_lock();
skb_dst_set_noref(skb, dst);
/* Restore final destination back after routing done */
fl6.daddr = sk->sk_v6_daddr;
res = ip6_xmit(sk, skb, &fl6, np->opt, np->tclass);
rcu_read_unlock();
return res;
}
Commit Message: ipv6: add complete rcu protection around np->opt
This patch addresses multiple problems :
UDP/RAW sendmsg() need to get a stable struct ipv6_txoptions
while socket is not locked : Other threads can change np->opt
concurrently. Dmitry posted a syzkaller
(http://github.com/google/syzkaller) program desmonstrating
use-after-free.
Starting with TCP/DCCP lockless listeners, tcp_v6_syn_recv_sock()
and dccp_v6_request_recv_sock() also need to use RCU protection
to dereference np->opt once (before calling ipv6_dup_options())
This patch adds full RCU protection to np->opt
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: Eric Dumazet <[email protected]>
Acked-by: Hannes Frederic Sowa <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-416 | int inet6_csk_xmit(struct sock *sk, struct sk_buff *skb, struct flowi *fl_unused)
{
struct ipv6_pinfo *np = inet6_sk(sk);
struct flowi6 fl6;
struct dst_entry *dst;
int res;
dst = inet6_csk_route_socket(sk, &fl6);
if (IS_ERR(dst)) {
sk->sk_err_soft = -PTR_ERR(dst);
sk->sk_route_caps = 0;
kfree_skb(skb);
return PTR_ERR(dst);
}
rcu_read_lock();
skb_dst_set_noref(skb, dst);
/* Restore final destination back after routing done */
fl6.daddr = sk->sk_v6_daddr;
res = ip6_xmit(sk, skb, &fl6, rcu_dereference(np->opt),
np->tclass);
rcu_read_unlock();
return res;
}
| 167,334 |
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_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu;
int exthdrlen;
int dst_exthdrlen;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
exthdrlen = (opt ? opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM)
sock_tx_timestamp(sk, &tx_flags);
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
cork->length += length;
if (length > mtu) {
int proto = sk->sk_protocol;
if (dontfrag && (proto == IPPROTO_UDP || proto == IPPROTO_RAW)){
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
if (proto == IPPROTO_UDP &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
}
if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (skb == NULL || skb_prev == NULL)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
np->pmtudisc ==
IPV6_PMTUDISC_PROBE);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = CHECKSUM_NONE;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
Commit Message: ipv6: udp packets following an UFO enqueued packet need also be handled by UFO
In the following scenario the socket is corked:
If the first UDP packet is larger then the mtu we try to append it to the
write queue via ip6_ufo_append_data. A following packet, which is smaller
than the mtu would be appended to the already queued up gso-skb via
plain ip6_append_data. This causes random memory corruptions.
In ip6_ufo_append_data we also have to be careful to not queue up the
same skb multiple times. So setup the gso frame only when no first skb
is available.
This also fixes a shortcoming where we add the current packet's length to
cork->length but return early because of a packet > mtu with dontfrag set
(instead of sutracting it again).
Found with trinity.
Cc: YOSHIFUJI Hideaki <[email protected]>
Signed-off-by: Hannes Frederic Sowa <[email protected]>
Reported-by: Dmitry Vyukov <[email protected]>
Signed-off-by: David S. Miller <[email protected]>
CWE ID: CWE-119 | int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to,
int offset, int len, int odd, struct sk_buff *skb),
void *from, int length, int transhdrlen,
int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6,
struct rt6_info *rt, unsigned int flags, int dontfrag)
{
struct inet_sock *inet = inet_sk(sk);
struct ipv6_pinfo *np = inet6_sk(sk);
struct inet_cork *cork;
struct sk_buff *skb, *skb_prev = NULL;
unsigned int maxfraglen, fragheaderlen, mtu;
int exthdrlen;
int dst_exthdrlen;
int hh_len;
int copy;
int err;
int offset = 0;
__u8 tx_flags = 0;
if (flags&MSG_PROBE)
return 0;
cork = &inet->cork.base;
if (skb_queue_empty(&sk->sk_write_queue)) {
/*
* setup for corking
*/
if (opt) {
if (WARN_ON(np->cork.opt))
return -EINVAL;
np->cork.opt = kzalloc(opt->tot_len, sk->sk_allocation);
if (unlikely(np->cork.opt == NULL))
return -ENOBUFS;
np->cork.opt->tot_len = opt->tot_len;
np->cork.opt->opt_flen = opt->opt_flen;
np->cork.opt->opt_nflen = opt->opt_nflen;
np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt,
sk->sk_allocation);
if (opt->dst0opt && !np->cork.opt->dst0opt)
return -ENOBUFS;
np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt,
sk->sk_allocation);
if (opt->dst1opt && !np->cork.opt->dst1opt)
return -ENOBUFS;
np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt,
sk->sk_allocation);
if (opt->hopopt && !np->cork.opt->hopopt)
return -ENOBUFS;
np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt,
sk->sk_allocation);
if (opt->srcrt && !np->cork.opt->srcrt)
return -ENOBUFS;
/* need source address above miyazawa*/
}
dst_hold(&rt->dst);
cork->dst = &rt->dst;
inet->cork.fl.u.ip6 = *fl6;
np->cork.hop_limit = hlimit;
np->cork.tclass = tclass;
if (rt->dst.flags & DST_XFRM_TUNNEL)
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(&rt->dst);
else
mtu = np->pmtudisc == IPV6_PMTUDISC_PROBE ?
rt->dst.dev->mtu : dst_mtu(rt->dst.path);
if (np->frag_size < mtu) {
if (np->frag_size)
mtu = np->frag_size;
}
cork->fragsize = mtu;
if (dst_allfrag(rt->dst.path))
cork->flags |= IPCORK_ALLFRAG;
cork->length = 0;
exthdrlen = (opt ? opt->opt_flen : 0);
length += exthdrlen;
transhdrlen += exthdrlen;
dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len;
} else {
rt = (struct rt6_info *)cork->dst;
fl6 = &inet->cork.fl.u.ip6;
opt = np->cork.opt;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
mtu = cork->fragsize;
}
hh_len = LL_RESERVED_SPACE(rt->dst.dev);
fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len +
(opt ? opt->opt_nflen : 0);
maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr);
if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) {
if (cork->length + length > sizeof(struct ipv6hdr) + IPV6_MAXPLEN - fragheaderlen) {
ipv6_local_error(sk, EMSGSIZE, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
}
/* For UDP, check if TX timestamp is enabled */
if (sk->sk_type == SOCK_DGRAM)
sock_tx_timestamp(sk, &tx_flags);
/*
* Let's try using as much space as possible.
* Use MTU if total length of the message fits into the MTU.
* Otherwise, we need to reserve fragment header and
* fragment alignment (= 8-15 octects, in total).
*
* Note that we may need to "move" the data from the tail of
* of the buffer to the new fragment when we split
* the message.
*
* FIXME: It may be fragmented into multiple chunks
* at once if non-fragmentable extension headers
* are too large.
* --yoshfuji
*/
if ((length > mtu) && dontfrag && (sk->sk_protocol == IPPROTO_UDP ||
sk->sk_protocol == IPPROTO_RAW)) {
ipv6_local_rxpmtu(sk, fl6, mtu-exthdrlen);
return -EMSGSIZE;
}
skb = skb_peek_tail(&sk->sk_write_queue);
cork->length += length;
if (((length > mtu) ||
(skb && skb_is_gso(skb))) &&
(sk->sk_protocol == IPPROTO_UDP) &&
(rt->dst.dev->features & NETIF_F_UFO)) {
err = ip6_ufo_append_data(sk, getfrag, from, length,
hh_len, fragheaderlen,
transhdrlen, mtu, flags, rt);
if (err)
goto error;
return 0;
}
if (!skb)
goto alloc_new_skb;
while (length > 0) {
/* Check if the remaining data fits into current packet. */
copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len;
if (copy < length)
copy = maxfraglen - skb->len;
if (copy <= 0) {
char *data;
unsigned int datalen;
unsigned int fraglen;
unsigned int fraggap;
unsigned int alloclen;
alloc_new_skb:
/* There's no room in the current skb */
if (skb)
fraggap = skb->len - maxfraglen;
else
fraggap = 0;
/* update mtu and maxfraglen if necessary */
if (skb == NULL || skb_prev == NULL)
ip6_append_data_mtu(&mtu, &maxfraglen,
fragheaderlen, skb, rt,
np->pmtudisc ==
IPV6_PMTUDISC_PROBE);
skb_prev = skb;
/*
* If remaining data exceeds the mtu,
* we know we need more fragment(s).
*/
datalen = length + fraggap;
if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen)
datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len;
if ((flags & MSG_MORE) &&
!(rt->dst.dev->features&NETIF_F_SG))
alloclen = mtu;
else
alloclen = datalen + fragheaderlen;
alloclen += dst_exthdrlen;
if (datalen != length + fraggap) {
/*
* this is not the last fragment, the trailer
* space is regarded as data space.
*/
datalen += rt->dst.trailer_len;
}
alloclen += rt->dst.trailer_len;
fraglen = datalen + fragheaderlen;
/*
* We just reserve space for fragment header.
* Note: this may be overallocation if the message
* (without MSG_MORE) fits into the MTU.
*/
alloclen += sizeof(struct frag_hdr);
if (transhdrlen) {
skb = sock_alloc_send_skb(sk,
alloclen + hh_len,
(flags & MSG_DONTWAIT), &err);
} else {
skb = NULL;
if (atomic_read(&sk->sk_wmem_alloc) <=
2 * sk->sk_sndbuf)
skb = sock_wmalloc(sk,
alloclen + hh_len, 1,
sk->sk_allocation);
if (unlikely(skb == NULL))
err = -ENOBUFS;
else {
/* Only the initial fragment
* is time stamped.
*/
tx_flags = 0;
}
}
if (skb == NULL)
goto error;
/*
* Fill in the control structures
*/
skb->protocol = htons(ETH_P_IPV6);
skb->ip_summed = CHECKSUM_NONE;
skb->csum = 0;
/* reserve for fragmentation and ipsec header */
skb_reserve(skb, hh_len + sizeof(struct frag_hdr) +
dst_exthdrlen);
if (sk->sk_type == SOCK_DGRAM)
skb_shinfo(skb)->tx_flags = tx_flags;
/*
* Find where to start putting bytes
*/
data = skb_put(skb, fraglen);
skb_set_network_header(skb, exthdrlen);
data += fragheaderlen;
skb->transport_header = (skb->network_header +
fragheaderlen);
if (fraggap) {
skb->csum = skb_copy_and_csum_bits(
skb_prev, maxfraglen,
data + transhdrlen, fraggap, 0);
skb_prev->csum = csum_sub(skb_prev->csum,
skb->csum);
data += fraggap;
pskb_trim_unique(skb_prev, maxfraglen);
}
copy = datalen - transhdrlen - fraggap;
if (copy < 0) {
err = -EINVAL;
kfree_skb(skb);
goto error;
} else if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) {
err = -EFAULT;
kfree_skb(skb);
goto error;
}
offset += copy;
length -= datalen - fraggap;
transhdrlen = 0;
exthdrlen = 0;
dst_exthdrlen = 0;
/*
* Put the packet on the pending queue
*/
__skb_queue_tail(&sk->sk_write_queue, skb);
continue;
}
if (copy > length)
copy = length;
if (!(rt->dst.dev->features&NETIF_F_SG)) {
unsigned int off;
off = skb->len;
if (getfrag(from, skb_put(skb, copy),
offset, copy, off, skb) < 0) {
__skb_trim(skb, off);
err = -EFAULT;
goto error;
}
} else {
int i = skb_shinfo(skb)->nr_frags;
struct page_frag *pfrag = sk_page_frag(sk);
err = -ENOMEM;
if (!sk_page_frag_refill(sk, pfrag))
goto error;
if (!skb_can_coalesce(skb, i, pfrag->page,
pfrag->offset)) {
err = -EMSGSIZE;
if (i == MAX_SKB_FRAGS)
goto error;
__skb_fill_page_desc(skb, i, pfrag->page,
pfrag->offset, 0);
skb_shinfo(skb)->nr_frags = ++i;
get_page(pfrag->page);
}
copy = min_t(int, copy, pfrag->size - pfrag->offset);
if (getfrag(from,
page_address(pfrag->page) + pfrag->offset,
offset, copy, skb->len, skb) < 0)
goto error_efault;
pfrag->offset += copy;
skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy);
skb->len += copy;
skb->data_len += copy;
skb->truesize += copy;
atomic_add(copy, &sk->sk_wmem_alloc);
}
offset += copy;
length -= copy;
}
return 0;
error_efault:
err = -EFAULT;
error:
cork->length -= length;
IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS);
return err;
}
| 165,987 |
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::GetPrevTimeCode() const
{
return m_prev;
}
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::GetPrevTimeCode() const
| 174,351 |
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 WebDevToolsAgentImpl::clearBrowserCache()
{
m_client->clearBrowserCache();
}
Commit Message: [4/4] Process clearBrowserCahce/cookies commands in browser.
BUG=366585
Review URL: https://codereview.chromium.org/251183005
git-svn-id: svn://svn.chromium.org/blink/trunk@172984 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: | void WebDevToolsAgentImpl::clearBrowserCache()
| 171,348 |
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 NTSTATUS fd_open_atomic(struct connection_struct *conn,
files_struct *fsp,
int flags,
mode_t mode,
bool *file_created)
{
NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
bool file_existed = VALID_STAT(fsp->fsp_name->st);
*file_created = false;
* We're not creating the file, just pass through.
*/
return fd_open(conn, fsp, flags, mode);
}
Commit Message:
CWE ID: CWE-835 | static NTSTATUS fd_open_atomic(struct connection_struct *conn,
files_struct *fsp,
int flags,
mode_t mode,
bool *file_created)
{
NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
NTSTATUS retry_status;
bool file_existed = VALID_STAT(fsp->fsp_name->st);
int curr_flags;
*file_created = false;
* We're not creating the file, just pass through.
*/
return fd_open(conn, fsp, flags, mode);
}
| 164,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: V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context,
Dispatcher* dispatcher)
: ObjectBackedNativeHandler(context),
context_(context),
dispatcher_(dispatcher) {
RouteFunction("GetAvailability",
base::Bind(&V8ContextNativeHandler::GetAvailability,
base::Unretained(this)));
RouteFunction("GetModuleSystem",
base::Bind(&V8ContextNativeHandler::GetModuleSystem,
base::Unretained(this)));
RouteFunction(
"RunWithNativesEnabledModuleSystem",
base::Bind(&V8ContextNativeHandler::RunWithNativesEnabledModuleSystem,
base::Unretained(this)));
}
Commit Message: Add a test that getModuleSystem() doesn't work cross origin
BUG=504011
[email protected]
[email protected]
Review URL: https://codereview.chromium.org/1241443004
Cr-Commit-Position: refs/heads/master@{#338663}
CWE ID: CWE-79 | V8ContextNativeHandler::V8ContextNativeHandler(ScriptContext* context,
Dispatcher* dispatcher)
: ObjectBackedNativeHandler(context),
context_(context),
dispatcher_(dispatcher) {
RouteFunction("GetAvailability",
base::Bind(&V8ContextNativeHandler::GetAvailability,
base::Unretained(this)));
RouteFunction("GetModuleSystem",
base::Bind(&V8ContextNativeHandler::GetModuleSystem,
base::Unretained(this)));
RouteFunction(
"RunWithNativesEnabled",
base::Bind(&V8ContextNativeHandler::RunWithNativesEnabled,
base::Unretained(this)));
}
| 171,949 |
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 record_and_restart(struct perf_event *event, unsigned long val,
struct pt_regs *regs, int nmi)
{
u64 period = event->hw.sample_period;
s64 prev, delta, left;
int record = 0;
if (event->hw.state & PERF_HES_STOPPED) {
write_pmc(event->hw.idx, 0);
return;
}
/* we don't have to worry about interrupts here */
prev = local64_read(&event->hw.prev_count);
delta = (val - prev) & 0xfffffffful;
local64_add(delta, &event->count);
/*
* See if the total period for this event has expired,
* and update for the next period.
*/
val = 0;
left = local64_read(&event->hw.period_left) - delta;
if (period) {
if (left <= 0) {
left += period;
if (left <= 0)
left = period;
record = 1;
event->hw.last_period = event->hw.sample_period;
}
if (left < 0x80000000LL)
val = 0x80000000LL - left;
}
write_pmc(event->hw.idx, val);
local64_set(&event->hw.prev_count, val);
local64_set(&event->hw.period_left, left);
perf_event_update_userpage(event);
/*
* Finally record data if requested.
*/
if (record) {
struct perf_sample_data data;
perf_sample_data_init(&data, 0);
data.period = event->hw.last_period;
if (perf_event_overflow(event, nmi, &data, regs))
fsl_emb_pmu_stop(event, 0);
}
}
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 | static void record_and_restart(struct perf_event *event, unsigned long val,
struct pt_regs *regs)
{
u64 period = event->hw.sample_period;
s64 prev, delta, left;
int record = 0;
if (event->hw.state & PERF_HES_STOPPED) {
write_pmc(event->hw.idx, 0);
return;
}
/* we don't have to worry about interrupts here */
prev = local64_read(&event->hw.prev_count);
delta = (val - prev) & 0xfffffffful;
local64_add(delta, &event->count);
/*
* See if the total period for this event has expired,
* and update for the next period.
*/
val = 0;
left = local64_read(&event->hw.period_left) - delta;
if (period) {
if (left <= 0) {
left += period;
if (left <= 0)
left = period;
record = 1;
event->hw.last_period = event->hw.sample_period;
}
if (left < 0x80000000LL)
val = 0x80000000LL - left;
}
write_pmc(event->hw.idx, val);
local64_set(&event->hw.prev_count, val);
local64_set(&event->hw.period_left, left);
perf_event_update_userpage(event);
/*
* Finally record data if requested.
*/
if (record) {
struct perf_sample_data data;
perf_sample_data_init(&data, 0);
data.period = event->hw.last_period;
if (perf_event_overflow(event, &data, regs))
fsl_emb_pmu_stop(event, 0);
}
}
| 165,791 |
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: gre_print_0(netdissect_options *ndo, const u_char *bp, u_int length)
{
u_int len = length;
uint16_t flags, prot;
/* 16 bits ND_TCHECKed in gre_print() */
flags = EXTRACT_16BITS(bp);
if (ndo->ndo_vflag)
ND_PRINT((ndo, ", Flags [%s]",
bittok2str(gre_flag_values,"none",flags)));
len -= 2;
bp += 2;
ND_TCHECK2(*bp, 2);
if (len < 2)
goto trunc;
prot = EXTRACT_16BITS(bp);
len -= 2;
bp += 2;
if ((flags & GRE_CP) | (flags & GRE_RP)) {
ND_TCHECK2(*bp, 2);
if (len < 2)
goto trunc;
if (ndo->ndo_vflag)
ND_PRINT((ndo, ", sum 0x%x", EXTRACT_16BITS(bp)));
bp += 2;
len -= 2;
ND_TCHECK2(*bp, 2);
if (len < 2)
goto trunc;
ND_PRINT((ndo, ", off 0x%x", EXTRACT_16BITS(bp)));
bp += 2;
len -= 2;
}
if (flags & GRE_KP) {
ND_TCHECK2(*bp, 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, ", key=0x%x", EXTRACT_32BITS(bp)));
bp += 4;
len -= 4;
}
if (flags & GRE_SP) {
ND_TCHECK2(*bp, 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, ", seq %u", EXTRACT_32BITS(bp)));
bp += 4;
len -= 4;
}
if (flags & GRE_RP) {
for (;;) {
uint16_t af;
uint8_t sreoff;
uint8_t srelen;
ND_TCHECK2(*bp, 4);
if (len < 4)
goto trunc;
af = EXTRACT_16BITS(bp);
sreoff = *(bp + 2);
srelen = *(bp + 3);
bp += 4;
len -= 4;
if (af == 0 && srelen == 0)
break;
if (!gre_sre_print(ndo, af, sreoff, srelen, bp, len))
goto trunc;
if (len < srelen)
goto trunc;
bp += srelen;
len -= srelen;
}
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", proto %s (0x%04x)",
tok2str(ethertype_values,"unknown",prot),
prot));
ND_PRINT((ndo, ", length %u",length));
if (ndo->ndo_vflag < 1)
ND_PRINT((ndo, ": ")); /* put in a colon as protocol demarc */
else
ND_PRINT((ndo, "\n\t")); /* if verbose go multiline */
switch (prot) {
case ETHERTYPE_IP:
ip_print(ndo, bp, len);
break;
case ETHERTYPE_IPV6:
ip6_print(ndo, bp, len);
break;
case ETHERTYPE_MPLS:
mpls_print(ndo, bp, len);
break;
case ETHERTYPE_IPX:
ipx_print(ndo, bp, len);
break;
case ETHERTYPE_ATALK:
atalk_print(ndo, bp, len);
break;
case ETHERTYPE_GRE_ISO:
isoclns_print(ndo, bp, len, ndo->ndo_snapend - bp);
break;
case ETHERTYPE_TEB:
ether_print(ndo, bp, len, ndo->ndo_snapend - bp, NULL, NULL);
break;
default:
ND_PRINT((ndo, "gre-proto-0x%x", prot));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
Commit Message: CVE-2017-12897/ISO CLNS: Use ND_TTEST() for the bounds checks in isoclns_print().
This fixes a buffer over-read discovered by Kamil Frankowicz.
Don't pass the remaining caplen - that's too hard to get right, and we
were getting it wrong in at least one case; just use ND_TTEST().
Add a test using the capture file supplied by the reporter(s).
CWE ID: CWE-125 | gre_print_0(netdissect_options *ndo, const u_char *bp, u_int length)
{
u_int len = length;
uint16_t flags, prot;
/* 16 bits ND_TCHECKed in gre_print() */
flags = EXTRACT_16BITS(bp);
if (ndo->ndo_vflag)
ND_PRINT((ndo, ", Flags [%s]",
bittok2str(gre_flag_values,"none",flags)));
len -= 2;
bp += 2;
ND_TCHECK2(*bp, 2);
if (len < 2)
goto trunc;
prot = EXTRACT_16BITS(bp);
len -= 2;
bp += 2;
if ((flags & GRE_CP) | (flags & GRE_RP)) {
ND_TCHECK2(*bp, 2);
if (len < 2)
goto trunc;
if (ndo->ndo_vflag)
ND_PRINT((ndo, ", sum 0x%x", EXTRACT_16BITS(bp)));
bp += 2;
len -= 2;
ND_TCHECK2(*bp, 2);
if (len < 2)
goto trunc;
ND_PRINT((ndo, ", off 0x%x", EXTRACT_16BITS(bp)));
bp += 2;
len -= 2;
}
if (flags & GRE_KP) {
ND_TCHECK2(*bp, 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, ", key=0x%x", EXTRACT_32BITS(bp)));
bp += 4;
len -= 4;
}
if (flags & GRE_SP) {
ND_TCHECK2(*bp, 4);
if (len < 4)
goto trunc;
ND_PRINT((ndo, ", seq %u", EXTRACT_32BITS(bp)));
bp += 4;
len -= 4;
}
if (flags & GRE_RP) {
for (;;) {
uint16_t af;
uint8_t sreoff;
uint8_t srelen;
ND_TCHECK2(*bp, 4);
if (len < 4)
goto trunc;
af = EXTRACT_16BITS(bp);
sreoff = *(bp + 2);
srelen = *(bp + 3);
bp += 4;
len -= 4;
if (af == 0 && srelen == 0)
break;
if (!gre_sre_print(ndo, af, sreoff, srelen, bp, len))
goto trunc;
if (len < srelen)
goto trunc;
bp += srelen;
len -= srelen;
}
}
if (ndo->ndo_eflag)
ND_PRINT((ndo, ", proto %s (0x%04x)",
tok2str(ethertype_values,"unknown",prot),
prot));
ND_PRINT((ndo, ", length %u",length));
if (ndo->ndo_vflag < 1)
ND_PRINT((ndo, ": ")); /* put in a colon as protocol demarc */
else
ND_PRINT((ndo, "\n\t")); /* if verbose go multiline */
switch (prot) {
case ETHERTYPE_IP:
ip_print(ndo, bp, len);
break;
case ETHERTYPE_IPV6:
ip6_print(ndo, bp, len);
break;
case ETHERTYPE_MPLS:
mpls_print(ndo, bp, len);
break;
case ETHERTYPE_IPX:
ipx_print(ndo, bp, len);
break;
case ETHERTYPE_ATALK:
atalk_print(ndo, bp, len);
break;
case ETHERTYPE_GRE_ISO:
isoclns_print(ndo, bp, len);
break;
case ETHERTYPE_TEB:
ether_print(ndo, bp, len, ndo->ndo_snapend - bp, NULL, NULL);
break;
default:
ND_PRINT((ndo, "gre-proto-0x%x", prot));
}
return;
trunc:
ND_PRINT((ndo, "%s", tstr));
}
| 167,946 |
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 LocalFrame::ShouldReuseDefaultView(const KURL& url) const {
if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument())
return false;
return GetDocument()->IsSecureTransitionTo(url);
}
Commit Message: Prevent sandboxed documents from reusing the default window
Bug: 377995
Change-Id: Iff66c6d214dfd0cb7ea9c80f83afeedfff703541
Reviewed-on: https://chromium-review.googlesource.com/983558
Commit-Queue: Andy Paicu <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Cr-Commit-Position: refs/heads/master@{#567663}
CWE ID: CWE-285 | bool LocalFrame::ShouldReuseDefaultView(const KURL& url) const {
bool LocalFrame::ShouldReuseDefaultView(
const KURL& url,
const ContentSecurityPolicy* csp) const {
if (!Loader().StateMachine()->IsDisplayingInitialEmptyDocument())
return false;
// The Window object should only be re-used if it is same-origin.
// Since sandboxing turns the origin into an opaque origin it needs to also
// be considered when deciding whether to reuse it.
// Spec:
// https://html.spec.whatwg.org/multipage/browsing-the-web.html#initialise-the-document-object
if (csp &&
SecurityContext::IsSandboxed(kSandboxOrigin, csp->GetSandboxMask())) {
return false;
}
return GetDocument()->IsSecureTransitionTo(url);
}
| 173,196 |
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 ape_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
APEContext *s = avctx->priv_data;
uint8_t *sample8;
int16_t *sample16;
int32_t *sample24;
int i, ch, ret;
int blockstodecode;
/* this should never be negative, but bad things will happen if it is, so
check it just to make sure. */
av_assert0(s->samples >= 0);
if(!s->samples){
uint32_t nblocks, offset;
int buf_size;
if (!avpkt->size) {
*got_frame_ptr = 0;
return 0;
}
if (avpkt->size < 8) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
buf_size = avpkt->size & ~3;
if (buf_size != avpkt->size) {
av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
"extra bytes at the end will be skipped.\n");
}
if (s->fileversion < 3950) // previous versions overread two bytes
buf_size += 2;
av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
if (!s->data)
return AVERROR(ENOMEM);
s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
buf_size >> 2);
memset(s->data + (buf_size & ~3), 0, buf_size & 3);
s->ptr = s->data;
s->data_end = s->data + buf_size;
nblocks = bytestream_get_be32(&s->ptr);
offset = bytestream_get_be32(&s->ptr);
if (s->fileversion >= 3900) {
if (offset > 3) {
av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
s->data = NULL;
return AVERROR_INVALIDDATA;
}
if (s->data_end - s->ptr < offset) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
s->ptr += offset;
} else {
if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
return ret;
if (s->fileversion > 3800)
skip_bits_long(&s->gb, offset * 8);
else
skip_bits_long(&s->gb, offset);
}
if (!nblocks || nblocks > INT_MAX) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
nblocks);
return AVERROR_INVALIDDATA;
}
/* Initialize the frame decoder */
if (init_frame_decoder(s) < 0) {
av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
return AVERROR_INVALIDDATA;
}
s->samples = nblocks;
}
if (!s->data) {
*got_frame_ptr = 0;
return avpkt->size;
}
blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
if (s->fileversion < 3930)
blockstodecode = s->samples;
/* reallocate decoded sample buffer if needed */
av_fast_malloc(&s->decoded_buffer, &s->decoded_size,
2 * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer));
if (!s->decoded_buffer)
return AVERROR(ENOMEM);
memset(s->decoded_buffer, 0, s->decoded_size);
s->decoded[0] = s->decoded_buffer;
s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
/* get output buffer */
frame->nb_samples = blockstodecode;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
s->error=0;
if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
ape_unpack_mono(s, blockstodecode);
else
ape_unpack_stereo(s, blockstodecode);
emms_c();
if (s->error) {
s->samples=0;
av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
return AVERROR_INVALIDDATA;
}
switch (s->bps) {
case 8:
for (ch = 0; ch < s->channels; ch++) {
sample8 = (uint8_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
}
break;
case 16:
for (ch = 0; ch < s->channels; ch++) {
sample16 = (int16_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample16++ = s->decoded[ch][i];
}
break;
case 24:
for (ch = 0; ch < s->channels; ch++) {
sample24 = (int32_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample24++ = s->decoded[ch][i] << 8;
}
break;
}
s->samples -= blockstodecode;
*got_frame_ptr = 1;
return !s->samples ? avpkt->size : 0;
}
Commit Message: avcodec/apedec: Fix integer overflow
Fixes: out of array access
Fixes: PoC.ape and others
Found-by: Bingchang, Liu@VARAS of IIE
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-125 | static int ape_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
AVFrame *frame = data;
const uint8_t *buf = avpkt->data;
APEContext *s = avctx->priv_data;
uint8_t *sample8;
int16_t *sample16;
int32_t *sample24;
int i, ch, ret;
int blockstodecode;
uint64_t decoded_buffer_size;
/* this should never be negative, but bad things will happen if it is, so
check it just to make sure. */
av_assert0(s->samples >= 0);
if(!s->samples){
uint32_t nblocks, offset;
int buf_size;
if (!avpkt->size) {
*got_frame_ptr = 0;
return 0;
}
if (avpkt->size < 8) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
buf_size = avpkt->size & ~3;
if (buf_size != avpkt->size) {
av_log(avctx, AV_LOG_WARNING, "packet size is not a multiple of 4. "
"extra bytes at the end will be skipped.\n");
}
if (s->fileversion < 3950) // previous versions overread two bytes
buf_size += 2;
av_fast_padded_malloc(&s->data, &s->data_size, buf_size);
if (!s->data)
return AVERROR(ENOMEM);
s->bdsp.bswap_buf((uint32_t *) s->data, (const uint32_t *) buf,
buf_size >> 2);
memset(s->data + (buf_size & ~3), 0, buf_size & 3);
s->ptr = s->data;
s->data_end = s->data + buf_size;
nblocks = bytestream_get_be32(&s->ptr);
offset = bytestream_get_be32(&s->ptr);
if (s->fileversion >= 3900) {
if (offset > 3) {
av_log(avctx, AV_LOG_ERROR, "Incorrect offset passed\n");
s->data = NULL;
return AVERROR_INVALIDDATA;
}
if (s->data_end - s->ptr < offset) {
av_log(avctx, AV_LOG_ERROR, "Packet is too small\n");
return AVERROR_INVALIDDATA;
}
s->ptr += offset;
} else {
if ((ret = init_get_bits8(&s->gb, s->ptr, s->data_end - s->ptr)) < 0)
return ret;
if (s->fileversion > 3800)
skip_bits_long(&s->gb, offset * 8);
else
skip_bits_long(&s->gb, offset);
}
if (!nblocks || nblocks > INT_MAX / 2 / sizeof(*s->decoded_buffer) - 8) {
av_log(avctx, AV_LOG_ERROR, "Invalid sample count: %"PRIu32".\n",
nblocks);
return AVERROR_INVALIDDATA;
}
/* Initialize the frame decoder */
if (init_frame_decoder(s) < 0) {
av_log(avctx, AV_LOG_ERROR, "Error reading frame header\n");
return AVERROR_INVALIDDATA;
}
s->samples = nblocks;
}
if (!s->data) {
*got_frame_ptr = 0;
return avpkt->size;
}
blockstodecode = FFMIN(s->blocks_per_loop, s->samples);
if (s->fileversion < 3930)
blockstodecode = s->samples;
/* reallocate decoded sample buffer if needed */
decoded_buffer_size = 2LL * FFALIGN(blockstodecode, 8) * sizeof(*s->decoded_buffer);
av_assert0(decoded_buffer_size <= INT_MAX);
av_fast_malloc(&s->decoded_buffer, &s->decoded_size, decoded_buffer_size);
if (!s->decoded_buffer)
return AVERROR(ENOMEM);
memset(s->decoded_buffer, 0, s->decoded_size);
s->decoded[0] = s->decoded_buffer;
s->decoded[1] = s->decoded_buffer + FFALIGN(blockstodecode, 8);
/* get output buffer */
frame->nb_samples = blockstodecode;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
s->error=0;
if ((s->channels == 1) || (s->frameflags & APE_FRAMECODE_PSEUDO_STEREO))
ape_unpack_mono(s, blockstodecode);
else
ape_unpack_stereo(s, blockstodecode);
emms_c();
if (s->error) {
s->samples=0;
av_log(avctx, AV_LOG_ERROR, "Error decoding frame\n");
return AVERROR_INVALIDDATA;
}
switch (s->bps) {
case 8:
for (ch = 0; ch < s->channels; ch++) {
sample8 = (uint8_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample8++ = (s->decoded[ch][i] + 0x80) & 0xff;
}
break;
case 16:
for (ch = 0; ch < s->channels; ch++) {
sample16 = (int16_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample16++ = s->decoded[ch][i];
}
break;
case 24:
for (ch = 0; ch < s->channels; ch++) {
sample24 = (int32_t *)frame->data[ch];
for (i = 0; i < blockstodecode; i++)
*sample24++ = s->decoded[ch][i] << 8;
}
break;
}
s->samples -= blockstodecode;
*got_frame_ptr = 1;
return !s->samples ? avpkt->size : 0;
}
| 168,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 ssize_t aio_setup_single_vector(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
struct iovec *iovec)
{
if (unlikely(!access_ok(!rw, buf, kiocb->ki_nbytes)))
return -EFAULT;
iovec->iov_base = buf;
iovec->iov_len = kiocb->ki_nbytes;
*nr_segs = 1;
return 0;
}
Commit Message: AIO: properly check iovec sizes
In Linus's tree, the iovec code has been reworked massively, but in
older kernels the AIO layer should be checking this before passing the
request on to other layers.
Many thanks to Ben Hawkes of Google Project Zero for pointing out the
issue.
Reported-by: Ben Hawkes <[email protected]>
Acked-by: Benjamin LaHaise <[email protected]>
Tested-by: Willy Tarreau <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static ssize_t aio_setup_single_vector(struct kiocb *kiocb,
int rw, char __user *buf,
unsigned long *nr_segs,
struct iovec *iovec)
{
size_t len = kiocb->ki_nbytes;
if (len > MAX_RW_COUNT)
len = MAX_RW_COUNT;
if (unlikely(!access_ok(!rw, buf, len)))
return -EFAULT;
iovec->iov_base = buf;
iovec->iov_len = len;
*nr_segs = 1;
return 0;
}
| 167,493 |
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 comps_mrtree_unite(COMPS_MRTree *rt1, COMPS_MRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it, *it2;
struct Pair {
COMPS_HSList * subnodes;
char * key;
char added;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
pair->added = 0;
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key =
malloc(sizeof(char)
* (strlen(((COMPS_MRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key+strlen(parent_pair->key),
((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_MRTreeData*)it->data)->key) +
1));
memcpy(pair->key, ((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_MRTreeData*)it->data)->data->first != NULL) {
for (it2 = ((COMPS_MRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
comps_mrtree_set(rt1, pair->key, it2->data);
}
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
/* current node hasn't data */
} else {
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
Commit Message: Fix UAF in comps_objmrtree_unite function
The added field is not used at all in many places and it is probably the
left-over of some copy-paste.
CWE ID: CWE-416 | void comps_mrtree_unite(COMPS_MRTree *rt1, COMPS_MRTree *rt2) {
COMPS_HSList *tmplist, *tmp_subnodes;
COMPS_HSListItem *it, *it2;
struct Pair {
COMPS_HSList * subnodes;
char * key;
} *pair, *parent_pair;
pair = malloc(sizeof(struct Pair));
pair->subnodes = rt2->subnodes;
pair->key = NULL;
tmplist = comps_hslist_create();
comps_hslist_init(tmplist, NULL, NULL, &free);
comps_hslist_append(tmplist, pair, 0);
while (tmplist->first != NULL) {
it = tmplist->first;
comps_hslist_remove(tmplist, tmplist->first);
tmp_subnodes = ((struct Pair*)it->data)->subnodes;
parent_pair = (struct Pair*) it->data;
free(it);
for (it = tmp_subnodes->first; it != NULL; it=it->next) {
pair = malloc(sizeof(struct Pair));
pair->subnodes = ((COMPS_MRTreeData*)it->data)->subnodes;
if (parent_pair->key != NULL) {
pair->key =
malloc(sizeof(char)
* (strlen(((COMPS_MRTreeData*)it->data)->key)
+ strlen(parent_pair->key) + 1));
memcpy(pair->key, parent_pair->key,
sizeof(char) * strlen(parent_pair->key));
memcpy(pair->key+strlen(parent_pair->key),
((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
} else {
pair->key = malloc(sizeof(char)*
(strlen(((COMPS_MRTreeData*)it->data)->key) +
1));
memcpy(pair->key, ((COMPS_MRTreeData*)it->data)->key,
sizeof(char)*(strlen(((COMPS_MRTreeData*)it->data)->key)+1));
}
/* current node has data */
if (((COMPS_MRTreeData*)it->data)->data->first != NULL) {
for (it2 = ((COMPS_MRTreeData*)it->data)->data->first;
it2 != NULL; it2 = it2->next) {
comps_mrtree_set(rt1, pair->key, it2->data);
}
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
/* current node hasn't data */
} else {
if (((COMPS_MRTreeData*)it->data)->subnodes->first) {
comps_hslist_append(tmplist, pair, 0);
} else {
free(pair->key);
free(pair);
}
}
}
free(parent_pair->key);
free(parent_pair);
}
comps_hslist_destroy(&tmplist);
}
| 169,750 |
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 SoftAVC::onQueueFilled(OMX_U32 portIndex) {
UNUSED(portIndex);
if (mSignalledError) {
return;
}
if (mOutputPortSettingsChange != NONE) {
return;
}
if (NULL == mCodecCtx) {
if (OK != initDecoder()) {
ALOGE("Failed to initialize decoder");
notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
mSignalledError = true;
return;
}
}
if (outputBufferWidth() != mStride) {
/* Set the run-time (dynamic) parameters */
mStride = outputBufferWidth();
setParams(mStride);
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
/* If input EOS is seen and decoder is not in flush mode,
* set the decoder in flush mode.
* There can be a case where EOS is sent along with last picture data
* In that case, only after decoding that input data, decoder has to be
* put in flush. This case is handled here */
if (mReceivedEOS && !mIsInFlush) {
setFlushMode();
}
while (!outQueue.empty()) {
BufferInfo *inInfo;
OMX_BUFFERHEADERTYPE *inHeader;
BufferInfo *outInfo;
OMX_BUFFERHEADERTYPE *outHeader;
size_t timeStampIx;
inInfo = NULL;
inHeader = NULL;
if (!mIsInFlush) {
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
} else {
break;
}
}
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
outHeader->nTimeStamp = 0;
outHeader->nOffset = 0;
if (inHeader != NULL) {
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
if (!(inHeader->nFlags & OMX_BUFFERFLAG_EOS)) {
continue;
}
mReceivedEOS = true;
inHeader = NULL;
setFlushMode();
} else if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mReceivedEOS = true;
}
}
/* Get a free slot in timestamp array to hold input timestamp */
{
size_t i;
timeStampIx = 0;
for (i = 0; i < MAX_TIME_STAMPS; i++) {
if (!mTimeStampsValid[i]) {
timeStampIx = i;
break;
}
}
if (inHeader != NULL) {
mTimeStampsValid[timeStampIx] = true;
mTimeStamps[timeStampIx] = inHeader->nTimeStamp;
}
}
{
ivd_video_decode_ip_t s_dec_ip;
ivd_video_decode_op_t s_dec_op;
WORD32 timeDelay, timeTaken;
size_t sizeY, sizeUV;
setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx);
DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes);
GETTIME(&mTimeStart, NULL);
/* Compute time elapsed between end of previous decode()
* to start of current decode() */
TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
IV_API_CALL_STATUS_T status;
status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
bool unsupportedResolution =
(IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED == (s_dec_op.u4_error_code & 0xFF));
/* Check for unsupported dimensions */
if (unsupportedResolution) {
ALOGE("Unsupported resolution : %dx%d", mWidth, mHeight);
notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
mSignalledError = true;
return;
}
bool allocationFailed = (IVD_MEM_ALLOC_FAILED == (s_dec_op.u4_error_code & 0xFF));
if (allocationFailed) {
ALOGE("Allocation failure in decoder");
notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
mSignalledError = true;
return;
}
bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF));
GETTIME(&mTimeEnd, NULL);
/* Compute time taken for decode() */
TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
PRINT_TIME("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
s_dec_op.u4_num_bytes_consumed);
if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) {
mFlushNeeded = true;
}
if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) {
/* If the input did not contain picture data, then ignore
* the associated timestamp */
mTimeStampsValid[timeStampIx] = false;
}
if (mChangingResolution && !s_dec_op.u4_output_present) {
mChangingResolution = false;
resetDecoder();
resetPlugin();
continue;
}
if (resChanged) {
mChangingResolution = true;
if (mFlushNeeded) {
setFlushMode();
}
continue;
}
if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) {
uint32_t width = s_dec_op.u4_pic_wd;
uint32_t height = s_dec_op.u4_pic_ht;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
resetDecoder();
return;
}
}
if (s_dec_op.u4_output_present) {
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts];
mTimeStampsValid[s_dec_op.u4_ts] = false;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
} else {
/* If in flush mode and no output is returned by the codec,
* then come out of flush mode */
mIsInFlush = false;
/* If EOS was recieved on input port and there is no output
* from the codec, then signal EOS on output port */
if (mReceivedEOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags |= OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
resetPlugin();
}
}
}
if (inHeader != NULL) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
}
Commit Message: codecs: check OMX buffer size before use in (avc|hevc|mpeg2)dec
Bug: 27833616
Change-Id: Ic4045a3f56f53b08d0b1264b2a91b8f43e91b738
(cherry picked from commit 87fdee0bc9e3ac4d2a88ef0a8e150cfdf08c161d)
CWE ID: CWE-20 | void SoftAVC::onQueueFilled(OMX_U32 portIndex) {
UNUSED(portIndex);
if (mSignalledError) {
return;
}
if (mOutputPortSettingsChange != NONE) {
return;
}
if (NULL == mCodecCtx) {
if (OK != initDecoder()) {
ALOGE("Failed to initialize decoder");
notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
mSignalledError = true;
return;
}
}
if (outputBufferWidth() != mStride) {
/* Set the run-time (dynamic) parameters */
mStride = outputBufferWidth();
setParams(mStride);
}
List<BufferInfo *> &inQueue = getPortQueue(kInputPortIndex);
List<BufferInfo *> &outQueue = getPortQueue(kOutputPortIndex);
/* If input EOS is seen and decoder is not in flush mode,
* set the decoder in flush mode.
* There can be a case where EOS is sent along with last picture data
* In that case, only after decoding that input data, decoder has to be
* put in flush. This case is handled here */
if (mReceivedEOS && !mIsInFlush) {
setFlushMode();
}
while (!outQueue.empty()) {
BufferInfo *inInfo;
OMX_BUFFERHEADERTYPE *inHeader;
BufferInfo *outInfo;
OMX_BUFFERHEADERTYPE *outHeader;
size_t timeStampIx;
inInfo = NULL;
inHeader = NULL;
if (!mIsInFlush) {
if (!inQueue.empty()) {
inInfo = *inQueue.begin();
inHeader = inInfo->mHeader;
if (inHeader == NULL) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
continue;
}
} else {
break;
}
}
outInfo = *outQueue.begin();
outHeader = outInfo->mHeader;
outHeader->nFlags = 0;
outHeader->nTimeStamp = 0;
outHeader->nOffset = 0;
if (inHeader != NULL) {
if (inHeader->nFilledLen == 0) {
inQueue.erase(inQueue.begin());
inInfo->mOwnedByUs = false;
notifyEmptyBufferDone(inHeader);
if (!(inHeader->nFlags & OMX_BUFFERFLAG_EOS)) {
continue;
}
mReceivedEOS = true;
inHeader = NULL;
setFlushMode();
} else if (inHeader->nFlags & OMX_BUFFERFLAG_EOS) {
mReceivedEOS = true;
}
}
/* Get a free slot in timestamp array to hold input timestamp */
{
size_t i;
timeStampIx = 0;
for (i = 0; i < MAX_TIME_STAMPS; i++) {
if (!mTimeStampsValid[i]) {
timeStampIx = i;
break;
}
}
if (inHeader != NULL) {
mTimeStampsValid[timeStampIx] = true;
mTimeStamps[timeStampIx] = inHeader->nTimeStamp;
}
}
{
ivd_video_decode_ip_t s_dec_ip;
ivd_video_decode_op_t s_dec_op;
WORD32 timeDelay, timeTaken;
size_t sizeY, sizeUV;
if (!setDecodeArgs(&s_dec_ip, &s_dec_op, inHeader, outHeader, timeStampIx)) {
ALOGE("Decoder arg setup failed");
notify(OMX_EventError, OMX_ErrorUndefined, 0, NULL);
mSignalledError = true;
return;
}
DUMP_TO_FILE(mInFile, s_dec_ip.pv_stream_buffer, s_dec_ip.u4_num_Bytes);
GETTIME(&mTimeStart, NULL);
/* Compute time elapsed between end of previous decode()
* to start of current decode() */
TIME_DIFF(mTimeEnd, mTimeStart, timeDelay);
IV_API_CALL_STATUS_T status;
status = ivdec_api_function(mCodecCtx, (void *)&s_dec_ip, (void *)&s_dec_op);
bool unsupportedResolution =
(IVD_STREAM_WIDTH_HEIGHT_NOT_SUPPORTED == (s_dec_op.u4_error_code & 0xFF));
/* Check for unsupported dimensions */
if (unsupportedResolution) {
ALOGE("Unsupported resolution : %dx%d", mWidth, mHeight);
notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
mSignalledError = true;
return;
}
bool allocationFailed = (IVD_MEM_ALLOC_FAILED == (s_dec_op.u4_error_code & 0xFF));
if (allocationFailed) {
ALOGE("Allocation failure in decoder");
notify(OMX_EventError, OMX_ErrorUnsupportedSetting, 0, NULL);
mSignalledError = true;
return;
}
bool resChanged = (IVD_RES_CHANGED == (s_dec_op.u4_error_code & 0xFF));
GETTIME(&mTimeEnd, NULL);
/* Compute time taken for decode() */
TIME_DIFF(mTimeStart, mTimeEnd, timeTaken);
PRINT_TIME("timeTaken=%6d delay=%6d numBytes=%6d", timeTaken, timeDelay,
s_dec_op.u4_num_bytes_consumed);
if (s_dec_op.u4_frame_decoded_flag && !mFlushNeeded) {
mFlushNeeded = true;
}
if ((inHeader != NULL) && (1 != s_dec_op.u4_frame_decoded_flag)) {
/* If the input did not contain picture data, then ignore
* the associated timestamp */
mTimeStampsValid[timeStampIx] = false;
}
if (mChangingResolution && !s_dec_op.u4_output_present) {
mChangingResolution = false;
resetDecoder();
resetPlugin();
continue;
}
if (resChanged) {
mChangingResolution = true;
if (mFlushNeeded) {
setFlushMode();
}
continue;
}
if ((0 < s_dec_op.u4_pic_wd) && (0 < s_dec_op.u4_pic_ht)) {
uint32_t width = s_dec_op.u4_pic_wd;
uint32_t height = s_dec_op.u4_pic_ht;
bool portWillReset = false;
handlePortSettingsChange(&portWillReset, width, height);
if (portWillReset) {
resetDecoder();
return;
}
}
if (s_dec_op.u4_output_present) {
outHeader->nFilledLen = (outputBufferWidth() * outputBufferHeight() * 3) / 2;
outHeader->nTimeStamp = mTimeStamps[s_dec_op.u4_ts];
mTimeStampsValid[s_dec_op.u4_ts] = false;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
} else {
/* If in flush mode and no output is returned by the codec,
* then come out of flush mode */
mIsInFlush = false;
/* If EOS was recieved on input port and there is no output
* from the codec, then signal EOS on output port */
if (mReceivedEOS) {
outHeader->nFilledLen = 0;
outHeader->nFlags |= OMX_BUFFERFLAG_EOS;
outInfo->mOwnedByUs = false;
outQueue.erase(outQueue.begin());
outInfo = NULL;
notifyFillBufferDone(outHeader);
outHeader = NULL;
resetPlugin();
}
}
}
if (inHeader != NULL) {
inInfo->mOwnedByUs = false;
inQueue.erase(inQueue.begin());
inInfo = NULL;
notifyEmptyBufferDone(inHeader);
inHeader = NULL;
}
}
}
| 174,179 |
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 GpuProcessHost::EstablishChannelError(
const EstablishChannelCallback& callback,
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle renderer_process_for_gpu,
const content::GPUInfo& gpu_info) {
callback.Run(channel_handle, renderer_process_for_gpu, gpu_info);
}
Commit Message: Convert plugin and GPU process to brokered handle duplication.
BUG=119250
Review URL: https://chromiumcodereview.appspot.com/9958034
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@132303 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: | void GpuProcessHost::EstablishChannelError(
const EstablishChannelCallback& callback,
const IPC::ChannelHandle& channel_handle,
base::ProcessHandle renderer_process_for_gpu,
const content::GPUInfo& gpu_info) {
callback.Run(channel_handle, gpu_info);
}
| 170,920 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.