instruction
stringclasses 1
value | input
stringlengths 90
9.34k
| output
stringlengths 16
15.4k
| __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. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: LockScreenMediaControlsView::LockScreenMediaControlsView(
service_manager::Connector* connector,
const Callbacks& callbacks)
: connector_(connector),
hide_controls_timer_(new base::OneShotTimer()),
media_controls_enabled_(callbacks.media_controls_enabled),
hide_media_controls_(callbacks.hide_media_controls),
show_media_controls_(callbacks.show_media_controls) {
DCHECK(callbacks.media_controls_enabled);
DCHECK(callbacks.hide_media_controls);
DCHECK(callbacks.show_media_controls);
Shell::Get()->media_controller()->SetMediaControlsDismissed(false);
middle_spacing_ = std::make_unique<NonAccessibleView>();
middle_spacing_->set_owned_by_client();
set_notify_enter_exit_on_child(true);
contents_view_ = AddChildView(std::make_unique<views::View>());
contents_view_->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical));
contents_view_->SetBackground(views::CreateRoundedRectBackground(
kMediaControlsBackground, kMediaControlsCornerRadius));
contents_view_->SetPaintToLayer(); // Needed for opacity animation.
contents_view_->layer()->SetFillsBoundsOpaquely(false);
auto close_button_row = std::make_unique<NonAccessibleView>();
views::GridLayout* close_button_layout =
close_button_row->SetLayoutManager(std::make_unique<views::GridLayout>());
views::ColumnSet* columns = close_button_layout->AddColumnSet(0);
columns->AddPaddingColumn(0, kCloseButtonOffset);
columns->AddColumn(views::GridLayout::CENTER, views::GridLayout::CENTER, 0,
views::GridLayout::USE_PREF, 0, 0);
close_button_layout->StartRowWithPadding(
0, 0, 0, 5 /* padding between close button and top of view */);
auto close_button = CreateVectorImageButton(this);
SetImageFromVectorIcon(close_button.get(), vector_icons::kCloseRoundedIcon,
kCloseButtonIconSize, gfx::kGoogleGrey700);
close_button->SetPreferredSize(kCloseButtonSize);
close_button->SetFocusBehavior(View::FocusBehavior::ALWAYS);
base::string16 close_button_label(
l10n_util::GetStringUTF16(IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_CLOSE));
close_button->SetAccessibleName(close_button_label);
close_button_ = close_button_layout->AddView(std::move(close_button));
close_button_->SetVisible(false);
contents_view_->AddChildView(std::move(close_button_row));
header_row_ =
contents_view_->AddChildView(std::make_unique<MediaControlsHeaderView>());
auto session_artwork = std::make_unique<views::ImageView>();
session_artwork->SetPreferredSize(
gfx::Size(kArtworkViewWidth, kArtworkViewHeight));
session_artwork->SetBorder(views::CreateEmptyBorder(kArtworkInsets));
session_artwork_ = contents_view_->AddChildView(std::move(session_artwork));
progress_ = contents_view_->AddChildView(
std::make_unique<media_message_center::MediaControlsProgressView>(
base::BindRepeating(&LockScreenMediaControlsView::SeekTo,
base::Unretained(this))));
auto button_row = std::make_unique<NonAccessibleView>();
auto* button_row_layout =
button_row->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, kButtonRowInsets,
kMediaButtonRowSeparator));
button_row_layout->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kCenter);
button_row_layout->set_main_axis_alignment(
views::BoxLayout::MainAxisAlignment::kCenter);
button_row->SetPreferredSize(kMediaControlsButtonRowSize);
button_row_ = contents_view_->AddChildView(std::move(button_row));
CreateMediaButton(
kChangeTrackIconSize, MediaSessionAction::kPreviousTrack,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PREVIOUS_TRACK));
CreateMediaButton(
kSeekingIconsSize, MediaSessionAction::kSeekBackward,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_BACKWARD));
auto play_pause_button = views::CreateVectorToggleImageButton(this);
play_pause_button->set_tag(static_cast<int>(MediaSessionAction::kPause));
play_pause_button->SetPreferredSize(kMediaButtonSize);
play_pause_button->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
play_pause_button->SetTooltipText(l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PAUSE));
play_pause_button->SetToggledTooltipText(l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PLAY));
play_pause_button_ = button_row_->AddChildView(std::move(play_pause_button));
views::SetImageFromVectorIcon(
play_pause_button_,
GetVectorIconForMediaAction(MediaSessionAction::kPause),
kPlayPauseIconSize, kMediaButtonColor);
views::SetToggledImageFromVectorIcon(
play_pause_button_,
GetVectorIconForMediaAction(MediaSessionAction::kPlay),
kPlayPauseIconSize, kMediaButtonColor);
CreateMediaButton(
kSeekingIconsSize, MediaSessionAction::kSeekForward,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_FORWARD));
CreateMediaButton(kChangeTrackIconSize, MediaSessionAction::kNextTrack,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_NEXT_TRACK));
MediaSessionMetadataChanged(base::nullopt);
MediaSessionPositionChanged(base::nullopt);
MediaControllerImageChanged(
media_session::mojom::MediaSessionImageType::kSourceIcon, SkBitmap());
SetArtwork(base::nullopt);
if (!connector_)
return;
mojo::Remote<media_session::mojom::MediaControllerManager>
controller_manager_remote;
connector_->Connect(media_session::mojom::kServiceName,
controller_manager_remote.BindNewPipeAndPassReceiver());
controller_manager_remote->CreateActiveMediaController(
media_controller_remote_.BindNewPipeAndPassReceiver());
media_controller_remote_->AddObserver(
observer_receiver_.BindNewPipeAndPassRemote());
media_controller_remote_->ObserveImages(
media_session::mojom::MediaSessionImageType::kArtwork,
kMinimumArtworkSize, kDesiredArtworkSize,
artwork_observer_receiver_.BindNewPipeAndPassRemote());
media_controller_remote_->ObserveImages(
media_session::mojom::MediaSessionImageType::kSourceIcon,
kMinimumIconSize, kDesiredIconSize,
icon_observer_receiver_.BindNewPipeAndPassRemote());
}
Commit Message: [Lock Screen Media Controls] Tweak UI based on new mocks
This CL rearranges the different components of the CrOS lock screen
media controls based on the newest mocks. This involves resizing most
of the child views and their spacings. The artwork was also resized
and re-positioned. Additionally, the close button was moved from the
main view to the header row child view.
Artist and title data about the current session will eventually be
placed to the right of the artwork, but right now this space is empty.
See the bug for before and after pictures.
Bug: 991647
Change-Id: I7b97f31982ccf2912bd2564d5241bfd849d21d92
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1746554
Reviewed-by: Xiyuan Xia <[email protected]>
Reviewed-by: Becca Hughes <[email protected]>
Commit-Queue: Mia Bergeron <[email protected]>
Cr-Commit-Position: refs/heads/master@{#686253}
CWE ID: CWE-200 | LockScreenMediaControlsView::LockScreenMediaControlsView(
service_manager::Connector* connector,
const Callbacks& callbacks)
: connector_(connector),
hide_controls_timer_(new base::OneShotTimer()),
media_controls_enabled_(callbacks.media_controls_enabled),
hide_media_controls_(callbacks.hide_media_controls),
show_media_controls_(callbacks.show_media_controls) {
DCHECK(callbacks.media_controls_enabled);
DCHECK(callbacks.hide_media_controls);
DCHECK(callbacks.show_media_controls);
Shell::Get()->media_controller()->SetMediaControlsDismissed(false);
middle_spacing_ = std::make_unique<NonAccessibleView>();
middle_spacing_->set_owned_by_client();
set_notify_enter_exit_on_child(true);
contents_view_ = AddChildView(std::make_unique<views::View>());
contents_view_->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kVertical, kMediaControlsInsets));
contents_view_->SetBackground(views::CreateRoundedRectBackground(
kMediaControlsBackground, kMediaControlsCornerRadius));
contents_view_->SetPaintToLayer(); // Needed for opacity animation.
contents_view_->layer()->SetFillsBoundsOpaquely(false);
// session. It also contains the close button.
header_row_ = contents_view_->AddChildView(
std::make_unique<MediaControlsHeaderView>(base::BindOnce(
&LockScreenMediaControlsView::Dismiss, base::Unretained(this))));
auto session_artwork = std::make_unique<views::ImageView>();
session_artwork->SetPreferredSize(kArtworkSize);
session_artwork->SetHorizontalAlignment(
views::ImageView::Alignment::kLeading);
session_artwork_ = contents_view_->AddChildView(std::move(session_artwork));
progress_ = contents_view_->AddChildView(
std::make_unique<media_message_center::MediaControlsProgressView>(
base::BindRepeating(&LockScreenMediaControlsView::SeekTo,
base::Unretained(this))));
auto button_row = std::make_unique<NonAccessibleView>();
auto* button_row_layout =
button_row->SetLayoutManager(std::make_unique<views::BoxLayout>(
views::BoxLayout::Orientation::kHorizontal, kButtonRowInsets,
kMediaButtonRowSeparator));
button_row_layout->set_cross_axis_alignment(
views::BoxLayout::CrossAxisAlignment::kCenter);
button_row_layout->set_main_axis_alignment(
views::BoxLayout::MainAxisAlignment::kCenter);
button_row->SetPreferredSize(kMediaControlsButtonRowSize);
button_row_ = contents_view_->AddChildView(std::move(button_row));
CreateMediaButton(
kChangeTrackIconSize, MediaSessionAction::kPreviousTrack,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PREVIOUS_TRACK));
CreateMediaButton(
kSeekingIconsSize, MediaSessionAction::kSeekBackward,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_BACKWARD));
auto play_pause_button = views::CreateVectorToggleImageButton(this);
play_pause_button->set_tag(static_cast<int>(MediaSessionAction::kPause));
play_pause_button->SetPreferredSize(kMediaButtonSize);
play_pause_button->SetFocusBehavior(views::View::FocusBehavior::ALWAYS);
play_pause_button->SetTooltipText(l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PAUSE));
play_pause_button->SetToggledTooltipText(l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_PLAY));
play_pause_button_ = button_row_->AddChildView(std::move(play_pause_button));
views::SetImageFromVectorIcon(
play_pause_button_,
GetVectorIconForMediaAction(MediaSessionAction::kPause),
kPlayPauseIconSize, kMediaButtonColor);
views::SetToggledImageFromVectorIcon(
play_pause_button_,
GetVectorIconForMediaAction(MediaSessionAction::kPlay),
kPlayPauseIconSize, kMediaButtonColor);
CreateMediaButton(
kSeekingIconsSize, MediaSessionAction::kSeekForward,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_SEEK_FORWARD));
CreateMediaButton(kChangeTrackIconSize, MediaSessionAction::kNextTrack,
l10n_util::GetStringUTF16(
IDS_ASH_LOCK_SCREEN_MEDIA_CONTROLS_ACTION_NEXT_TRACK));
MediaSessionMetadataChanged(base::nullopt);
MediaSessionPositionChanged(base::nullopt);
MediaControllerImageChanged(
media_session::mojom::MediaSessionImageType::kSourceIcon, SkBitmap());
SetArtwork(base::nullopt);
if (!connector_)
return;
mojo::Remote<media_session::mojom::MediaControllerManager>
controller_manager_remote;
connector_->Connect(media_session::mojom::kServiceName,
controller_manager_remote.BindNewPipeAndPassReceiver());
controller_manager_remote->CreateActiveMediaController(
media_controller_remote_.BindNewPipeAndPassReceiver());
media_controller_remote_->AddObserver(
observer_receiver_.BindNewPipeAndPassRemote());
media_controller_remote_->ObserveImages(
media_session::mojom::MediaSessionImageType::kArtwork,
kMinimumArtworkSize, kDesiredArtworkSize,
artwork_observer_receiver_.BindNewPipeAndPassRemote());
media_controller_remote_->ObserveImages(
media_session::mojom::MediaSessionImageType::kSourceIcon,
kMinimumIconSize, kDesiredIconSize,
icon_observer_receiver_.BindNewPipeAndPassRemote());
}
| 172,339 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: InProcessBrowserTest::InProcessBrowserTest()
: browser_(NULL),
exit_when_last_browser_closes_(true),
multi_desktop_test_(false)
#if defined(OS_MACOSX)
, autorelease_pool_(NULL)
#endif // OS_MACOSX
{
#if defined(OS_MACOSX)
base::FilePath chrome_path;
CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
chrome_path = chrome_path.DirName();
chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);
CHECK(PathService::Override(base::FILE_EXE, chrome_path));
#endif // defined(OS_MACOSX)
CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
base::FilePath src_dir;
CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir));
base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data");
embedded_test_server()->ServeFilesFromDirectory(test_data_dir);
CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir));
}
Commit Message: Make the policy fetch for first time login blocking
The CL makes policy fetching for first time login blocking for all users, except the ones that are known to be non-enterprise users.
BUG=334584
Review URL: https://codereview.chromium.org/330843002
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@282925 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-119 | InProcessBrowserTest::InProcessBrowserTest()
: browser_(NULL),
exit_when_last_browser_closes_(true),
open_about_blank_on_browser_launch_(true),
multi_desktop_test_(false)
#if defined(OS_MACOSX)
, autorelease_pool_(NULL)
#endif // OS_MACOSX
{
#if defined(OS_MACOSX)
base::FilePath chrome_path;
CHECK(PathService::Get(base::FILE_EXE, &chrome_path));
chrome_path = chrome_path.DirName();
chrome_path = chrome_path.Append(chrome::kBrowserProcessExecutablePath);
CHECK(PathService::Override(base::FILE_EXE, chrome_path));
#endif // defined(OS_MACOSX)
CreateTestServer(base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
base::FilePath src_dir;
CHECK(PathService::Get(base::DIR_SOURCE_ROOT, &src_dir));
base::FilePath test_data_dir = src_dir.AppendASCII("chrome/test/data");
embedded_test_server()->ServeFilesFromDirectory(test_data_dir);
CHECK(PathService::Override(chrome::DIR_TEST_DATA, test_data_dir));
}
| 171,151 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void WebsiteSettings::OnUIClosing() {
if (show_info_bar_)
WebsiteSettingsInfoBarDelegate::Create(infobar_service_);
SSLCertificateDecisionsDidRevoke user_decision =
did_revoke_user_ssl_decisions_ ? USER_CERT_DECISIONS_REVOKED
: USER_CERT_DECISIONS_NOT_REVOKED;
UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.did_user_revoke_decisions",
user_decision,
END_OF_SSL_CERTIFICATE_DECISIONS_DID_REVOKE_ENUM);
}
Commit Message: Fix UAF in Origin Info Bubble and permission settings UI.
In addition to fixing the UAF, will this also fix the problem of the bubble
showing over the previous tab (if the bubble is open when the tab it was opened
for closes).
BUG=490492
TBR=tedchoc
Review URL: https://codereview.chromium.org/1317443002
Cr-Commit-Position: refs/heads/master@{#346023}
CWE ID: | void WebsiteSettings::OnUIClosing() {
if (show_info_bar_ && web_contents_) {
InfoBarService* infobar_service =
InfoBarService::FromWebContents(web_contents_);
if (infobar_service)
WebsiteSettingsInfoBarDelegate::Create(infobar_service);
}
SSLCertificateDecisionsDidRevoke user_decision =
did_revoke_user_ssl_decisions_ ? USER_CERT_DECISIONS_REVOKED
: USER_CERT_DECISIONS_NOT_REVOKED;
UMA_HISTOGRAM_ENUMERATION("interstitial.ssl.did_user_revoke_decisions",
user_decision,
END_OF_SSL_CERTIFICATE_DECISIONS_DID_REVOKE_ENUM);
}
| 171,780 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
RASN1Object *object;
RCMS *container;
if (!buffer || !length) {
return NULL;
}
container = R_NEW0 (RCMS);
if (!container) {
return NULL;
}
object = r_asn1_create_object (buffer, length);
if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {
r_asn1_free_object (object);
free (container);
return NULL;
}
container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
r_asn1_free_object (object);
return container;
}
Commit Message: Fix #7152 - Null deref in cms
CWE ID: CWE-476 | RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
RASN1Object *object;
RCMS *container;
if (!buffer || !length) {
return NULL;
}
container = R_NEW0 (RCMS);
if (!container) {
return NULL;
}
object = r_asn1_create_object (buffer, length);
if (!object || object->list.length != 2 || !object->list.objects ||
!object->list.objects[0] || !object->list.objects[1] ||
object->list.objects[1]->list.length != 1) {
r_asn1_free_object (object);
free (container);
return NULL;
}
container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
r_asn1_free_object (object);
return container;
}
| 168,287 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BookmarkManagerView::BookmarkManagerView(Profile* profile)
: profile_(profile->GetOriginalProfile()),
table_view_(NULL),
tree_view_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(search_factory_(this)) {
search_tf_ = new views::TextField();
search_tf_->set_default_width_in_chars(30);
table_view_ = new BookmarkTableView(profile_, NULL);
table_view_->SetObserver(this);
table_view_->SetContextMenuController(this);
tree_view_ = new BookmarkFolderTreeView(profile_, NULL);
tree_view_->SetController(this);
tree_view_->SetContextMenuController(this);
views::MenuButton* organize_menu_button = new views::MenuButton(
NULL, l10n_util::GetString(IDS_BOOKMARK_MANAGER_ORGANIZE_MENU),
this, true);
organize_menu_button->SetID(kOrganizeMenuButtonID);
views::MenuButton* tools_menu_button = new views::MenuButton(
NULL, l10n_util::GetString(IDS_BOOKMARK_MANAGER_TOOLS_MENU),
this, true);
tools_menu_button->SetID(kToolsMenuButtonID);
split_view_ = new views::SingleSplitView(tree_view_, table_view_);
split_view_->set_background(
views::Background::CreateSolidBackground(kBackgroundColorBottom));
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
const int top_id = 1;
const int split_cs_id = 2;
layout->SetInsets(2, 0, 0, 0); // 2px padding above content.
views::ColumnSet* column_set = layout->AddColumnSet(top_id);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(1, kUnrelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, 3); // 3px padding at end of row.
column_set = layout->AddColumnSet(split_cs_id);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, top_id);
layout->AddView(organize_menu_button);
layout->AddView(tools_menu_button);
layout->AddView(new views::Label(
l10n_util::GetString(IDS_BOOKMARK_MANAGER_SEARCH_TITLE)));
layout->AddView(search_tf_);
layout->AddPaddingRow(0, 3); // 3px padding between rows.
layout->StartRow(1, split_cs_id);
layout->AddView(split_view_);
BookmarkModel* bookmark_model = profile_->GetBookmarkModel();
if (!bookmark_model->IsLoaded())
bookmark_model->AddObserver(this);
}
Commit Message: Relands cl 16982 as it wasn't the cause of the build breakage. Here's
the description for that cl:
Lands http://codereview.chromium.org/115505 for bug
http://crbug.com/4030 for tyoshino.
BUG=http://crbug.com/4030
TEST=make sure control-w dismisses bookmark manager.
Review URL: http://codereview.chromium.org/113902
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@16987 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | BookmarkManagerView::BookmarkManagerView(Profile* profile)
: profile_(profile->GetOriginalProfile()),
table_view_(NULL),
tree_view_(NULL),
ALLOW_THIS_IN_INITIALIZER_LIST(search_factory_(this)) {
search_tf_ = new views::TextField();
search_tf_->set_default_width_in_chars(30);
table_view_ = new BookmarkTableView(profile_, NULL);
table_view_->SetObserver(this);
table_view_->SetContextMenuController(this);
tree_view_ = new BookmarkFolderTreeView(profile_, NULL);
tree_view_->SetController(this);
tree_view_->SetContextMenuController(this);
views::MenuButton* organize_menu_button = new views::MenuButton(
NULL, l10n_util::GetString(IDS_BOOKMARK_MANAGER_ORGANIZE_MENU),
this, true);
organize_menu_button->SetID(kOrganizeMenuButtonID);
views::MenuButton* tools_menu_button = new views::MenuButton(
NULL, l10n_util::GetString(IDS_BOOKMARK_MANAGER_TOOLS_MENU),
this, true);
tools_menu_button->SetID(kToolsMenuButtonID);
split_view_ = new views::SingleSplitView(tree_view_, table_view_);
split_view_->set_background(
views::Background::CreateSolidBackground(kBackgroundColorBottom));
views::GridLayout* layout = new views::GridLayout(this);
SetLayoutManager(layout);
const int top_id = 1;
const int split_cs_id = 2;
layout->SetInsets(2, 0, 0, 0); // 2px padding above content.
views::ColumnSet* column_set = layout->AddColumnSet(top_id);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(1, kUnrelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, kRelatedControlHorizontalSpacing);
column_set->AddColumn(views::GridLayout::TRAILING, views::GridLayout::CENTER,
0, views::GridLayout::USE_PREF, 0, 0);
column_set->AddPaddingColumn(0, 3); // 3px padding at end of row.
column_set = layout->AddColumnSet(split_cs_id);
column_set->AddColumn(views::GridLayout::FILL, views::GridLayout::FILL, 1,
views::GridLayout::USE_PREF, 0, 0);
layout->StartRow(0, top_id);
layout->AddView(organize_menu_button);
layout->AddView(tools_menu_button);
layout->AddView(new views::Label(
l10n_util::GetString(IDS_BOOKMARK_MANAGER_SEARCH_TITLE)));
layout->AddView(search_tf_);
layout->AddPaddingRow(0, 3); // 3px padding between rows.
layout->StartRow(1, split_cs_id);
layout->AddView(split_view_);
// Press Ctrl-W to close bookmark manager window.
AddAccelerator(views::Accelerator('W', false, true, false));
BookmarkModel* bookmark_model = profile_->GetBookmarkModel();
if (!bookmark_model->IsLoaded())
bookmark_model->AddObserver(this);
}
| 171,060 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void mark_files_ro(struct super_block *sb)
{
struct file *f;
lg_global_lock(&files_lglock);
do_file_list_for_each_entry(sb, f) {
if (!file_count(f))
continue;
if (!(f->f_mode & FMODE_WRITE))
continue;
spin_lock(&f->f_lock);
f->f_mode &= ~FMODE_WRITE;
spin_unlock(&f->f_lock);
if (file_check_writeable(f) != 0)
continue;
__mnt_drop_write(f->f_path.mnt);
file_release_write(f);
} while_file_list_for_each_entry;
lg_global_unlock(&files_lglock);
}
Commit Message: get rid of s_files and files_lock
The only thing we need it for is alt-sysrq-r (emergency remount r/o)
and these days we can do just as well without going through the
list of files.
Signed-off-by: Al Viro <[email protected]>
CWE ID: CWE-17 | void mark_files_ro(struct super_block *sb)
| 166,803 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftAVCEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams =
(OMX_VIDEO_PARAM_AVCTYPE *)params;
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
OMX_U32 omxLevel = AVC_LEVEL2;
if (OMX_ErrorNone !=
ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eLevel = (OMX_VIDEO_AVCLEVELTYPE) omxLevel;
avcParams->nRefFrames = 1;
avcParams->nBFrames = 0;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bEntropyCodingCABAC = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftAVCEncoder::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamVideoBitrate:
{
OMX_VIDEO_PARAM_BITRATETYPE *bitRate =
(OMX_VIDEO_PARAM_BITRATETYPE *) params;
if (!isValidOMXParam(bitRate)) {
return OMX_ErrorBadParameter;
}
if (bitRate->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
bitRate->eControlRate = OMX_Video_ControlRateVariable;
bitRate->nTargetBitrate = mBitrate;
return OMX_ErrorNone;
}
case OMX_IndexParamVideoAvc:
{
OMX_VIDEO_PARAM_AVCTYPE *avcParams =
(OMX_VIDEO_PARAM_AVCTYPE *)params;
if (!isValidOMXParam(avcParams)) {
return OMX_ErrorBadParameter;
}
if (avcParams->nPortIndex != 1) {
return OMX_ErrorUndefined;
}
avcParams->eProfile = OMX_VIDEO_AVCProfileBaseline;
OMX_U32 omxLevel = AVC_LEVEL2;
if (OMX_ErrorNone !=
ConvertAvcSpecLevelToOmxAvcLevel(mAVCEncLevel, &omxLevel)) {
return OMX_ErrorUndefined;
}
avcParams->eLevel = (OMX_VIDEO_AVCLEVELTYPE) omxLevel;
avcParams->nRefFrames = 1;
avcParams->nBFrames = 0;
avcParams->bUseHadamard = OMX_TRUE;
avcParams->nAllowedPictureTypes =
(OMX_VIDEO_PictureTypeI | OMX_VIDEO_PictureTypeP);
avcParams->nRefIdx10ActiveMinus1 = 0;
avcParams->nRefIdx11ActiveMinus1 = 0;
avcParams->bWeightedPPrediction = OMX_FALSE;
avcParams->bEntropyCodingCABAC = OMX_FALSE;
avcParams->bconstIpred = OMX_FALSE;
avcParams->bDirect8x8Inference = OMX_FALSE;
avcParams->bDirectSpatialTemporal = OMX_FALSE;
avcParams->nCabacInitIdc = 0;
return OMX_ErrorNone;
}
default:
return SoftVideoEncoderOMXComponent::internalGetParameter(index, params);
}
}
| 174,198 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool HTMLMediaElement::IsMediaDataCORSSameOrigin(
const SecurityOrigin* origin) const {
if (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidGetOpaqueResponseFromServiceWorker()) {
return false;
}
if (!HasSingleSecurityOrigin())
return false;
return (GetWebMediaPlayer() &&
GetWebMediaPlayer()->DidPassCORSAccessCheck()) ||
origin->CanReadContent(currentSrc());
}
Commit Message: Simplify "WouldTaintOrigin" concept in media/blink
Currently WebMediaPlayer has three predicates:
- DidGetOpaqueResponseFromServiceWorker
- HasSingleSecurityOrigin
- DidPassCORSAccessCheck
. These are used to determine whether the response body is available
for scripts. They are known to be confusing, and actually
MediaElementAudioSourceHandler::WouldTaintOrigin misuses them.
This CL merges the three predicates to one, WouldTaintOrigin, to remove
the confusion. Now the "response type" concept is available and we
don't need a custom CORS check, so this CL removes
BaseAudioContext::WouldTaintOrigin. This CL also renames
URLData::has_opaque_data_ and its (direct and indirect) data accessors
to match the spec.
Bug: 849942, 875153
Change-Id: I6acf50169d7445c4ff614e80ac606f79ee577d2a
Reviewed-on: https://chromium-review.googlesource.com/c/1238098
Reviewed-by: Fredrik Hubinette <[email protected]>
Reviewed-by: Kinuko Yasuda <[email protected]>
Reviewed-by: Raymond Toy <[email protected]>
Commit-Queue: Yutaka Hirano <[email protected]>
Cr-Commit-Position: refs/heads/master@{#598258}
CWE ID: CWE-732 | bool HTMLMediaElement::IsMediaDataCORSSameOrigin(
const SecurityOrigin* origin) const {
if (!GetWebMediaPlayer())
return true;
const auto network_state = GetWebMediaPlayer()->GetNetworkState();
if (network_state == WebMediaPlayer::kNetworkStateNetworkError)
return false;
return !GetWebMediaPlayer()->WouldTaintOrigin();
}
| 172,632 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void load_xref_from_plaintext(FILE *fp, xref_t *xref)
{
int i, buf_idx, obj_id, added_entries;
char c, buf[32] = {0};
long start, pos;
start = ftell(fp);
/* Get number of entries */
pos = xref->end;
fseek(fp, pos, SEEK_SET);
while (ftell(fp) != 0)
if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S')))
break;
else
SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n");
SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n");
xref->n_entries = atoi(buf + strlen("ize "));
xref->entries = calloc(1, xref->n_entries * sizeof(struct _xref_entry));
/* Load entry data */
obj_id = 0;
fseek(fp, xref->start + strlen("xref"), SEEK_SET);
added_entries = 0;
for (i=0; i<xref->n_entries; i++)
{
/* Advance past newlines. */
c = fgetc(fp);
while (c == '\n' || c == '\r')
c = fgetc(fp);
/* Collect data up until the following newline. */
buf_idx = 0;
while (c != '\n' && c != '\r' && !feof(fp) &&
!ferror(fp) && buf_idx < sizeof(buf))
{
buf[buf_idx++] = c;
c = fgetc(fp);
}
if (buf_idx >= sizeof(buf))
{
ERR("Failed to locate newline character. "
"This might be a corrupt PDF.\n");
exit(EXIT_FAILURE);
}
buf[buf_idx] = '\0';
/* Went to far and hit start of trailer */
if (strchr(buf, 't'))
break;
/* Entry or object id */
if (strlen(buf) > 17)
{
xref->entries[i].obj_id = obj_id++;
xref->entries[i].offset = atol(strtok(buf, " "));
xref->entries[i].gen_num = atoi(strtok(NULL, " "));
xref->entries[i].f_or_n = buf[17];
++added_entries;
}
else
{
obj_id = atoi(buf);
--i;
}
}
xref->n_entries = added_entries;
fseek(fp, start, SEEK_SET);
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787 | static void load_xref_from_plaintext(FILE *fp, xref_t *xref)
{
int i, buf_idx, obj_id, added_entries;
char c, buf[32] = {0};
long start, pos;
start = ftell(fp);
/* Get number of entries */
pos = xref->end;
fseek(fp, pos, SEEK_SET);
while (ftell(fp) != 0)
if (SAFE_F(fp, (fgetc(fp) == '/' && fgetc(fp) == 'S')))
break;
else
SAFE_E(fseek(fp, --pos, SEEK_SET), 0, "Failed seek to xref /Size.\n");
SAFE_E(fread(buf, 1, 21, fp), 21, "Failed to load entry Size string.\n");
xref->n_entries = atoi(buf + strlen("ize "));
xref->entries = safe_calloc(xref->n_entries * sizeof(struct _xref_entry));
/* Load entry data */
obj_id = 0;
fseek(fp, xref->start + strlen("xref"), SEEK_SET);
added_entries = 0;
for (i=0; i<xref->n_entries; i++)
{
/* Advance past newlines. */
c = fgetc(fp);
while (c == '\n' || c == '\r')
c = fgetc(fp);
/* Collect data up until the following newline. */
buf_idx = 0;
while (c != '\n' && c != '\r' && !feof(fp) &&
!ferror(fp) && buf_idx < sizeof(buf))
{
buf[buf_idx++] = c;
c = fgetc(fp);
}
if (buf_idx >= sizeof(buf))
{
ERR("Failed to locate newline character. "
"This might be a corrupt PDF.\n");
exit(EXIT_FAILURE);
}
buf[buf_idx] = '\0';
/* Went to far and hit start of trailer */
if (strchr(buf, 't'))
break;
/* Entry or object id */
if (strlen(buf) > 17)
{
xref->entries[i].obj_id = obj_id++;
xref->entries[i].offset = atol(strtok(buf, " "));
xref->entries[i].gen_num = atoi(strtok(NULL, " "));
xref->entries[i].f_or_n = buf[17];
++added_entries;
}
else
{
obj_id = atoi(buf);
--i;
}
}
xref->n_entries = added_entries;
fseek(fp, start, SEEK_SET);
}
| 169,569 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void suffix_object( cJSON *prev, cJSON *item )
{
prev->next = item;
item->prev = prev;
}
Commit Message: Fix a buffer overflow / heap corruption issue that could occur if a
malformed JSON string was passed on the control channel. This issue,
present in the cJSON library, was already fixed upstream, so was
addressed here in iperf3 by importing a newer version of cJSON (plus
local ESnet modifications).
Discovered and reported by Dave McDaniel, Cisco Talos.
Based on a patch by @dopheide-esnet, with input from @DaveGamble.
Cross-references: TALOS-CAN-0164, ESNET-SECADV-2016-0001,
CVE-2016-4303
(cherry picked from commit ed94082be27d971a5e1b08b666e2c217cf470a40)
Signed-off-by: Bruce A. Mah <[email protected]>
CWE ID: CWE-119 | static void suffix_object( cJSON *prev, cJSON *item )
| 167,313 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: choose_volume(struct archive_read *a, struct iso9660 *iso9660)
{
struct file_info *file;
int64_t skipsize;
struct vd *vd;
const void *block;
char seenJoliet;
vd = &(iso9660->primary);
if (!iso9660->opt_support_joliet)
iso9660->seenJoliet = 0;
if (iso9660->seenJoliet &&
vd->location > iso9660->joliet.location)
/* This condition is unlikely; by way of caution. */
vd = &(iso9660->joliet);
skipsize = LOGICAL_BLOCK_SIZE * vd->location;
skipsize = __archive_read_consume(a, skipsize);
if (skipsize < 0)
return ((int)skipsize);
iso9660->current_position = skipsize;
block = __archive_read_ahead(a, vd->size, NULL);
if (block == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to read full block when scanning "
"ISO9660 directory list");
return (ARCHIVE_FATAL);
}
/*
* While reading Root Directory, flag seenJoliet must be zero to
* avoid converting special name 0x00(Current Directory) and
* next byte to UCS2.
*/
seenJoliet = iso9660->seenJoliet;/* Save flag. */
iso9660->seenJoliet = 0;
file = parse_file_info(a, NULL, block);
if (file == NULL)
return (ARCHIVE_FATAL);
iso9660->seenJoliet = seenJoliet;
/*
* If the iso image has both RockRidge and Joliet, we preferentially
* use RockRidge Extensions rather than Joliet ones.
*/
if (vd == &(iso9660->primary) && iso9660->seenRockridge
&& iso9660->seenJoliet)
iso9660->seenJoliet = 0;
if (vd == &(iso9660->primary) && !iso9660->seenRockridge
&& iso9660->seenJoliet) {
/* Switch reading data from primary to joliet. */
vd = &(iso9660->joliet);
skipsize = LOGICAL_BLOCK_SIZE * vd->location;
skipsize -= iso9660->current_position;
skipsize = __archive_read_consume(a, skipsize);
if (skipsize < 0)
return ((int)skipsize);
iso9660->current_position += skipsize;
block = __archive_read_ahead(a, vd->size, NULL);
if (block == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to read full block when scanning "
"ISO9660 directory list");
return (ARCHIVE_FATAL);
}
iso9660->seenJoliet = 0;
file = parse_file_info(a, NULL, block);
if (file == NULL)
return (ARCHIVE_FATAL);
iso9660->seenJoliet = seenJoliet;
}
/* Store the root directory in the pending list. */
if (add_entry(a, iso9660, file) != ARCHIVE_OK)
return (ARCHIVE_FATAL);
if (iso9660->seenRockridge) {
a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;
a->archive.archive_format_name =
"ISO9660 with Rockridge extensions";
}
return (ARCHIVE_OK);
}
Commit Message: Issue 717: Fix integer overflow when computing location of volume descriptor
The multiplication here defaulted to 'int' but calculations
of file positions should always use int64_t. A simple cast
suffices to fix this since the base location is always 32 bits
for ISO, so multiplying by the sector size will never overflow
a 64-bit integer.
CWE ID: CWE-190 | choose_volume(struct archive_read *a, struct iso9660 *iso9660)
{
struct file_info *file;
int64_t skipsize;
struct vd *vd;
const void *block;
char seenJoliet;
vd = &(iso9660->primary);
if (!iso9660->opt_support_joliet)
iso9660->seenJoliet = 0;
if (iso9660->seenJoliet &&
vd->location > iso9660->joliet.location)
/* This condition is unlikely; by way of caution. */
vd = &(iso9660->joliet);
skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location;
skipsize = __archive_read_consume(a, skipsize);
if (skipsize < 0)
return ((int)skipsize);
iso9660->current_position = skipsize;
block = __archive_read_ahead(a, vd->size, NULL);
if (block == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to read full block when scanning "
"ISO9660 directory list");
return (ARCHIVE_FATAL);
}
/*
* While reading Root Directory, flag seenJoliet must be zero to
* avoid converting special name 0x00(Current Directory) and
* next byte to UCS2.
*/
seenJoliet = iso9660->seenJoliet;/* Save flag. */
iso9660->seenJoliet = 0;
file = parse_file_info(a, NULL, block);
if (file == NULL)
return (ARCHIVE_FATAL);
iso9660->seenJoliet = seenJoliet;
/*
* If the iso image has both RockRidge and Joliet, we preferentially
* use RockRidge Extensions rather than Joliet ones.
*/
if (vd == &(iso9660->primary) && iso9660->seenRockridge
&& iso9660->seenJoliet)
iso9660->seenJoliet = 0;
if (vd == &(iso9660->primary) && !iso9660->seenRockridge
&& iso9660->seenJoliet) {
/* Switch reading data from primary to joliet. */
vd = &(iso9660->joliet);
skipsize = LOGICAL_BLOCK_SIZE * (int64_t)vd->location;
skipsize -= iso9660->current_position;
skipsize = __archive_read_consume(a, skipsize);
if (skipsize < 0)
return ((int)skipsize);
iso9660->current_position += skipsize;
block = __archive_read_ahead(a, vd->size, NULL);
if (block == NULL) {
archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
"Failed to read full block when scanning "
"ISO9660 directory list");
return (ARCHIVE_FATAL);
}
iso9660->seenJoliet = 0;
file = parse_file_info(a, NULL, block);
if (file == NULL)
return (ARCHIVE_FATAL);
iso9660->seenJoliet = seenJoliet;
}
/* Store the root directory in the pending list. */
if (add_entry(a, iso9660, file) != ARCHIVE_OK)
return (ARCHIVE_FATAL);
if (iso9660->seenRockridge) {
a->archive.archive_format = ARCHIVE_FORMAT_ISO9660_ROCKRIDGE;
a->archive.archive_format_name =
"ISO9660 with Rockridge extensions";
}
return (ARCHIVE_OK);
}
| 167,021 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, hasChildren)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto bool SplFileObject::getChildren()
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, hasChildren)
{
if (zend_parse_parameters_none() == FAILURE) {
return;
}
RETURN_FALSE;
} /* }}} */
/* {{{ proto bool SplFileObject::getChildren()
| 167,060 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: zsetcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp;
es_ptr ep;
const gs_color_space * pcs = gs_currentcolorspace(igs);
gs_client_color cc;
int n_comps, n_numeric_comps, num_offset = 0, code, depth;
PS_colour_space_t *space;
/* initialize the client color pattern pointer for GC */
cc.pattern = 0;
/* check for a pattern color space */
if ((n_comps = cs_num_components(pcs)) < 0) {
n_comps = -n_comps;
if (r_has_type(op, t_dictionary)) {
ref *pImpl, pPatInst;
code = dict_find_string(op, "Implementation", &pImpl);
if (code != 0) {
code = array_get(imemory, pImpl, 0, &pPatInst);
if (code < 0)
return code;
n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern)
? n_comps - 1
: 0 );
} else
n_numeric_comps = 0;
} else
n_numeric_comps = 0;
num_offset = 1;
} else
n_numeric_comps = n_comps;
/* gather the numeric operands */
code = float_params(op - num_offset, n_numeric_comps, cc.paint.values);
if (code < 0)
return code;
/* The values are copied to graphic state and compared with */
/* other colors by memcmp() in gx_hld_saved_color_equal() */
/* This is the easiest way to avoid indeterminism */
memset(cc.paint.values + n_numeric_comps, 0,
sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps);
code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space);
if (code < 0)
return code;
if (space->validatecomponents) {
code = space->validatecomponents(i_ctx_p,
&istate->colorspace[0].array,
cc.paint.values, n_numeric_comps);
if (code < 0)
return code;
}
/* pass the color to the graphic library */
if ((code = gs_setcolor(igs, &cc)) >= 0) {
if (n_comps > n_numeric_comps) {
istate->pattern[0] = *op; /* save pattern dict or null */
}
}
/* Check the color spaces, to see if we need to run any tint transform
* procedures. Some Adobe applications *eg Photoshop) expect that the
* tint transform will be run and use this to set up duotone DeviceN
* spaces.
*/
code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth);
if (code < 0)
return code;
/* Set up for the continuation procedure which will do the work */
/* Make sure the exec stack has enough space */
check_estack(5);
/* A place holder for data potentially used by transform functions */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'depth' of the space returned during checking above */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'stage' of processing (initially 0) */
ep = esp += 1;
make_int(ep, 0);
/* Store a pointer to the color space stored on the operand stack
* as the stack may grow unpredictably making further access
* to the space difficult
*/
ep = esp += 1;
*ep = istate->colorspace[0].array;
/* Finally, the actual continuation routine */
push_op_estack(setcolor_cont);
return o_push_estack;
}
Commit Message:
CWE ID: CWE-704 | zsetcolor(i_ctx_t * i_ctx_p)
{
os_ptr op = osp;
es_ptr ep;
const gs_color_space * pcs = gs_currentcolorspace(igs);
gs_client_color cc;
int n_comps, n_numeric_comps, num_offset = 0, code, depth;
PS_colour_space_t *space;
/* initialize the client color pattern pointer for GC */
cc.pattern = 0;
/* check for a pattern color space */
if ((n_comps = cs_num_components(pcs)) < 0) {
n_comps = -n_comps;
if (r_has_type(op, t_dictionary)) {
ref *pImpl, pPatInst;
if ((code = dict_find_string(op, "Implementation", &pImpl)) < 0)
return code;
if (code > 0) {
code = array_get(imemory, pImpl, 0, &pPatInst);
if (code < 0)
return code;
n_numeric_comps = ( pattern_instance_uses_base_space(cc.pattern)
? n_comps - 1
: 0 );
} else
n_numeric_comps = 0;
} else
n_numeric_comps = 0;
num_offset = 1;
} else
n_numeric_comps = n_comps;
/* gather the numeric operands */
code = float_params(op - num_offset, n_numeric_comps, cc.paint.values);
if (code < 0)
return code;
/* The values are copied to graphic state and compared with */
/* other colors by memcmp() in gx_hld_saved_color_equal() */
/* This is the easiest way to avoid indeterminism */
memset(cc.paint.values + n_numeric_comps, 0,
sizeof(cc.paint.values) - sizeof(*cc.paint.values)*n_numeric_comps);
code = get_space_object(i_ctx_p, &istate->colorspace[0].array, &space);
if (code < 0)
return code;
if (space->validatecomponents) {
code = space->validatecomponents(i_ctx_p,
&istate->colorspace[0].array,
cc.paint.values, n_numeric_comps);
if (code < 0)
return code;
}
/* pass the color to the graphic library */
if ((code = gs_setcolor(igs, &cc)) >= 0) {
if (n_comps > n_numeric_comps) {
istate->pattern[0] = *op; /* save pattern dict or null */
}
}
/* Check the color spaces, to see if we need to run any tint transform
* procedures. Some Adobe applications *eg Photoshop) expect that the
* tint transform will be run and use this to set up duotone DeviceN
* spaces.
*/
code = validate_spaces(i_ctx_p, &istate->colorspace[0].array, &depth);
if (code < 0)
return code;
/* Set up for the continuation procedure which will do the work */
/* Make sure the exec stack has enough space */
check_estack(5);
/* A place holder for data potentially used by transform functions */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'depth' of the space returned during checking above */
ep = esp += 1;
make_int(ep, 0);
/* Store the 'stage' of processing (initially 0) */
ep = esp += 1;
make_int(ep, 0);
/* Store a pointer to the color space stored on the operand stack
* as the stack may grow unpredictably making further access
* to the space difficult
*/
ep = esp += 1;
*ep = istate->colorspace[0].array;
/* Finally, the actual continuation routine */
push_op_estack(setcolor_cont);
return o_push_estack;
}
| 164,697 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code)
return code;
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
Commit Message: Prevent KDC unset status assertion failures
Assign status values if S4U2Self padata fails to decode, if an
S4U2Proxy request uses invalid KDC options, or if an S4U2Proxy request
uses an evidence ticket which does not match the canonicalized request
server principal name. Reported by Samuel Cabrero.
If a status value is not assigned during KDC processing, default to
"UNKNOWN_REASON" rather than failing an assertion. This change will
prevent future denial of service bugs due to similar mistakes, and
will allow us to omit assigning status values for unlikely errors such
as small memory allocation failures.
CVE-2017-11368:
In MIT krb5 1.7 and later, an authenticated attacker can cause an
assertion failure in krb5kdc by sending an invalid S4U2Self or
S4U2Proxy request.
CVSSv3 Vector: AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:N/A:H/E:H/RL:O/RC:C
ticket: 8599 (new)
target_version: 1.15-next
target_version: 1.14-next
tags: pullup
CWE ID: CWE-617 | kdc_process_s4u_x509_user(krb5_context context,
krb5_kdc_req *request,
krb5_pa_data *pa_data,
krb5_keyblock *tgs_subkey,
krb5_keyblock *tgs_session,
krb5_pa_s4u_x509_user **s4u_x509_user,
const char **status)
{
krb5_error_code code;
krb5_data req_data;
req_data.length = pa_data->length;
req_data.data = (char *)pa_data->contents;
code = decode_krb5_pa_s4u_x509_user(&req_data, s4u_x509_user);
if (code) {
*status = "DECODE_PA_S4U_X509_USER";
return code;
}
code = verify_s4u_x509_user_checksum(context,
tgs_subkey ? tgs_subkey :
tgs_session,
&req_data,
request->nonce, *s4u_x509_user);
if (code) {
*status = "INVALID_S4U2SELF_CHECKSUM";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return code;
}
if (krb5_princ_size(context, (*s4u_x509_user)->user_id.user) == 0 ||
(*s4u_x509_user)->user_id.subject_cert.length != 0) {
*status = "INVALID_S4U2SELF_REQUEST";
krb5_free_pa_s4u_x509_user(context, *s4u_x509_user);
*s4u_x509_user = NULL;
return KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
}
return 0;
}
| 168,043 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: const BlockEntry* Cues::GetBlock(
const CuePoint* pCP,
const CuePoint::TrackPosition* pTP) const
{
if (pCP == NULL)
return NULL;
if (pTP == NULL)
return NULL;
return m_pSegment->GetBlock(*pCP, *pTP);
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | const BlockEntry* Cues::GetBlock(
if (pTP == NULL)
return NULL;
return m_pSegment->GetBlock(*pCP, *pTP);
}
| 174,287 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ShellContentUtilityClient::ShellContentUtilityClient() {
if (base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kProcessType) == switches::kUtilityProcess)
network_service_test_helper_ = std::make_unique<NetworkServiceTestHelper>();
}
Commit Message: Fix content_shell with network service enabled not loading pages.
This regressed in my earlier cl r528763.
This is a reland of r547221.
Bug: 833612
Change-Id: I4c2649414d42773f2530e1abe5912a04fcd0ed9b
Reviewed-on: https://chromium-review.googlesource.com/1064702
Reviewed-by: Jay Civelli <[email protected]>
Commit-Queue: John Abd-El-Malek <[email protected]>
Cr-Commit-Position: refs/heads/master@{#560011}
CWE ID: CWE-264 | ShellContentUtilityClient::ShellContentUtilityClient() {
ShellContentUtilityClient::ShellContentUtilityClient(bool is_browsertest) {
if (is_browsertest &&
base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kProcessType) == switches::kUtilityProcess) {
network_service_test_helper_ = std::make_unique<NetworkServiceTestHelper>();
}
}
| 172,122 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int cypress_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct cypress_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
unsigned long flags;
int result = 0;
if (!priv->comm_is_ok)
return -EIO;
/* clear halts before open */
usb_clear_halt(serial->dev, 0x81);
usb_clear_halt(serial->dev, 0x02);
spin_lock_irqsave(&priv->lock, flags);
/* reset read/write statistics */
priv->bytes_in = 0;
priv->bytes_out = 0;
priv->cmd_count = 0;
priv->rx_flags = 0;
spin_unlock_irqrestore(&priv->lock, flags);
/* Set termios */
cypress_send(port);
if (tty)
cypress_set_termios(tty, port, &priv->tmp_termios);
/* setup the port and start reading from the device */
if (!port->interrupt_in_urb) {
dev_err(&port->dev, "%s - interrupt_in_urb is empty!\n",
__func__);
return -1;
}
usb_fill_int_urb(port->interrupt_in_urb, serial->dev,
usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress),
port->interrupt_in_urb->transfer_buffer,
port->interrupt_in_urb->transfer_buffer_length,
cypress_read_int_callback, port, priv->read_urb_interval);
result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (result) {
dev_err(&port->dev,
"%s - failed submitting read urb, error %d\n",
__func__, result);
cypress_set_dead(port);
}
return result;
} /* cypress_open */
Commit Message: USB: cypress_m8: add endpoint sanity check
An attack using missing endpoints exists.
CVE-2016-3137
Signed-off-by: Oliver Neukum <[email protected]>
CC: [email protected]
Signed-off-by: Johan Hovold <[email protected]>
Signed-off-by: Greg Kroah-Hartman <[email protected]>
CWE ID: | static int cypress_open(struct tty_struct *tty, struct usb_serial_port *port)
{
struct cypress_private *priv = usb_get_serial_port_data(port);
struct usb_serial *serial = port->serial;
unsigned long flags;
int result = 0;
if (!priv->comm_is_ok)
return -EIO;
/* clear halts before open */
usb_clear_halt(serial->dev, 0x81);
usb_clear_halt(serial->dev, 0x02);
spin_lock_irqsave(&priv->lock, flags);
/* reset read/write statistics */
priv->bytes_in = 0;
priv->bytes_out = 0;
priv->cmd_count = 0;
priv->rx_flags = 0;
spin_unlock_irqrestore(&priv->lock, flags);
/* Set termios */
cypress_send(port);
if (tty)
cypress_set_termios(tty, port, &priv->tmp_termios);
/* setup the port and start reading from the device */
usb_fill_int_urb(port->interrupt_in_urb, serial->dev,
usb_rcvintpipe(serial->dev, port->interrupt_in_endpointAddress),
port->interrupt_in_urb->transfer_buffer,
port->interrupt_in_urb->transfer_buffer_length,
cypress_read_int_callback, port, priv->read_urb_interval);
result = usb_submit_urb(port->interrupt_in_urb, GFP_KERNEL);
if (result) {
dev_err(&port->dev,
"%s - failed submitting read urb, error %d\n",
__func__, result);
cypress_set_dead(port);
}
return result;
} /* cypress_open */
| 167,360 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool NavigationController::RendererDidNavigate(
const ViewHostMsg_FrameNavigate_Params& params,
int extra_invalidate_flags,
LoadCommittedDetails* details) {
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->url();
details->previous_entry_index = last_committed_entry_index();
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
if (pending_entry_index_ >= 0 && !pending_entry_->site_instance()) {
DCHECK(pending_entry_->restore_type() != NavigationEntry::RESTORE_NONE);
pending_entry_->set_site_instance(tab_contents_->GetSiteInstance());
pending_entry_->set_restore_type(NavigationEntry::RESTORE_NONE);
}
details->is_in_page = IsURLInPageNavigation(params.url);
details->type = ClassifyNavigation(params);
switch (details->type) {
case NavigationType::NEW_PAGE:
RendererDidNavigateToNewPage(params, &(details->did_replace_entry));
break;
case NavigationType::EXISTING_PAGE:
RendererDidNavigateToExistingPage(params);
break;
case NavigationType::SAME_PAGE:
RendererDidNavigateToSamePage(params);
break;
case NavigationType::IN_PAGE:
RendererDidNavigateInPage(params, &(details->did_replace_entry));
break;
case NavigationType::NEW_SUBFRAME:
RendererDidNavigateNewSubframe(params);
break;
case NavigationType::AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(params))
return false;
break;
case NavigationType::NAV_IGNORE:
return false;
default:
NOTREACHED();
}
DCHECK(!params.content_state.empty());
NavigationEntry* active_entry = GetActiveEntry();
active_entry->set_content_state(params.content_state);
DCHECK(active_entry->site_instance() == tab_contents_->GetSiteInstance());
details->is_auto = (PageTransition::IsRedirect(params.transition) &&
!pending_entry()) ||
params.gesture == NavigationGestureAuto;
details->entry = active_entry;
details->is_main_frame = PageTransition::IsMainFrame(params.transition);
details->serialized_security_info = params.security_info;
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details, extra_invalidate_flags);
return true;
}
Commit Message: Ensure URL is updated after a cross-site navigation is pre-empted by
an "ignored" navigation.
BUG=77507
TEST=NavigationControllerTest.LoadURL_IgnorePreemptsPending
Review URL: http://codereview.chromium.org/6826015
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@81307 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-264 | bool NavigationController::RendererDidNavigate(
const ViewHostMsg_FrameNavigate_Params& params,
int extra_invalidate_flags,
LoadCommittedDetails* details) {
if (GetLastCommittedEntry()) {
details->previous_url = GetLastCommittedEntry()->url();
details->previous_entry_index = last_committed_entry_index();
} else {
details->previous_url = GURL();
details->previous_entry_index = -1;
}
if (pending_entry_index_ >= 0 && !pending_entry_->site_instance()) {
DCHECK(pending_entry_->restore_type() != NavigationEntry::RESTORE_NONE);
pending_entry_->set_site_instance(tab_contents_->GetSiteInstance());
pending_entry_->set_restore_type(NavigationEntry::RESTORE_NONE);
}
details->is_in_page = IsURLInPageNavigation(params.url);
details->type = ClassifyNavigation(params);
switch (details->type) {
case NavigationType::NEW_PAGE:
RendererDidNavigateToNewPage(params, &(details->did_replace_entry));
break;
case NavigationType::EXISTING_PAGE:
RendererDidNavigateToExistingPage(params);
break;
case NavigationType::SAME_PAGE:
RendererDidNavigateToSamePage(params);
break;
case NavigationType::IN_PAGE:
RendererDidNavigateInPage(params, &(details->did_replace_entry));
break;
case NavigationType::NEW_SUBFRAME:
RendererDidNavigateNewSubframe(params);
break;
case NavigationType::AUTO_SUBFRAME:
if (!RendererDidNavigateAutoSubframe(params))
return false;
break;
case NavigationType::NAV_IGNORE:
// If a pending navigation was in progress, this canceled it. We should
// discard it and make sure it is removed from the URL bar. After that,
// there is nothing we can do with this navigation, so we just return to
if (pending_entry_) {
DiscardNonCommittedEntries();
extra_invalidate_flags |= TabContents::INVALIDATE_URL;
tab_contents_->NotifyNavigationStateChanged(extra_invalidate_flags);
}
return false;
default:
NOTREACHED();
}
DCHECK(!params.content_state.empty());
NavigationEntry* active_entry = GetActiveEntry();
active_entry->set_content_state(params.content_state);
DCHECK(active_entry->site_instance() == tab_contents_->GetSiteInstance());
details->is_auto = (PageTransition::IsRedirect(params.transition) &&
!pending_entry()) ||
params.gesture == NavigationGestureAuto;
details->entry = active_entry;
details->is_main_frame = PageTransition::IsMainFrame(params.transition);
details->serialized_security_info = params.security_info;
details->http_status_code = params.http_status_code;
NotifyNavigationEntryCommitted(details, extra_invalidate_flags);
return true;
}
| 170,406 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t Parcel::readUtf8FromUtf16(std::string* str) const {
size_t utf16Size = 0;
const char16_t* src = readString16Inplace(&utf16Size);
if (!src) {
return UNEXPECTED_NULL;
}
if (utf16Size == 0u) {
str->clear();
return NO_ERROR;
}
ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size);
if (utf8Size < 0) {
return BAD_VALUE;
}
str->resize(utf8Size + 1);
utf16_to_utf8(src, utf16Size, &((*str)[0]));
str->resize(utf8Size);
return NO_ERROR;
}
Commit Message: Add bound checks to utf16_to_utf8
Bug: 29250543
Change-Id: I518e7b2fe10aaa3f1c1987586a09b1110aff7e1a
(cherry picked from commit 7e93b2ddcb49b5365fbe1dab134ffb38e6f1c719)
CWE ID: CWE-119 | status_t Parcel::readUtf8FromUtf16(std::string* str) const {
size_t utf16Size = 0;
const char16_t* src = readString16Inplace(&utf16Size);
if (!src) {
return UNEXPECTED_NULL;
}
if (utf16Size == 0u) {
str->clear();
return NO_ERROR;
}
// Allow for closing '\0'
ssize_t utf8Size = utf16_to_utf8_length(src, utf16Size) + 1;
if (utf8Size < 1) {
return BAD_VALUE;
}
// spare byte around for the trailing null, we still pass the size including the trailing null
str->resize(utf8Size);
utf16_to_utf8(src, utf16Size, &((*str)[0]), utf8Size);
str->resize(utf8Size - 1);
return NO_ERROR;
}
| 174,158 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void FrameSelection::Clear() {
granularity_ = TextGranularity::kCharacter;
if (granularity_strategy_)
granularity_strategy_->Clear();
SetSelection(SelectionInDOMTree());
}
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::Clear() {
granularity_ = TextGranularity::kCharacter;
if (granularity_strategy_)
granularity_strategy_->Clear();
SetSelection(SelectionInDOMTree());
is_handle_visible_ = false;
}
| 171,754 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXARIAGridCell::isAriaRowHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringCase(role, "rowheader");
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXARIAGridCell::isAriaRowHeader() const {
const AtomicString& role = getAttribute(HTMLNames::roleAttr);
return equalIgnoringASCIICase(role, "rowheader");
}
| 171,902 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DataReductionProxyConfig::FetchWarmupProbeURL() {
DCHECK(thread_checker_.CalledOnValidThread());
if (!enabled_by_user_) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kProxyNotEnabledByUser);
return;
}
if (!params::FetchWarmupProbeURLEnabled()) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kWarmupURLFetchingDisabled);
return;
}
if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kConnectionTypeNone);
return;
}
base::Optional<DataReductionProxyServer> warmup_proxy =
GetProxyConnectionToProbe();
if (!warmup_proxy)
return;
warmup_url_fetch_in_flight_secure_proxy_ = warmup_proxy->IsSecureProxy();
warmup_url_fetch_in_flight_core_proxy_ = warmup_proxy->IsCoreProxy();
size_t previous_attempt_counts = GetWarmupURLFetchAttemptCounts();
network_properties_manager_->OnWarmupFetchInitiated(
warmup_url_fetch_in_flight_secure_proxy_,
warmup_url_fetch_in_flight_core_proxy_);
RecordWarmupURLFetchAttemptEvent(WarmupURLFetchAttemptEvent::kFetchInitiated);
warmup_url_fetcher_->FetchWarmupURL(previous_attempt_counts,
warmup_proxy.value());
}
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 | void DataReductionProxyConfig::FetchWarmupProbeURL() {
DCHECK(thread_checker_.CalledOnValidThread());
if (params::IsIncludedInHoldbackFieldTrial())
return;
if (!enabled_by_user_) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kProxyNotEnabledByUser);
return;
}
if (!params::FetchWarmupProbeURLEnabled()) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kWarmupURLFetchingDisabled);
return;
}
if (connection_type_ == network::mojom::ConnectionType::CONNECTION_NONE) {
RecordWarmupURLFetchAttemptEvent(
WarmupURLFetchAttemptEvent::kConnectionTypeNone);
return;
}
base::Optional<DataReductionProxyServer> warmup_proxy =
GetProxyConnectionToProbe();
if (!warmup_proxy)
return;
warmup_url_fetch_in_flight_secure_proxy_ = warmup_proxy->IsSecureProxy();
warmup_url_fetch_in_flight_core_proxy_ = warmup_proxy->IsCoreProxy();
size_t previous_attempt_counts = GetWarmupURLFetchAttemptCounts();
network_properties_manager_->OnWarmupFetchInitiated(
warmup_url_fetch_in_flight_secure_proxy_,
warmup_url_fetch_in_flight_core_proxy_);
RecordWarmupURLFetchAttemptEvent(WarmupURLFetchAttemptEvent::kFetchInitiated);
warmup_url_fetcher_->FetchWarmupURL(previous_attempt_counts,
warmup_proxy.value());
}
| 172,415 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ossl_cipher_set_key(VALUE self, VALUE key)
{
EVP_CIPHER_CTX *ctx;
int key_len;
StringValue(key);
GetCipher(self, ctx);
key_len = EVP_CIPHER_CTX_key_length(ctx);
if (RSTRING_LEN(key) != key_len)
ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
return key;
}
Commit Message: cipher: don't set dummy encryption key in Cipher#initialize
Remove the encryption key initialization from Cipher#initialize. This
is effectively a revert of r32723 ("Avoid possible SEGV from AES
encryption/decryption", 2011-07-28).
r32723, which added the key initialization, was a workaround for
Ruby Bug #2768. For some certain ciphers, calling EVP_CipherUpdate()
before setting an encryption key caused segfault. It was not a problem
until OpenSSL implemented GCM mode - the encryption key could be
overridden by repeated calls of EVP_CipherInit_ex(). But, it is not the
case for AES-GCM ciphers. Setting a key, an IV, a key, in this order
causes the IV to be reset to an all-zero IV.
The problem of Bug #2768 persists on the current versions of OpenSSL.
So, make Cipher#update raise an exception if a key is not yet set by the
user. Since encrypting or decrypting without key does not make any
sense, this should not break existing applications.
Users can still call Cipher#key= and Cipher#iv= multiple times with
their own responsibility.
Reference: https://bugs.ruby-lang.org/issues/2768
Reference: https://bugs.ruby-lang.org/issues/8221
Reference: https://github.com/ruby/openssl/issues/49
CWE ID: CWE-310 | ossl_cipher_set_key(VALUE self, VALUE key)
{
EVP_CIPHER_CTX *ctx;
int key_len;
StringValue(key);
GetCipher(self, ctx);
key_len = EVP_CIPHER_CTX_key_length(ctx);
if (RSTRING_LEN(key) != key_len)
ossl_raise(rb_eArgError, "key must be %d bytes", key_len);
if (EVP_CipherInit_ex(ctx, NULL, NULL, (unsigned char *)RSTRING_PTR(key), NULL, -1) != 1)
ossl_raise(eCipherError, NULL);
rb_ivar_set(self, id_key_set, Qtrue);
return key;
}
| 168,782 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct crypto_template *crypto_lookup_template(const char *name)
{
return try_then_request_module(__crypto_lookup_template(name), "%s",
name);
}
Commit Message: crypto: include crypto- module prefix in template
This adds the module loading prefix "crypto-" to the template lookup
as well.
For example, attempting to load 'vfat(blowfish)' via AF_ALG now correctly
includes the "crypto-" prefix at every level, correctly rejecting "vfat":
net-pf-38
algif-hash
crypto-vfat(blowfish)
crypto-vfat(blowfish)-all
crypto-vfat
Reported-by: Mathias Krause <[email protected]>
Signed-off-by: Kees Cook <[email protected]>
Acked-by: Mathias Krause <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: CWE-264 | struct crypto_template *crypto_lookup_template(const char *name)
{
return try_then_request_module(__crypto_lookup_template(name),
"crypto-%s", name);
}
| 166,771 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void MemoryInstrumentation::GetVmRegionsForHeapProfiler(
RequestGlobalDumpCallback callback) {
const auto& coordinator = GetCoordinatorBindingForCurrentThread();
coordinator->GetVmRegionsForHeapProfiler(callback);
}
Commit Message: memory-infra: split up memory-infra coordinator service into two
This allows for heap profiler to use its own service with correct
capabilities and all other instances to use the existing coordinator
service.
Bug: 792028
Change-Id: I84e4ec71f5f1d00991c0516b1424ce7334bcd3cd
Reviewed-on: https://chromium-review.googlesource.com/836896
Commit-Queue: Lalit Maganti <[email protected]>
Reviewed-by: Daniel Cheng <[email protected]>
Reviewed-by: oysteine <[email protected]>
Reviewed-by: Albert J. Wong <[email protected]>
Reviewed-by: Hector Dearman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#529059}
CWE ID: CWE-269 | void MemoryInstrumentation::GetVmRegionsForHeapProfiler(
| 172,918 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: safe_fprintf(FILE *f, const char *fmt, ...)
{
char fmtbuff_stack[256]; /* Place to format the printf() string. */
char outbuff[256]; /* Buffer for outgoing characters. */
char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
int fmtbuff_length;
int length, n;
va_list ap;
const char *p;
unsigned i;
wchar_t wc;
char try_wc;
/* Use a stack-allocated buffer if we can, for speed and safety. */
fmtbuff_heap = NULL;
fmtbuff_length = sizeof(fmtbuff_stack);
fmtbuff = fmtbuff_stack;
/* Try formatting into the stack buffer. */
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
/* If the result was too large, allocate a buffer on the heap. */
while (length < 0 || length >= fmtbuff_length) {
if (length >= fmtbuff_length)
fmtbuff_length = length+1;
else if (fmtbuff_length < 8192)
fmtbuff_length *= 2;
else if (fmtbuff_length < 1000000)
fmtbuff_length += fmtbuff_length / 4;
else {
length = fmtbuff_length;
fmtbuff_heap[length-1] = '\0';
break;
}
free(fmtbuff_heap);
fmtbuff_heap = malloc(fmtbuff_length);
/* Reformat the result into the heap buffer if we can. */
if (fmtbuff_heap != NULL) {
fmtbuff = fmtbuff_heap;
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
} else {
/* Leave fmtbuff pointing to the truncated
* string in fmtbuff_stack. */
length = sizeof(fmtbuff_stack) - 1;
break;
}
}
/* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
* more portable, so we use that here instead. */
if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
/* mbtowc() should never fail in practice, but
* handle the theoretical error anyway. */
free(fmtbuff_heap);
return;
}
/* Write data, expanding unprintable characters. */
p = fmtbuff;
i = 0;
try_wc = 1;
while (*p != '\0') {
/* Convert to wide char, test if the wide
* char is printable in the current locale. */
if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
length -= n;
if (iswprint(wc) && wc != L'\\') {
/* Printable, copy the bytes through. */
while (n-- > 0)
outbuff[i++] = *p++;
} else {
/* Not printable, format the bytes. */
while (n-- > 0)
i += (unsigned)bsdtar_expand_char(
outbuff, i, *p++);
}
} else {
/* After any conversion failure, don't bother
* trying to convert the rest. */
i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
try_wc = 0;
}
/* If our output buffer is full, dump it and keep going. */
if (i > (sizeof(outbuff) - 20)) {
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
i = 0;
}
}
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
/* If we allocated a heap-based formatting buffer, free it now. */
free(fmtbuff_heap);
}
Commit Message: Issue #767: Buffer overflow printing a filename
The safe_fprintf function attempts to ensure clean output for an
arbitrary sequence of bytes by doing a trial conversion of the
multibyte characters to wide characters -- if the resulting wide
character is printable then we pass through the corresponding bytes
unaltered, otherwise, we convert them to C-style ASCII escapes.
The stack trace in Issue #767 suggest that the 20-byte buffer
was getting overflowed trying to format a non-printable multibyte
character. This should only happen if there is a valid multibyte
character of more than 5 bytes that was unprintable. (Each byte
would get expanded to a four-charcter octal-style escape of the form
"\123" resulting in >20 characters for the >5 byte multibyte character.)
I've not been able to reproduce this, but have expanded the conversion
buffer to 128 bytes on the belief that no multibyte character set
has a single character of more than 32 bytes.
CWE ID: CWE-119 | safe_fprintf(FILE *f, const char *fmt, ...)
{
char fmtbuff_stack[256]; /* Place to format the printf() string. */
char outbuff[256]; /* Buffer for outgoing characters. */
char *fmtbuff_heap; /* If fmtbuff_stack is too small, we use malloc */
char *fmtbuff; /* Pointer to fmtbuff_stack or fmtbuff_heap. */
int fmtbuff_length;
int length, n;
va_list ap;
const char *p;
unsigned i;
wchar_t wc;
char try_wc;
/* Use a stack-allocated buffer if we can, for speed and safety. */
fmtbuff_heap = NULL;
fmtbuff_length = sizeof(fmtbuff_stack);
fmtbuff = fmtbuff_stack;
/* Try formatting into the stack buffer. */
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
/* If the result was too large, allocate a buffer on the heap. */
while (length < 0 || length >= fmtbuff_length) {
if (length >= fmtbuff_length)
fmtbuff_length = length+1;
else if (fmtbuff_length < 8192)
fmtbuff_length *= 2;
else if (fmtbuff_length < 1000000)
fmtbuff_length += fmtbuff_length / 4;
else {
length = fmtbuff_length;
fmtbuff_heap[length-1] = '\0';
break;
}
free(fmtbuff_heap);
fmtbuff_heap = malloc(fmtbuff_length);
/* Reformat the result into the heap buffer if we can. */
if (fmtbuff_heap != NULL) {
fmtbuff = fmtbuff_heap;
va_start(ap, fmt);
length = vsnprintf(fmtbuff, fmtbuff_length, fmt, ap);
va_end(ap);
} else {
/* Leave fmtbuff pointing to the truncated
* string in fmtbuff_stack. */
length = sizeof(fmtbuff_stack) - 1;
break;
}
}
/* Note: mbrtowc() has a cleaner API, but mbtowc() seems a bit
* more portable, so we use that here instead. */
if (mbtowc(NULL, NULL, 1) == -1) { /* Reset the shift state. */
/* mbtowc() should never fail in practice, but
* handle the theoretical error anyway. */
free(fmtbuff_heap);
return;
}
/* Write data, expanding unprintable characters. */
p = fmtbuff;
i = 0;
try_wc = 1;
while (*p != '\0') {
/* Convert to wide char, test if the wide
* char is printable in the current locale. */
if (try_wc && (n = mbtowc(&wc, p, length)) != -1) {
length -= n;
if (iswprint(wc) && wc != L'\\') {
/* Printable, copy the bytes through. */
while (n-- > 0)
outbuff[i++] = *p++;
} else {
/* Not printable, format the bytes. */
while (n-- > 0)
i += (unsigned)bsdtar_expand_char(
outbuff, i, *p++);
}
} else {
/* After any conversion failure, don't bother
* trying to convert the rest. */
i += (unsigned)bsdtar_expand_char(outbuff, i, *p++);
try_wc = 0;
}
/* If our output buffer is full, dump it and keep going. */
if (i > (sizeof(outbuff) - 128)) {
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
i = 0;
}
}
outbuff[i] = '\0';
fprintf(f, "%s", outbuff);
/* If we allocated a heap-based formatting buffer, free it now. */
free(fmtbuff_heap);
}
| 168,766 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void Editor::Transpose() {
if (!CanEdit())
//// TODO(yosin): We should move |Transpose()| into |ExecuteTranspose()| in
//// "EditorCommand.cpp"
return;
GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& range = ComputeRangeForTranspose(GetFrame());
if (range.IsNull())
return;
const String& text = PlainText(range);
if (text.length() != 2)
return;
const String& transposed = text.Right(1) + text.Left(1);
if (DispatchBeforeInputInsertText(
EventTargetNodeForDocument(GetFrame().GetDocument()), transposed,
InputEvent::InputType::kInsertTranspose,
new StaticRangeVector(1, StaticRange::Create(range))) !=
DispatchEventResult::kNotCanceled)
return;
if (frame_->GetDocument()->GetFrame() != frame_)
return;
GetFrame().GetDocument()->UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& new_range = ComputeRangeForTranspose(GetFrame());
if (new_range.IsNull())
return;
const String& new_text = PlainText(new_range);
if (new_text.length() != 2)
return;
const String& new_transposed = new_text.Right(1) + new_text.Left(1);
const SelectionInDOMTree& new_selection =
SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build();
if (CreateVisibleSelection(new_selection) !=
GetFrame().Selection().ComputeVisibleSelectionInDOMTree())
GetFrame().Selection().SetSelection(new_selection);
ReplaceSelectionWithText(new_transposed, false, false,
InputEvent::InputType::kInsertTranspose);
}
Commit Message: Move Editor::Transpose() out of Editor class
This patch moves |Editor::Transpose()| out of |Editor| class as preparation of
expanding it into |ExecutTranspose()| in "EditorCommand.cpp" to make |Editor|
class simpler for improving code health.
Following patch will expand |Transpose()| into |ExecutTranspose()|.
Bug: 672405
Change-Id: Icde253623f31813d2b4517c4da7d4798bd5fadf6
Reviewed-on: https://chromium-review.googlesource.com/583880
Reviewed-by: Xiaocheng Hu <[email protected]>
Commit-Queue: Yoshifumi Inoue <[email protected]>
Cr-Commit-Position: refs/heads/master@{#489518}
CWE ID: | void Editor::Transpose() {
//// TODO(yosin): We should move |Transpose()| into |ExecuteTranspose()| in
//// "EditorCommand.cpp"
void Transpose(LocalFrame& frame) {
Editor& editor = frame.GetEditor();
if (!editor.CanEdit())
return;
Document* const document = frame.GetDocument();
document->UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& range = ComputeRangeForTranspose(frame);
if (range.IsNull())
return;
const String& text = PlainText(range);
if (text.length() != 2)
return;
const String& transposed = text.Right(1) + text.Left(1);
if (DispatchBeforeInputInsertText(
EventTargetNodeForDocument(document), transposed,
InputEvent::InputType::kInsertTranspose,
new StaticRangeVector(1, StaticRange::Create(range))) !=
DispatchEventResult::kNotCanceled)
return;
// 'beforeinput' event handler may destroy document->
if (frame.GetDocument() != document)
return;
document->UpdateStyleAndLayoutIgnorePendingStylesheets();
const EphemeralRange& new_range = ComputeRangeForTranspose(frame);
if (new_range.IsNull())
return;
const String& new_text = PlainText(new_range);
if (new_text.length() != 2)
return;
const String& new_transposed = new_text.Right(1) + new_text.Left(1);
const SelectionInDOMTree& new_selection =
SelectionInDOMTree::Builder().SetBaseAndExtent(new_range).Build();
if (CreateVisibleSelection(new_selection) !=
frame.Selection().ComputeVisibleSelectionInDOMTree())
frame.Selection().SetSelection(new_selection);
editor.ReplaceSelectionWithText(new_transposed, false, false,
InputEvent::InputType::kInsertTranspose);
}
| 172,011 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: BOOL transport_connect_nla(rdpTransport* transport)
{
freerdp* instance;
rdpSettings* settings;
if (transport->layer == TRANSPORT_LAYER_TSG)
return TRUE;
if (!transport_connect_tls(transport))
return FALSE;
/* Network Level Authentication */
if (transport->settings->Authentication != TRUE)
return TRUE;
settings = transport->settings;
instance = (freerdp*) settings->instance;
if (transport->credssp == NULL)
transport->credssp = credssp_new(instance, transport, settings);
if (credssp_authenticate(transport->credssp) < 0)
{
if (!connectErrorCode)
connectErrorCode = AUTHENTICATIONERROR;
fprintf(stderr, "Authentication failure, check credentials.\n"
"If credentials are valid, the NTLMSSP implementation may be to blame.\n");
credssp_free(transport->credssp);
return FALSE;
}
credssp_free(transport->credssp);
return TRUE;
}
Commit Message: nla: invalidate sec handle after creation
If sec pointer isn't invalidated after creation it is not possible
to check if the upper and lower pointers are valid.
This fixes a segfault in the server part if the client disconnects before
the authentication was finished.
CWE ID: CWE-476 | BOOL transport_connect_nla(rdpTransport* transport)
{
freerdp* instance;
rdpSettings* settings;
if (transport->layer == TRANSPORT_LAYER_TSG)
return TRUE;
if (!transport_connect_tls(transport))
return FALSE;
/* Network Level Authentication */
if (transport->settings->Authentication != TRUE)
return TRUE;
settings = transport->settings;
instance = (freerdp*) settings->instance;
if (transport->credssp == NULL)
transport->credssp = credssp_new(instance, transport, settings);
if (credssp_authenticate(transport->credssp) < 0)
{
if (!connectErrorCode)
connectErrorCode = AUTHENTICATIONERROR;
fprintf(stderr, "Authentication failure, check credentials.\n"
"If credentials are valid, the NTLMSSP implementation may be to blame.\n");
credssp_free(transport->credssp);
transport->credssp = NULL;
return FALSE;
}
credssp_free(transport->credssp);
return TRUE;
}
| 167,602 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void ExtensionTtsController::ClearUtteranceQueue() {
while (!utterance_queue_.empty()) {
Utterance* utterance = utterance_queue_.front();
utterance_queue_.pop();
utterance->set_error(kSpeechRemovedFromQueueError);
utterance->FinishAndDestroy();
}
}
Commit Message: Extend TTS extension API to support richer events returned from the engine
to the client. Previously we just had a completed event; this adds start,
word boundary, sentence boundary, and marker boundary. In addition,
interrupted and canceled, which were previously errors, now become events.
Mac and Windows implementations extended to support as many of these events
as possible.
BUG=67713
BUG=70198
BUG=75106
BUG=83404
TEST=Updates all TTS API tests to be event-based, and adds new tests.
Review URL: http://codereview.chromium.org/6792014
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@91665 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-20 | void ExtensionTtsController::ClearUtteranceQueue() {
std::set<std::string> required_event_types;
if (options->HasKey(constants::kRequiredEventTypesKey)) {
ListValue* list;
EXTENSION_FUNCTION_VALIDATE(
options->GetList(constants::kRequiredEventTypesKey, &list));
for (size_t i = 0; i < list->GetSize(); i++) {
std::string event_type;
if (!list->GetString(i, &event_type))
required_event_types.insert(event_type);
}
}
| 170,375 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
size_t
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(size_t) (buffer[0] << 24);
value|=buffer[1] << 16;
value|=buffer[2] << 8;
value|=buffer[3];
quantum.unsigned_value=(value & 0xffffffff);
return(quantum.signed_value);
}
Commit Message: Improve checking of EXIF profile to prevent integer overflow (bug report from Ibrahim el-sayed)
CWE ID: CWE-125 | static inline signed int ReadPropertyMSBLong(const unsigned char **p,
size_t *length)
{
union
{
unsigned int
unsigned_value;
signed int
signed_value;
} quantum;
int
c;
register ssize_t
i;
unsigned char
buffer[4];
unsigned int
value;
if (*length < 4)
return(-1);
for (i=0; i < 4; i++)
{
c=(int) (*(*p)++);
(*length)--;
buffer[i]=(unsigned char) c;
}
value=(unsigned int) buffer[0] << 24;
value|=(unsigned int) buffer[1] << 16;
value|=(unsigned int) buffer[2] << 8;
value|=(unsigned int) buffer[3];
quantum.unsigned_value=value & 0xffffffff;
return(quantum.signed_value);
}
| 169,952 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k)
{
void * result;
DCL_LOCK_STATE;
if (EXPECT(GC_have_errors, FALSE))
GC_print_all_errors();
GC_INVOKE_FINALIZERS();
if (SMALL_OBJ(lb)) {
LOCK();
result = GC_generic_malloc_inner((word)lb, k);
UNLOCK();
} else {
size_t lg;
size_t lb_rounded;
word n_blocks;
GC_bool init;
lg = ROUNDED_UP_GRANULES(lb);
lb_rounded = GRANULES_TO_BYTES(lg);
n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded);
init = GC_obj_kinds[k].ok_init;
LOCK();
result = (ptr_t)GC_alloc_large(lb_rounded, k, 0);
if (0 != result) {
if (GC_debugging_started) {
BZERO(result, n_blocks * HBLKSIZE);
} else {
# ifdef THREADS
/* Clear any memory that might be used for GC descriptors */
/* before we release the lock. */
((word *)result)[0] = 0;
((word *)result)[1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0;
# endif
}
}
GC_bytes_allocd += lb_rounded;
UNLOCK();
if (init && !GC_debugging_started && 0 != result) {
BZERO(result, n_blocks * HBLKSIZE);
}
}
if (0 == result) {
return((*GC_get_oom_fn())(lb));
} else {
return(result);
}
}
Commit Message: Fix allocation size overflows due to rounding.
* malloc.c (GC_generic_malloc): Check if the allocation size is
rounded to a smaller value.
* mallocx.c (GC_generic_malloc_ignore_off_page): Likewise.
CWE ID: CWE-189 | GC_API void * GC_CALL GC_generic_malloc(size_t lb, int k)
{
void * result;
DCL_LOCK_STATE;
if (EXPECT(GC_have_errors, FALSE))
GC_print_all_errors();
GC_INVOKE_FINALIZERS();
if (SMALL_OBJ(lb)) {
LOCK();
result = GC_generic_malloc_inner((word)lb, k);
UNLOCK();
} else {
size_t lg;
size_t lb_rounded;
word n_blocks;
GC_bool init;
lg = ROUNDED_UP_GRANULES(lb);
lb_rounded = GRANULES_TO_BYTES(lg);
if (lb_rounded < lb)
return((*GC_get_oom_fn())(lb));
n_blocks = OBJ_SZ_TO_BLOCKS(lb_rounded);
init = GC_obj_kinds[k].ok_init;
LOCK();
result = (ptr_t)GC_alloc_large(lb_rounded, k, 0);
if (0 != result) {
if (GC_debugging_started) {
BZERO(result, n_blocks * HBLKSIZE);
} else {
# ifdef THREADS
/* Clear any memory that might be used for GC descriptors */
/* before we release the lock. */
((word *)result)[0] = 0;
((word *)result)[1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-1] = 0;
((word *)result)[GRANULES_TO_WORDS(lg)-2] = 0;
# endif
}
}
GC_bytes_allocd += lb_rounded;
UNLOCK();
if (init && !GC_debugging_started && 0 != result) {
BZERO(result, n_blocks * HBLKSIZE);
}
}
if (0 == result) {
return((*GC_get_oom_fn())(lb));
} else {
return(result);
}
}
| 169,878 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void CancelHandwriting(int n_strokes) {
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_cancel_hand_writing(context, n_strokes);
g_object_unref(context);
}
Commit Message: Remove use of libcros from InputMethodLibrary.
BUG=chromium-os:16238
TEST==confirm that input methods work as before on the netbook. Also confirm that the chrome builds and works on the desktop as before.
Review URL: http://codereview.chromium.org/7003086
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@89142 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void CancelHandwriting(int n_strokes) {
// IBusController override.
virtual void CancelHandwriting(int n_strokes) {
IBusInputContext* context = GetInputContext(input_context_path_, ibus_);
if (!context) {
return;
}
ibus_input_context_cancel_hand_writing(context, n_strokes);
g_object_unref(context);
}
| 170,518 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
ip += n - 1; /* point to last one */
wp += n - 1; /* point to last one */
n -= stride;
while (n > 0) {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]);
wp[stride] -= wp[0];
wp[stride] &= mask;
wp--; ip--)
n -= stride;
}
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp--; ip--)
}
}
}
Commit Message: * tools/tiffcrop.c: fix various out-of-bounds write vulnerabilities
in heap or stack allocated buffers. Reported as MSVR 35093,
MSVR 35096 and MSVR 35097. Discovered by Axel Souchet and Vishal
Chauhan from the MSRC Vulnerabilities & Mitigations team.
* tools/tiff2pdf.c: fix out-of-bounds write vulnerabilities in
heap allocate buffer in t2p_process_jpeg_strip(). Reported as MSVR
35098. Discovered by Axel Souchet and Vishal Chauhan from the MSRC
Vulnerabilities & Mitigations team.
* libtiff/tif_pixarlog.c: fix out-of-bounds write vulnerabilities
in heap allocated buffers. Reported as MSVR 35094. Discovered by
Axel Souchet and Vishal Chauhan from the MSRC Vulnerabilities &
Mitigations team.
* libtiff/tif_write.c: fix issue in error code path of TIFFFlushData1()
that didn't reset the tif_rawcc and tif_rawcp members. I'm not
completely sure if that could happen in practice outside of the odd
behaviour of t2p_seekproc() of tiff2pdf). The report points that a
better fix could be to check the return value of TIFFFlushData1() in
places where it isn't done currently, but it seems this patch is enough.
Reported as MSVR 35095. Discovered by Axel Souchet & Vishal Chauhan &
Suha Can from the MSRC Vulnerabilities & Mitigations team.
CWE ID: CWE-787 | horizontalDifferenceF(float *ip, int n, int stride, uint16 *wp, uint16 *FromLT2)
{
int32 r1, g1, b1, a1, r2, g2, b2, a2, mask;
float fltsize = Fltsize;
#define CLAMP(v) ( (v<(float)0.) ? 0 \
: (v<(float)2.) ? FromLT2[(int)(v*fltsize)] \
: (v>(float)24.2) ? 2047 \
: LogK1*log(v*LogK2) + 0.5 )
mask = CODE_MASK;
if (n >= stride) {
if (stride == 3) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
n -= 3;
while (n > 0) {
n -= 3;
wp += 3;
ip += 3;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
}
} else if (stride == 4) {
r2 = wp[0] = (uint16) CLAMP(ip[0]);
g2 = wp[1] = (uint16) CLAMP(ip[1]);
b2 = wp[2] = (uint16) CLAMP(ip[2]);
a2 = wp[3] = (uint16) CLAMP(ip[3]);
n -= 4;
while (n > 0) {
n -= 4;
wp += 4;
ip += 4;
r1 = (int32) CLAMP(ip[0]); wp[0] = (uint16)((r1-r2) & mask); r2 = r1;
g1 = (int32) CLAMP(ip[1]); wp[1] = (uint16)((g1-g2) & mask); g2 = g1;
b1 = (int32) CLAMP(ip[2]); wp[2] = (uint16)((b1-b2) & mask); b2 = b1;
a1 = (int32) CLAMP(ip[3]); wp[3] = (uint16)((a1-a2) & mask); a2 = a1;
}
} else {
REPEAT(stride, wp[0] = (uint16) CLAMP(ip[0]); wp++; ip++)
n -= stride;
while (n > 0) {
REPEAT(stride,
wp[0] = (uint16)(((int32)CLAMP(ip[0])-(int32)CLAMP(ip[-stride])) & mask);
wp++; ip++)
n -= stride;
}
}
}
}
| 166,870 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize)
{
BYTE c;
BYTE flags;
UINT32 extra = 0;
int opIndex;
int haveBits;
int inPrefix;
UINT32 count;
UINT32 distance;
BYTE* pbSegment;
size_t cbSegment = segmentSize - 1;
if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1))
return FALSE;
Stream_Read_UINT8(stream, flags); /* header (1 byte) */
zgfx->OutputCount = 0;
pbSegment = Stream_Pointer(stream);
Stream_Seek(stream, cbSegment);
if (!(flags & PACKET_COMPRESSED))
{
zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment);
CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment);
zgfx->OutputCount = cbSegment;
return TRUE;
}
zgfx->pbInputCurrent = pbSegment;
zgfx->pbInputEnd = &pbSegment[cbSegment - 1];
/* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */
zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd;
zgfx->cBitsCurrent = 0;
zgfx->BitsCurrent = 0;
while (zgfx->cBitsRemaining)
{
haveBits = 0;
inPrefix = 0;
for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++)
{
while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength)
{
zgfx_GetBits(zgfx, 1);
inPrefix = (inPrefix << 1) + zgfx->bits;
haveBits++;
}
if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode)
{
if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0)
{
/* Literal */
zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits);
c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits);
zgfx->HistoryBuffer[zgfx->HistoryIndex] = c;
if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize)
zgfx->HistoryIndex = 0;
zgfx->OutputBuffer[zgfx->OutputCount++] = c;
}
else
{
zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits);
distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits;
if (distance != 0)
{
/* Match */
zgfx_GetBits(zgfx, 1);
if (zgfx->bits == 0)
{
count = 3;
}
else
{
count = 4;
extra = 2;
zgfx_GetBits(zgfx, 1);
while (zgfx->bits == 1)
{
count *= 2;
extra++;
zgfx_GetBits(zgfx, 1);
}
zgfx_GetBits(zgfx, extra);
count += zgfx->bits;
}
zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count);
zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count);
zgfx->OutputCount += count;
}
else
{
/* Unencoded */
zgfx_GetBits(zgfx, 15);
count = zgfx->bits;
zgfx->cBitsRemaining -= zgfx->cBitsCurrent;
zgfx->cBitsCurrent = 0;
zgfx->BitsCurrent = 0;
CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count);
zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count);
zgfx->pbInputCurrent += count;
zgfx->cBitsRemaining -= (8 * count);
zgfx->OutputCount += count;
}
}
break;
}
}
}
return TRUE;
}
Commit Message: Fixed CVE-2018-8784
Thanks to Eyal Itkin from Check Point Software Technologies.
CWE ID: CWE-119 | static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize)
{
BYTE c;
BYTE flags;
UINT32 extra = 0;
int opIndex;
int haveBits;
int inPrefix;
UINT32 count;
UINT32 distance;
BYTE* pbSegment;
size_t cbSegment;
if (!zgfx || !stream)
return FALSE;
cbSegment = segmentSize - 1;
if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1) ||
(segmentSize > UINT32_MAX))
return FALSE;
Stream_Read_UINT8(stream, flags); /* header (1 byte) */
zgfx->OutputCount = 0;
pbSegment = Stream_Pointer(stream);
Stream_Seek(stream, cbSegment);
if (!(flags & PACKET_COMPRESSED))
{
zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment);
if (cbSegment > sizeof(zgfx->OutputBuffer))
return FALSE;
CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment);
zgfx->OutputCount = cbSegment;
return TRUE;
}
zgfx->pbInputCurrent = pbSegment;
zgfx->pbInputEnd = &pbSegment[cbSegment - 1];
/* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */
zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd;
zgfx->cBitsCurrent = 0;
zgfx->BitsCurrent = 0;
while (zgfx->cBitsRemaining)
{
haveBits = 0;
inPrefix = 0;
for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++)
{
while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength)
{
zgfx_GetBits(zgfx, 1);
inPrefix = (inPrefix << 1) + zgfx->bits;
haveBits++;
}
if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode)
{
if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0)
{
/* Literal */
zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits);
c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits);
zgfx->HistoryBuffer[zgfx->HistoryIndex] = c;
if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize)
zgfx->HistoryIndex = 0;
if (zgfx->OutputCount >= sizeof(zgfx->OutputBuffer))
return FALSE;
zgfx->OutputBuffer[zgfx->OutputCount++] = c;
}
else
{
zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits);
distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits;
if (distance != 0)
{
/* Match */
zgfx_GetBits(zgfx, 1);
if (zgfx->bits == 0)
{
count = 3;
}
else
{
count = 4;
extra = 2;
zgfx_GetBits(zgfx, 1);
while (zgfx->bits == 1)
{
count *= 2;
extra++;
zgfx_GetBits(zgfx, 1);
}
zgfx_GetBits(zgfx, extra);
count += zgfx->bits;
}
if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount)
return FALSE;
zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count);
zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count);
zgfx->OutputCount += count;
}
else
{
/* Unencoded */
zgfx_GetBits(zgfx, 15);
count = zgfx->bits;
zgfx->cBitsRemaining -= zgfx->cBitsCurrent;
zgfx->cBitsCurrent = 0;
zgfx->BitsCurrent = 0;
if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount)
return FALSE;
CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count);
zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count);
zgfx->pbInputCurrent += count;
zgfx->cBitsRemaining -= (8 * count);
zgfx->OutputCount += count;
}
}
break;
}
}
}
return TRUE;
}
| 169,297 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DaemonProcessTest::LaunchNetworkProcess() {
terminal_id_ = 0;
daemon_process_->OnChannelConnected();
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void DaemonProcessTest::LaunchNetworkProcess() {
terminal_id_ = 0;
daemon_process_->OnChannelConnected(0);
}
| 171,541 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
{
DTLS1_RECORD_DATA *rdata;
pitem *item;
/* Limit the size of the queue to prevent DOS attacks */
if (pqueue_size(queue->q) >= 100)
return 0;
rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
item = pitem_new(priority, rdata);
if (rdata == NULL || item == NULL)
{
if (rdata != NULL) OPENSSL_free(rdata);
if (item != NULL) pitem_free(item);
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
return(0);
}
rdata->packet = s->packet;
rdata->packet_length = s->packet_length;
memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
item->data = rdata;
#ifndef OPENSSL_NO_SCTP
/* Store bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
(s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) {
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
s->packet = NULL;
s->packet_length = 0;
memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
if (!ssl3_setup_buffers(s))
{
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
OPENSSL_free(rdata);
pitem_free(item);
return(0);
}
/* insert should not fail, since duplicates are dropped */
if (pqueue_insert(queue->q, item) == NULL)
{
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
OPENSSL_free(rdata);
pitem_free(item);
return(0);
}
return(1);
}
Commit Message: A memory leak can occur in dtls1_buffer_record if either of the calls to
ssl3_setup_buffers or pqueue_insert fail. The former will fail if there is a
malloc failure, whilst the latter will fail if attempting to add a duplicate
record to the queue. This should never happen because duplicate records should
be detected and dropped before any attempt to add them to the queue.
Unfortunately records that arrive that are for the next epoch are not being
recorded correctly, and therefore replays are not being detected.
Additionally, these "should not happen" failures that can occur in
dtls1_buffer_record are not being treated as fatal and therefore an attacker
could exploit this by sending repeated replay records for the next epoch,
eventually causing a DoS through memory exhaustion.
Thanks to Chris Mueller for reporting this issue and providing initial
analysis and a patch. Further analysis and the final patch was performed by
Matt Caswell from the OpenSSL development team.
CVE-2015-0206
Reviewed-by: Dr Stephen Henson <[email protected]>
CWE ID: CWE-119 | dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
{
DTLS1_RECORD_DATA *rdata;
pitem *item;
/* Limit the size of the queue to prevent DOS attacks */
if (pqueue_size(queue->q) >= 100)
return 0;
rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
item = pitem_new(priority, rdata);
if (rdata == NULL || item == NULL)
{
if (rdata != NULL) OPENSSL_free(rdata);
if (item != NULL) pitem_free(item);
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
return(0);
}
rdata->packet = s->packet;
rdata->packet_length = s->packet_length;
memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
item->data = rdata;
#ifndef OPENSSL_NO_SCTP
/* Store bio_dgram_sctp_rcvinfo struct */
if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
(s->state == SSL3_ST_SR_FINISHED_A || s->state == SSL3_ST_CR_FINISHED_A)) {
BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO, sizeof(rdata->recordinfo), &rdata->recordinfo);
}
#endif
s->packet = NULL;
s->packet_length = 0;
memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
if (!ssl3_setup_buffers(s))
{
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
if (rdata->rbuf.buf != NULL)
OPENSSL_free(rdata->rbuf.buf);
OPENSSL_free(rdata);
pitem_free(item);
return(-1);
}
/* insert should not fail, since duplicates are dropped */
if (pqueue_insert(queue->q, item) == NULL)
{
SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
if (rdata->rbuf.buf != NULL)
OPENSSL_free(rdata->rbuf.buf);
OPENSSL_free(rdata);
pitem_free(item);
return(-1);
}
return(1);
}
| 166,745 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared sigtnature algorithms */
if (s->cert->shared_sigalgs) {
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].valid_flags = 0;
}
/* If sigalgs received process it. */
if (s->cert->peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else
ssl_cert_set_default_md(s->cert);
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
Commit Message:
CWE ID: | int tls1_set_server_sigalgs(SSL *s)
{
int al;
size_t i;
/* Clear any shared sigtnature algorithms */
if (s->cert->shared_sigalgs) {
OPENSSL_free(s->cert->shared_sigalgs);
s->cert->shared_sigalgs = NULL;
s->cert->shared_sigalgslen = 0;
}
/* Clear certificate digests and validity flags */
for (i = 0; i < SSL_PKEY_NUM; i++) {
s->cert->pkeys[i].valid_flags = 0;
}
/* If sigalgs received process it. */
if (s->cert->peer_sigalgs) {
if (!tls1_process_sigalgs(s)) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS, ERR_R_MALLOC_FAILURE);
al = SSL_AD_INTERNAL_ERROR;
goto err;
}
/* Fatal error is no shared signature algorithms */
if (!s->cert->shared_sigalgs) {
SSLerr(SSL_F_TLS1_SET_SERVER_SIGALGS,
SSL_R_NO_SHARED_SIGATURE_ALGORITHMS);
al = SSL_AD_ILLEGAL_PARAMETER;
goto err;
}
} else
ssl_cert_set_default_md(s->cert);
return 1;
err:
ssl3_send_alert(s, SSL3_AL_FATAL, al);
return 0;
}
| 164,804 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int http_connect(http_subtransport *t)
{
int error;
if (t->connected &&
http_should_keep_alive(&t->parser) &&
t->parse_finished)
return 0;
if (t->io) {
git_stream_close(t->io);
git_stream_free(t->io);
t->io = NULL;
t->connected = 0;
}
if (t->connection_data.use_ssl) {
error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
} else {
#ifdef GIT_CURL
error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#else
error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#endif
}
if (error < 0)
return error;
GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream");
apply_proxy_config(t);
error = git_stream_connect(t->io);
if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL &&
git_stream_is_encrypted(t->io)) {
git_cert *cert;
int is_valid;
if ((error = git_stream_certificate(&cert, t->io)) < 0)
return error;
giterr_clear();
is_valid = error != GIT_ECERTIFICATE;
error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload);
if (error < 0) {
if (!giterr_last())
giterr_set(GITERR_NET, "user cancelled certificate check");
return error;
}
}
if (error < 0)
return error;
t->connected = 1;
return 0;
}
Commit Message: http: check certificate validity before clobbering the error variable
CWE ID: CWE-284 | static int http_connect(http_subtransport *t)
{
int error;
if (t->connected &&
http_should_keep_alive(&t->parser) &&
t->parse_finished)
return 0;
if (t->io) {
git_stream_close(t->io);
git_stream_free(t->io);
t->io = NULL;
t->connected = 0;
}
if (t->connection_data.use_ssl) {
error = git_tls_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
} else {
#ifdef GIT_CURL
error = git_curl_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#else
error = git_socket_stream_new(&t->io, t->connection_data.host, t->connection_data.port);
#endif
}
if (error < 0)
return error;
GITERR_CHECK_VERSION(t->io, GIT_STREAM_VERSION, "git_stream");
apply_proxy_config(t);
error = git_stream_connect(t->io);
if ((!error || error == GIT_ECERTIFICATE) && t->owner->certificate_check_cb != NULL &&
git_stream_is_encrypted(t->io)) {
git_cert *cert;
int is_valid = (error == GIT_OK);
if ((error = git_stream_certificate(&cert, t->io)) < 0)
return error;
giterr_clear();
error = t->owner->certificate_check_cb(cert, is_valid, t->connection_data.host, t->owner->message_cb_payload);
if (error < 0) {
if (!giterr_last())
giterr_set(GITERR_NET, "user cancelled certificate check");
return error;
}
}
if (error < 0)
return error;
t->connected = 1;
return 0;
}
| 168,526 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SiteInstanceImpl::ShouldLockToOrigin(BrowserContext* browser_context,
GURL site_url) {
if (RenderProcessHost::run_renderer_in_process())
return false;
if (!DoesSiteRequireDedicatedProcess(browser_context, site_url))
return false;
if (site_url.SchemeIs(content::kGuestScheme))
return false;
if (site_url.SchemeIs(content::kChromeUIScheme))
return false;
if (!GetContentClient()->browser()->ShouldLockToOrigin(browser_context,
site_url)) {
return false;
}
return true;
}
Commit Message: Allow origin lock for WebUI pages.
Returning true for WebUI pages in DoesSiteRequireDedicatedProcess helps
to keep enforcing a SiteInstance swap during chrome://foo ->
chrome://bar navigation, even after relaxing
BrowsingInstance::GetSiteInstanceForURL to consider RPH::IsSuitableHost
(see https://crrev.com/c/783470 for that fixes process sharing in
isolated(b(c),d(c)) scenario).
I've manually tested this CL by visiting the following URLs:
- chrome://welcome/
- chrome://settings
- chrome://extensions
- chrome://history
- chrome://help and chrome://chrome (both redirect to chrome://settings/help)
Bug: 510588, 847127
Change-Id: I55073bce00f32cb8bc5c1c91034438ff9a3f8971
Reviewed-on: https://chromium-review.googlesource.com/1237392
Commit-Queue: Łukasz Anforowicz <[email protected]>
Reviewed-by: François Doray <[email protected]>
Reviewed-by: Nasko Oskov <[email protected]>
Reviewed-by: Avi Drissman <[email protected]>
Cr-Commit-Position: refs/heads/master@{#595259}
CWE ID: CWE-119 | bool SiteInstanceImpl::ShouldLockToOrigin(BrowserContext* browser_context,
GURL site_url) {
if (RenderProcessHost::run_renderer_in_process())
return false;
if (!DoesSiteRequireDedicatedProcess(browser_context, site_url))
return false;
if (site_url.SchemeIs(content::kGuestScheme))
return false;
if (!GetContentClient()->browser()->ShouldLockToOrigin(browser_context,
site_url)) {
return false;
}
return true;
}
| 173,282 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DisconnectWindowLinux::Hide() {
NOTIMPLEMENTED();
}
Commit Message: Initial implementation of DisconnectWindow on Linux.
BUG=None
TEST=Manual
Review URL: http://codereview.chromium.org/7089016
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88889 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | void DisconnectWindowLinux::Hide() {
DCHECK(disconnect_window_);
gtk_widget_hide(disconnect_window_);
}
gboolean DisconnectWindowLinux::OnWindowDelete(GtkWidget* widget,
GdkEvent* event) {
// Don't allow the window to be closed.
return TRUE;
}
void DisconnectWindowLinux::OnDisconnectClicked(GtkButton* sender) {
DCHECK(host_);
host_->Shutdown();
}
| 170,473 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: WORD32 ih264d_create(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
ih264d_create_op_t *ps_create_op;
WORD32 ret;
ps_create_op = (ih264d_create_op_t *)pv_api_op;
ps_create_op->s_ivd_create_op_t.u4_error_code = 0;
ret = ih264d_allocate_static_bufs(&dec_hdl, pv_api_ip, pv_api_op);
/* If allocation of some buffer fails, then free buffers allocated till then */
if((IV_FAIL == ret) && (NULL != dec_hdl))
{
ih264d_free_static_bufs(dec_hdl);
ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED;
ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR;
return IV_FAIL;
}
return IV_SUCCESS;
}
Commit Message: Decoder: Handle dec_hdl memory allocation failure gracefully
If memory allocation for dec_hdl fails, return gracefully
with an error code. All other allocation failures are
handled correctly.
Bug: 68300072
Test: ran poc before/after
Change-Id: I118ae71f4aded658441f1932bd4ede3536f5028b
(cherry picked from commit 7720b3fe3de04523da3a9ecec2b42a3748529bbd)
CWE ID: CWE-770 | WORD32 ih264d_create(iv_obj_t *dec_hdl, void *pv_api_ip, void *pv_api_op)
{
ih264d_create_ip_t *ps_create_ip;
ih264d_create_op_t *ps_create_op;
WORD32 ret;
ps_create_ip = (ih264d_create_ip_t *)pv_api_ip;
ps_create_op = (ih264d_create_op_t *)pv_api_op;
ps_create_op->s_ivd_create_op_t.u4_error_code = 0;
dec_hdl = NULL;
ret = ih264d_allocate_static_bufs(&dec_hdl, pv_api_ip, pv_api_op);
/* If allocation of some buffer fails, then free buffers allocated till then */
if(IV_FAIL == ret)
{
if(dec_hdl)
{
if(dec_hdl->pv_codec_handle)
{
ih264d_free_static_bufs(dec_hdl);
}
else
{
void (*pf_aligned_free)(void *pv_mem_ctxt, void *pv_buf);
void *pv_mem_ctxt;
pf_aligned_free = ps_create_ip->s_ivd_create_ip_t.pf_aligned_free;
pv_mem_ctxt = ps_create_ip->s_ivd_create_ip_t.pv_mem_ctxt;
pf_aligned_free(pv_mem_ctxt, dec_hdl);
}
}
ps_create_op->s_ivd_create_op_t.u4_error_code = IVD_MEM_ALLOC_FAILED;
ps_create_op->s_ivd_create_op_t.u4_error_code = 1 << IVD_FATALERROR;
return IV_FAIL;
}
return IV_SUCCESS;
}
| 174,112 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = !IS_MNT_LOCKED_AND_LAZY(p);
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
Commit Message: mnt: Update detach_mounts to leave mounts connected
Now that it is possible to lazily unmount an entire mount tree and
leave the individual mounts connected to each other add a new flag
UMOUNT_CONNECTED to umount_tree to force this behavior and use
this flag in detach_mounts.
This closes a bug where the deletion of a file or directory could
trigger an unmount and reveal data under a mount point.
Cc: [email protected]
Signed-off-by: "Eric W. Biederman" <[email protected]>
CWE ID: CWE-200 | static void umount_tree(struct mount *mnt, enum umount_tree_flags how)
{
LIST_HEAD(tmp_list);
struct mount *p;
if (how & UMOUNT_PROPAGATE)
propagate_mount_unlock(mnt);
/* Gather the mounts to umount */
for (p = mnt; p; p = next_mnt(p, mnt)) {
p->mnt.mnt_flags |= MNT_UMOUNT;
list_move(&p->mnt_list, &tmp_list);
}
/* Hide the mounts from mnt_mounts */
list_for_each_entry(p, &tmp_list, mnt_list) {
list_del_init(&p->mnt_child);
}
/* Add propogated mounts to the tmp_list */
if (how & UMOUNT_PROPAGATE)
propagate_umount(&tmp_list);
while (!list_empty(&tmp_list)) {
bool disconnect;
p = list_first_entry(&tmp_list, struct mount, mnt_list);
list_del_init(&p->mnt_expire);
list_del_init(&p->mnt_list);
__touch_mnt_namespace(p->mnt_ns);
p->mnt_ns = NULL;
if (how & UMOUNT_SYNC)
p->mnt.mnt_flags |= MNT_SYNC_UMOUNT;
disconnect = !(((how & UMOUNT_CONNECTED) &&
mnt_has_parent(p) &&
(p->mnt_parent->mnt.mnt_flags & MNT_UMOUNT)) ||
IS_MNT_LOCKED_AND_LAZY(p));
pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt,
disconnect ? &unmounted : NULL);
if (mnt_has_parent(p)) {
mnt_add_count(p->mnt_parent, -1);
if (!disconnect) {
/* Don't forget about p */
list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts);
} else {
umount_mnt(p);
}
}
change_mnt_propagation(p, MS_PRIVATE);
}
}
| 167,565 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void RunInvTxfm(int16_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride);
}
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 RunInvTxfm(int16_t *out, uint8_t *dst, int stride) {
void RunInvTxfm(tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride);
}
| 174,524 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SPL_METHOD(SplFileObject, next)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_file_free_line(intern TSRMLS_CC);
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
}
intern->u.file.current_line_num++;
} /* }}} */
/* {{{ proto void SplFileObject::setFlags(int flags)
Commit Message: Fix bug #72262 - do not overflow int
CWE ID: CWE-190 | SPL_METHOD(SplFileObject, next)
{
spl_filesystem_object *intern = (spl_filesystem_object*)zend_object_store_get_object(getThis() TSRMLS_CC);
if (zend_parse_parameters_none() == FAILURE) {
return;
}
spl_filesystem_file_free_line(intern TSRMLS_CC);
if (SPL_HAS_FLAG(intern->flags, SPL_FILE_OBJECT_READ_AHEAD)) {
spl_filesystem_file_read_line(getThis(), intern, 1 TSRMLS_CC);
}
intern->u.file.current_line_num++;
} /* }}} */
/* {{{ proto void SplFileObject::setFlags(int flags)
| 167,057 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Object> V8SchemaRegistry::GetSchema(const std::string& api) {
if (schema_cache_ != NULL) {
v8::Local<v8::Object> cached_schema = schema_cache_->Get(api);
if (!cached_schema.IsEmpty()) {
return cached_schema;
}
}
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope handle_scope(isolate);
v8::Local<v8::Context> context = GetOrCreateContext(isolate);
v8::Context::Scope context_scope(context);
const base::DictionaryValue* schema =
ExtensionAPI::GetSharedInstance()->GetSchema(api);
CHECK(schema) << api;
std::unique_ptr<V8ValueConverter> v8_value_converter(
V8ValueConverter::create());
v8::Local<v8::Value> value = v8_value_converter->ToV8Value(schema, context);
CHECK(!value.IsEmpty());
v8::Local<v8::Object> v8_schema(v8::Local<v8::Object>::Cast(value));
v8_schema->SetIntegrityLevel(context, v8::IntegrityLevel::kFrozen);
schema_cache_->Set(api, v8_schema);
return handle_scope.Escape(v8_schema);
}
Commit Message: [Extensions] Finish freezing schema
BUG=604901
BUG=603725
BUG=591164
Review URL: https://codereview.chromium.org/1906593002
Cr-Commit-Position: refs/heads/master@{#388945}
CWE ID: CWE-200 | v8::Local<v8::Object> V8SchemaRegistry::GetSchema(const std::string& api) {
if (schema_cache_ != NULL) {
v8::Local<v8::Object> cached_schema = schema_cache_->Get(api);
if (!cached_schema.IsEmpty()) {
return cached_schema;
}
}
v8::Isolate* isolate = v8::Isolate::GetCurrent();
v8::EscapableHandleScope handle_scope(isolate);
v8::Local<v8::Context> context = GetOrCreateContext(isolate);
v8::Context::Scope context_scope(context);
const base::DictionaryValue* schema =
ExtensionAPI::GetSharedInstance()->GetSchema(api);
CHECK(schema) << api;
std::unique_ptr<V8ValueConverter> v8_value_converter(
V8ValueConverter::create());
v8::Local<v8::Value> value = v8_value_converter->ToV8Value(schema, context);
CHECK(!value.IsEmpty());
v8::Local<v8::Object> v8_schema(v8::Local<v8::Object>::Cast(value));
DeepFreeze(v8_schema, context);
schema_cache_->Set(api, v8_schema);
return handle_scope.Escape(v8_schema);
}
| 172,259 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int prctl_set_vma_anon_name(unsigned long start, unsigned long end,
unsigned long arg)
{
unsigned long tmp;
struct vm_area_struct * vma, *prev;
int unmapped_error = 0;
int error = -EINVAL;
/*
* If the interval [start,end) covers some unmapped address
* ranges, just ignore them, but return -ENOMEM at the end.
* - this matches the handling in madvise.
*/
vma = find_vma_prev(current->mm, start, &prev);
if (vma && start > vma->vm_start)
prev = vma;
for (;;) {
/* Still start < end. */
error = -ENOMEM;
if (!vma)
return error;
/* Here start < (end|vma->vm_end). */
if (start < vma->vm_start) {
unmapped_error = -ENOMEM;
start = vma->vm_start;
if (start >= end)
return error;
}
/* Here vma->vm_start <= start < (end|vma->vm_end) */
tmp = vma->vm_end;
if (end < tmp)
tmp = end;
/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
error = prctl_update_vma_anon_name(vma, &prev, start, end,
(const char __user *)arg);
if (error)
return error;
start = tmp;
if (prev && start < prev->vm_end)
start = prev->vm_end;
error = unmapped_error;
if (start >= end)
return error;
if (prev)
vma = prev->vm_next;
else /* madvise_remove dropped mmap_sem */
vma = find_vma(current->mm, start);
}
}
Commit Message: mm: fix prctl_set_vma_anon_name
prctl_set_vma_anon_name could attempt to set the name across
two vmas at the same time due to a typo, which might corrupt
the vma list. Fix it to use tmp instead of end to limit
the name setting to a single vma at a time.
Change-Id: Ie32d8ddb0fd547efbeedd6528acdab5ca5b308b4
Reported-by: Jed Davis <[email protected]>
Signed-off-by: Colin Cross <[email protected]>
CWE ID: CWE-264 | static int prctl_set_vma_anon_name(unsigned long start, unsigned long end,
unsigned long arg)
{
unsigned long tmp;
struct vm_area_struct * vma, *prev;
int unmapped_error = 0;
int error = -EINVAL;
/*
* If the interval [start,end) covers some unmapped address
* ranges, just ignore them, but return -ENOMEM at the end.
* - this matches the handling in madvise.
*/
vma = find_vma_prev(current->mm, start, &prev);
if (vma && start > vma->vm_start)
prev = vma;
for (;;) {
/* Still start < end. */
error = -ENOMEM;
if (!vma)
return error;
/* Here start < (end|vma->vm_end). */
if (start < vma->vm_start) {
unmapped_error = -ENOMEM;
start = vma->vm_start;
if (start >= end)
return error;
}
/* Here vma->vm_start <= start < (end|vma->vm_end) */
tmp = vma->vm_end;
if (end < tmp)
tmp = end;
/* Here vma->vm_start <= start < tmp <= (end|vma->vm_end). */
error = prctl_update_vma_anon_name(vma, &prev, start, tmp,
(const char __user *)arg);
if (error)
return error;
start = tmp;
if (prev && start < prev->vm_end)
start = prev->vm_end;
error = unmapped_error;
if (start >= end)
return error;
if (prev)
vma = prev->vm_next;
else /* madvise_remove dropped mmap_sem */
vma = find_vma(current->mm, start);
}
}
| 173,972 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
FakeResponseMap::const_iterator it = fake_responses_.find(url);
if (it == fake_responses_.end()) {
DLOG(ERROR) << "No baked response for URL: " << url.spec();
return NULL;
}
return new FakeURLFetcher(url, request_type, d,
it->second.first, it->second.second);
}
Commit Message: Use URLFetcher::Create instead of new in http_bridge.cc.
This change modified http_bridge so that it uses a factory to construct
the URLFetcher. Moreover, it modified sync_backend_host_unittest.cc to
use an URLFetcher factory which will prevent access to www.example.com during
the test.
BUG=none
TEST=sync_backend_host_unittest.cc
Review URL: http://codereview.chromium.org/7053011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87227 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
int id,
const GURL& url,
URLFetcher::RequestType request_type,
URLFetcher::Delegate* d) {
FakeResponseMap::const_iterator it = fake_responses_.find(url);
if (it == fake_responses_.end()) {
if (default_factory_ == NULL) {
// If we don't have a baked response for that URL we return NULL.
DLOG(ERROR) << "No baked response for URL: " << url.spec();
return NULL;
} else {
return default_factory_->CreateURLFetcher(id, url, request_type, d);
}
}
return new FakeURLFetcher(url, request_type, d,
it->second.first, it->second.second);
}
| 170,429 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DesktopWindowTreeHostX11::SetVisible(bool visible) {
if (compositor())
compositor()->SetVisible(visible);
if (IsVisible() != visible)
native_widget_delegate_->OnNativeWidgetVisibilityChanged(visible);
}
Commit Message: Fix PIP window being blank after minimize/show
DesktopWindowTreeHostX11::SetVisible only made the call into
OnNativeWidgetVisibilityChanged when transitioning from shown
to minimized and not vice versa. This is because this change
https://chromium-review.googlesource.com/c/chromium/src/+/1437263
considered IsVisible to be true when minimized, which made
IsVisible always true in this case. This caused layers to be hidden
but never shown again.
This is a reland of:
https://chromium-review.googlesource.com/c/chromium/src/+/1580103
Bug: 949199
Change-Id: I2151cd09e537d8ce8781897f43a3b8e9cec75996
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1584617
Reviewed-by: Scott Violet <[email protected]>
Commit-Queue: enne <[email protected]>
Cr-Commit-Position: refs/heads/master@{#654280}
CWE ID: CWE-284 | void DesktopWindowTreeHostX11::SetVisible(bool visible) {
if (is_compositor_set_visible_ == visible)
return;
is_compositor_set_visible_ = visible;
if (compositor())
compositor()->SetVisible(visible);
native_widget_delegate_->OnNativeWidgetVisibilityChanged(visible);
}
| 172,516 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void __init acpi_debugfs_init(void)
{
acpi_debugfs_dir = debugfs_create_dir("acpi", NULL);
acpi_custom_method_init();
}
Commit Message: ACPI: Split out custom_method functionality into an own driver
With /sys/kernel/debug/acpi/custom_method root can write
to arbitrary memory and increase his priveleges, even if
these are restricted.
-> Make this an own debug .config option and warn about the
security issue in the config description.
-> Still keep acpi/debugfs.c which now only creates an empty
/sys/kernel/debug/acpi directory. There might be other
users of it later.
Signed-off-by: Thomas Renninger <[email protected]>
Acked-by: Rafael J. Wysocki <[email protected]>
Acked-by: [email protected]
Signed-off-by: Len Brown <[email protected]>
CWE ID: CWE-264 | void __init acpi_debugfs_init(void)
{
acpi_debugfs_dir = debugfs_create_dir("acpi", NULL);
}
| 165,902 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return in;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
chr[ len ++ ] = 0;
return chr;
}
Commit Message: New Pre Source
CWE ID: CWE-119 | SQLWCHAR* _multi_string_alloc_and_expand( LPCSTR in )
{
SQLWCHAR *chr;
int len = 0;
if ( !in )
{
return NULL;
}
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
len ++;
}
chr = malloc(sizeof( SQLWCHAR ) * ( len + 2 ));
len = 0;
while ( in[ len ] != 0 || in[ len + 1 ] != 0 )
{
chr[ len ] = in[ len ];
len ++;
}
chr[ len ++ ] = 0;
chr[ len ++ ] = 0;
return chr;
}
| 169,314 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t BnCrypto::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case INIT_CHECK:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(initCheck());
return OK;
}
case IS_CRYPTO_SUPPORTED:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
reply->writeInt32(isCryptoSchemeSupported(uuid));
return OK;
}
case CREATE_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
size_t opaqueSize = data.readInt32();
void *opaqueData = NULL;
if (opaqueSize > 0) {
opaqueData = malloc(opaqueSize);
data.read(opaqueData, opaqueSize);
}
reply->writeInt32(createPlugin(uuid, opaqueData, opaqueSize));
if (opaqueData != NULL) {
free(opaqueData);
opaqueData = NULL;
}
return OK;
}
case DESTROY_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(destroyPlugin());
return OK;
}
case REQUIRES_SECURE_COMPONENT:
{
CHECK_INTERFACE(ICrypto, data, reply);
const char *mime = data.readCString();
reply->writeInt32(requiresSecureDecoderComponent(mime));
return OK;
}
case DECRYPT:
{
CHECK_INTERFACE(ICrypto, data, reply);
bool secure = data.readInt32() != 0;
CryptoPlugin::Mode mode = (CryptoPlugin::Mode)data.readInt32();
uint8_t key[16];
data.read(key, sizeof(key));
uint8_t iv[16];
data.read(iv, sizeof(iv));
size_t totalSize = data.readInt32();
sp<IMemory> sharedBuffer =
interface_cast<IMemory>(data.readStrongBinder());
int32_t offset = data.readInt32();
int32_t numSubSamples = data.readInt32();
CryptoPlugin::SubSample *subSamples =
new CryptoPlugin::SubSample[numSubSamples];
data.read(
subSamples,
sizeof(CryptoPlugin::SubSample) * numSubSamples);
void *secureBufferId, *dstPtr;
if (secure) {
secureBufferId = reinterpret_cast<void *>(static_cast<uintptr_t>(data.readInt64()));
} else {
dstPtr = calloc(1, totalSize);
}
AString errorDetailMsg;
ssize_t result;
size_t sumSubsampleSizes = 0;
bool overflow = false;
for (int32_t i = 0; i < numSubSamples; ++i) {
CryptoPlugin::SubSample &ss = subSamples[i];
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfEncryptedData) {
sumSubsampleSizes += ss.mNumBytesOfEncryptedData;
} else {
overflow = true;
}
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfClearData) {
sumSubsampleSizes += ss.mNumBytesOfClearData;
} else {
overflow = true;
}
}
if (overflow || sumSubsampleSizes != totalSize) {
result = -EINVAL;
} else if (offset + totalSize > sharedBuffer->size()) {
result = -EINVAL;
} else {
result = decrypt(
secure,
key,
iv,
mode,
sharedBuffer, offset,
subSamples, numSubSamples,
secure ? secureBufferId : dstPtr,
&errorDetailMsg);
}
reply->writeInt32(result);
if (isCryptoError(result)) {
reply->writeCString(errorDetailMsg.c_str());
}
if (!secure) {
if (result >= 0) {
CHECK_LE(result, static_cast<ssize_t>(totalSize));
reply->write(dstPtr, result);
}
free(dstPtr);
dstPtr = NULL;
}
delete[] subSamples;
subSamples = NULL;
return OK;
}
case NOTIFY_RESOLUTION:
{
CHECK_INTERFACE(ICrypto, data, reply);
int32_t width = data.readInt32();
int32_t height = data.readInt32();
notifyResolution(width, height);
return OK;
}
case SET_MEDIADRM_SESSION:
{
CHECK_INTERFACE(IDrm, data, reply);
Vector<uint8_t> sessionId;
readVector(data, sessionId);
reply->writeInt32(setMediaDrmSession(sessionId));
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
Commit Message: Fix security vulnerability in ICrypto DO NOT MERGE
b/25800375
Change-Id: I03c9395f7c7de4ac5813a1207452aac57aa39484
CWE ID: CWE-200 | status_t BnCrypto::onTransact(
uint32_t code, const Parcel &data, Parcel *reply, uint32_t flags) {
switch (code) {
case INIT_CHECK:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(initCheck());
return OK;
}
case IS_CRYPTO_SUPPORTED:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
reply->writeInt32(isCryptoSchemeSupported(uuid));
return OK;
}
case CREATE_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
uint8_t uuid[16];
data.read(uuid, sizeof(uuid));
size_t opaqueSize = data.readInt32();
void *opaqueData = NULL;
if (opaqueSize > 0) {
opaqueData = malloc(opaqueSize);
data.read(opaqueData, opaqueSize);
}
reply->writeInt32(createPlugin(uuid, opaqueData, opaqueSize));
if (opaqueData != NULL) {
free(opaqueData);
opaqueData = NULL;
}
return OK;
}
case DESTROY_PLUGIN:
{
CHECK_INTERFACE(ICrypto, data, reply);
reply->writeInt32(destroyPlugin());
return OK;
}
case REQUIRES_SECURE_COMPONENT:
{
CHECK_INTERFACE(ICrypto, data, reply);
const char *mime = data.readCString();
reply->writeInt32(requiresSecureDecoderComponent(mime));
return OK;
}
case DECRYPT:
{
CHECK_INTERFACE(ICrypto, data, reply);
bool secure = data.readInt32() != 0;
CryptoPlugin::Mode mode = (CryptoPlugin::Mode)data.readInt32();
uint8_t key[16];
data.read(key, sizeof(key));
uint8_t iv[16];
data.read(iv, sizeof(iv));
size_t totalSize = data.readInt32();
sp<IMemory> sharedBuffer =
interface_cast<IMemory>(data.readStrongBinder());
int32_t offset = data.readInt32();
int32_t numSubSamples = data.readInt32();
CryptoPlugin::SubSample *subSamples =
new CryptoPlugin::SubSample[numSubSamples];
data.read(
subSamples,
sizeof(CryptoPlugin::SubSample) * numSubSamples);
void *secureBufferId, *dstPtr;
if (secure) {
secureBufferId = reinterpret_cast<void *>(static_cast<uintptr_t>(data.readInt64()));
} else {
dstPtr = calloc(1, totalSize);
}
AString errorDetailMsg;
ssize_t result;
size_t sumSubsampleSizes = 0;
bool overflow = false;
for (int32_t i = 0; i < numSubSamples; ++i) {
CryptoPlugin::SubSample &ss = subSamples[i];
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfEncryptedData) {
sumSubsampleSizes += ss.mNumBytesOfEncryptedData;
} else {
overflow = true;
}
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfClearData) {
sumSubsampleSizes += ss.mNumBytesOfClearData;
} else {
overflow = true;
}
}
if (overflow || sumSubsampleSizes != totalSize) {
result = -EINVAL;
} else if (totalSize > sharedBuffer->size()) {
result = -EINVAL;
} else if ((size_t)offset > sharedBuffer->size() - totalSize) {
result = -EINVAL;
} else {
result = decrypt(
secure,
key,
iv,
mode,
sharedBuffer, offset,
subSamples, numSubSamples,
secure ? secureBufferId : dstPtr,
&errorDetailMsg);
}
reply->writeInt32(result);
if (isCryptoError(result)) {
reply->writeCString(errorDetailMsg.c_str());
}
if (!secure) {
if (result >= 0) {
CHECK_LE(result, static_cast<ssize_t>(totalSize));
reply->write(dstPtr, result);
}
free(dstPtr);
dstPtr = NULL;
}
delete[] subSamples;
subSamples = NULL;
return OK;
}
case NOTIFY_RESOLUTION:
{
CHECK_INTERFACE(ICrypto, data, reply);
int32_t width = data.readInt32();
int32_t height = data.readInt32();
notifyResolution(width, height);
return OK;
}
case SET_MEDIADRM_SESSION:
{
CHECK_INTERFACE(IDrm, data, reply);
Vector<uint8_t> sessionId;
readVector(data, sessionId);
reply->writeInt32(setMediaDrmSession(sessionId));
return OK;
}
default:
return BBinder::onTransact(code, data, reply, flags);
}
}
| 173,959 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void lockd_down_net(struct svc_serv *serv, struct net *net)
{
struct lockd_net *ln = net_generic(net, lockd_net_id);
if (ln->nlmsvc_users) {
if (--ln->nlmsvc_users == 0) {
nlm_shutdown_hosts_net(net);
cancel_delayed_work_sync(&ln->grace_period_end);
locks_end_grace(&ln->lockd_manager);
svc_shutdown_net(serv, net);
dprintk("lockd_down_net: per-net data destroyed; net=%p\n", net);
}
} else {
printk(KERN_ERR "lockd_down_net: no users! task=%p, net=%p\n",
nlmsvc_task, net);
BUG();
}
}
Commit Message: Merge tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux
Pull nfsd updates from Bruce Fields:
"Another RDMA update from Chuck Lever, and a bunch of miscellaneous
bugfixes"
* tag 'nfsd-4.12' of git://linux-nfs.org/~bfields/linux: (26 commits)
nfsd: Fix up the "supattr_exclcreat" attributes
nfsd: encoders mustn't use unitialized values in error cases
nfsd: fix undefined behavior in nfsd4_layout_verify
lockd: fix lockd shutdown race
NFSv4: Fix callback server shutdown
SUNRPC: Refactor svc_set_num_threads()
NFSv4.x/callback: Create the callback service through svc_create_pooled
lockd: remove redundant check on block
svcrdma: Clean out old XDR encoders
svcrdma: Remove the req_map cache
svcrdma: Remove unused RDMA Write completion handler
svcrdma: Reduce size of sge array in struct svc_rdma_op_ctxt
svcrdma: Clean up RPC-over-RDMA backchannel reply processing
svcrdma: Report Write/Reply chunk overruns
svcrdma: Clean up RDMA_ERROR path
svcrdma: Use rdma_rw API in RPC reply path
svcrdma: Introduce local rdma_rw API helpers
svcrdma: Clean up svc_rdma_get_inv_rkey()
svcrdma: Add helper to save pages under I/O
svcrdma: Eliminate RPCRDMA_SQ_DEPTH_MULT
...
CWE ID: CWE-404 | static void lockd_down_net(struct svc_serv *serv, struct net *net)
{
struct lockd_net *ln = net_generic(net, lockd_net_id);
if (ln->nlmsvc_users) {
if (--ln->nlmsvc_users == 0) {
nlm_shutdown_hosts_net(net);
svc_shutdown_net(serv, net);
dprintk("lockd_down_net: per-net data destroyed; net=%p\n", net);
}
} else {
printk(KERN_ERR "lockd_down_net: no users! task=%p, net=%p\n",
nlmsvc_task, net);
BUG();
}
}
| 168,135 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void __ip_select_ident(struct iphdr *iph, int segs)
{
static u32 ip_idents_hashrnd __read_mostly;
u32 hash, id;
net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));
hash = jhash_3words((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol,
ip_idents_hashrnd);
id = ip_idents_reserve(hash, segs);
iph->id = htons(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 | void __ip_select_ident(struct iphdr *iph, int segs)
{
static u32 ip_idents_hashrnd __read_mostly;
static u32 ip_idents_hashrnd_extra __read_mostly;
u32 hash, id;
net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd));
net_get_random_once(&ip_idents_hashrnd_extra, sizeof(ip_idents_hashrnd_extra));
hash = jhash_3words((__force u32)iph->daddr,
(__force u32)iph->saddr,
iph->protocol ^ ip_idents_hashrnd_extra,
ip_idents_hashrnd);
id = ip_idents_reserve(hash, segs);
iph->id = htons(id);
}
| 170,237 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: dissect_ac_if_hdr_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info)
{
gint offset_start;
guint16 bcdADC;
guint8 ver_major;
double ver;
guint8 if_in_collection, i;
audio_conv_info_t *audio_conv_info;
offset_start = offset;
bcdADC = tvb_get_letohs(tvb, offset);
ver_major = USB_AUDIO_BCD44_TO_DEC(bcdADC>>8);
ver = ver_major + USB_AUDIO_BCD44_TO_DEC(bcdADC&0xFF) / 100.0;
proto_tree_add_double_format_value(tree, hf_ac_if_hdr_ver,
tvb, offset, 2, ver, "%2.2f", ver);
audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data;
if(!audio_conv_info) {
audio_conv_info = wmem_new(wmem_file_scope(), audio_conv_info_t);
usb_conv_info->class_data = audio_conv_info;
/* XXX - set reasonable default values for all components
that are not filled in by this function */
}
audio_conv_info->ver_major = ver_major;
offset += 2;
/* version 1 refers to the Basic Audio Device specification,
version 2 is the Audio Device class specification, see above */
if (ver_major==1) {
proto_tree_add_item(tree, hf_ac_if_hdr_total_len,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
if_in_collection = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_ac_if_hdr_bInCollection,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
for (i=0; i<if_in_collection; i++) {
proto_tree_add_item(tree, hf_ac_if_hdr_if_num,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
}
}
return offset-offset_start;
}
Commit Message: Make class "type" for USB conversations.
USB dissectors can't assume that only their class type has been passed around in the conversation. Make explicit check that class type expected matches the dissector and stop/prevent dissection if there isn't a match.
Bug: 12356
Change-Id: Ib23973a4ebd0fbb51952ffc118daf95e3389a209
Reviewed-on: https://code.wireshark.org/review/15212
Petri-Dish: Michael Mann <[email protected]>
Reviewed-by: Martin Kaiser <[email protected]>
Petri-Dish: Martin Kaiser <[email protected]>
Tested-by: Petri Dish Buildbot <[email protected]>
Reviewed-by: Michael Mann <[email protected]>
CWE ID: CWE-476 | dissect_ac_if_hdr_body(tvbuff_t *tvb, gint offset, packet_info *pinfo _U_,
proto_tree *tree, usb_conv_info_t *usb_conv_info)
{
gint offset_start;
guint16 bcdADC;
guint8 ver_major;
double ver;
guint8 if_in_collection, i;
audio_conv_info_t *audio_conv_info;
offset_start = offset;
bcdADC = tvb_get_letohs(tvb, offset);
ver_major = USB_AUDIO_BCD44_TO_DEC(bcdADC>>8);
ver = ver_major + USB_AUDIO_BCD44_TO_DEC(bcdADC&0xFF) / 100.0;
proto_tree_add_double_format_value(tree, hf_ac_if_hdr_ver,
tvb, offset, 2, ver, "%2.2f", ver);
audio_conv_info = (audio_conv_info_t *)usb_conv_info->class_data;
if(!audio_conv_info) {
audio_conv_info = wmem_new(wmem_file_scope(), audio_conv_info_t);
usb_conv_info->class_data = audio_conv_info;
usb_conv_info->class_data_type = USB_CONV_AUDIO;
/* XXX - set reasonable default values for all components
that are not filled in by this function */
} else if (usb_conv_info->class_data_type != USB_CONV_AUDIO) {
/* Don't dissect if another USB type is in the conversation */
return 0;
}
audio_conv_info->ver_major = ver_major;
offset += 2;
/* version 1 refers to the Basic Audio Device specification,
version 2 is the Audio Device class specification, see above */
if (ver_major==1) {
proto_tree_add_item(tree, hf_ac_if_hdr_total_len,
tvb, offset, 2, ENC_LITTLE_ENDIAN);
offset += 2;
if_in_collection = tvb_get_guint8(tvb, offset);
proto_tree_add_item(tree, hf_ac_if_hdr_bInCollection,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
for (i=0; i<if_in_collection; i++) {
proto_tree_add_item(tree, hf_ac_if_hdr_if_num,
tvb, offset, 1, ENC_LITTLE_ENDIAN);
offset++;
}
}
return offset-offset_start;
}
| 167,153 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: CheckClientDownloadRequest(
content::DownloadItem* item,
const CheckDownloadCallback& callback,
DownloadProtectionService* service,
const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager,
BinaryFeatureExtractor* binary_feature_extractor)
: item_(item),
url_chain_(item->GetUrlChain()),
referrer_url_(item->GetReferrerUrl()),
tab_url_(item->GetTabUrl()),
tab_referrer_url_(item->GetTabReferrerUrl()),
zipped_executable_(false),
callback_(callback),
service_(service),
binary_feature_extractor_(binary_feature_extractor),
database_manager_(database_manager),
pingback_enabled_(service_->enabled()),
finished_(false),
type_(ClientDownloadRequest::WIN_EXECUTABLE),
start_time_(base::TimeTicks::Now()),
weakptr_factory_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
item_->AddObserver(this);
}
Commit Message: Add the SandboxedDMGParser and wire it up to the DownloadProtectionService.
BUG=496898,464083
[email protected], [email protected], [email protected], [email protected]
Review URL: https://codereview.chromium.org/1299223006 .
Cr-Commit-Position: refs/heads/master@{#344876}
CWE ID: | CheckClientDownloadRequest(
content::DownloadItem* item,
const CheckDownloadCallback& callback,
DownloadProtectionService* service,
const scoped_refptr<SafeBrowsingDatabaseManager>& database_manager,
BinaryFeatureExtractor* binary_feature_extractor)
: item_(item),
url_chain_(item->GetUrlChain()),
referrer_url_(item->GetReferrerUrl()),
tab_url_(item->GetTabUrl()),
tab_referrer_url_(item->GetTabReferrerUrl()),
archived_executable_(false),
callback_(callback),
service_(service),
binary_feature_extractor_(binary_feature_extractor),
database_manager_(database_manager),
pingback_enabled_(service_->enabled()),
finished_(false),
type_(ClientDownloadRequest::WIN_EXECUTABLE),
start_time_(base::TimeTicks::Now()),
weakptr_factory_(this) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
item_->AddObserver(this);
}
| 171,712 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply)
{
uint8_t buf[NBD_REPLY_SIZE];
uint32_t magic;
ssize_t ret;
ret = read_sync(ioc, buf, sizeof(buf));
if (ret < 0) {
return ret;
}
if (ret != sizeof(buf)) {
LOG("read failed");
return -EINVAL;
}
/* Reply
[ 0 .. 3] magic (NBD_REPLY_MAGIC)
[ 4 .. 7] error (0 == no error)
[ 7 .. 15] handle
*/
magic = ldl_be_p(buf);
reply->error = ldl_be_p(buf + 4);
reply->handle = ldq_be_p(buf + 8);
reply->error = nbd_errno_to_system_errno(reply->error);
if (reply->error == ESHUTDOWN) {
/* This works even on mingw which lacks a native ESHUTDOWN */
LOG("server shutting down");
return -EINVAL;
}
TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32
", handle = %" PRIu64" }",
magic, reply->error, reply->handle);
if (magic != NBD_REPLY_MAGIC) {
LOG("invalid magic (got 0x%" PRIx32 ")", magic);
return -EINVAL;
}
return 0;
}
Commit Message:
CWE ID: CWE-20 | ssize_t nbd_receive_reply(QIOChannel *ioc, NBDReply *reply)
{
uint8_t buf[NBD_REPLY_SIZE];
uint32_t magic;
ssize_t ret;
ret = read_sync(ioc, buf, sizeof(buf));
if (ret <= 0) {
return ret;
}
if (ret != sizeof(buf)) {
LOG("read failed");
return -EINVAL;
}
/* Reply
[ 0 .. 3] magic (NBD_REPLY_MAGIC)
[ 4 .. 7] error (0 == no error)
[ 7 .. 15] handle
*/
magic = ldl_be_p(buf);
reply->error = ldl_be_p(buf + 4);
reply->handle = ldq_be_p(buf + 8);
reply->error = nbd_errno_to_system_errno(reply->error);
if (reply->error == ESHUTDOWN) {
/* This works even on mingw which lacks a native ESHUTDOWN */
LOG("server shutting down");
return -EINVAL;
}
TRACE("Got reply: { magic = 0x%" PRIx32 ", .error = % " PRId32
", handle = %" PRIu64" }",
magic, reply->error, reply->handle);
if (magic != NBD_REPLY_MAGIC) {
LOG("invalid magic (got 0x%" PRIx32 ")", magic);
return -EINVAL;
}
return 0;
}
| 165,450 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: DWORD WtsSessionProcessDelegate::GetExitCode() {
if (!core_)
return CONTROL_C_EXIT;
return core_->GetExitCode();
}
Commit Message: Validate and report peer's PID to WorkerProcessIpcDelegate so it will be able to duplicate handles to and from the worker process.
As a side effect WorkerProcessLauncher::Delegate is now responsible for retrieving the client's PID and deciding whether a launch failed due to a permanent error condition.
BUG=134694
Review URL: https://chromiumcodereview.appspot.com/11143025
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@162778 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | DWORD WtsSessionProcessDelegate::GetExitCode() {
DWORD WtsSessionProcessDelegate::GetProcessId() const {
if (core_)
return 0;
return core_->GetProcessId();
}
bool WtsSessionProcessDelegate::IsPermanentError(int failure_count) const {
if (core_)
return false;
return core_->IsPermanentError(failure_count);
}
| 171,557 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AutofillDownloadManager::StartUploadRequest(
const FormStructure& form,
bool form_was_autofilled,
const FieldTypeSet& available_field_types) {
if (next_upload_request_ > base::Time::Now()) {
VLOG(1) << "AutofillDownloadManager: Upload request is throttled.";
return false;
}
double upload_rate = form_was_autofilled ? GetPositiveUploadRate() :
GetNegativeUploadRate();
if (base::RandDouble() > upload_rate) {
VLOG(1) << "AutofillDownloadManager: Upload request is ignored.";
return false;
}
std::string form_xml;
if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled,
&form_xml))
return false;
FormRequestData request_data;
request_data.form_signatures.push_back(form.FormSignature());
request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD;
return StartRequest(form_xml, request_data);
}
Commit Message: Add support for the "uploadrequired" attribute for Autofill query responses
BUG=84693
TEST=unit_tests --gtest_filter=AutofillDownloadTest.QueryAndUploadTest
Review URL: http://codereview.chromium.org/6969090
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@87729 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool AutofillDownloadManager::StartUploadRequest(
const FormStructure& form,
bool form_was_autofilled,
const FieldTypeSet& available_field_types) {
if (next_upload_request_ > base::Time::Now()) {
VLOG(1) << "AutofillDownloadManager: Upload request is throttled.";
return false;
}
double upload_rate = form_was_autofilled ? GetPositiveUploadRate() :
GetNegativeUploadRate();
if (form.upload_required() == UPLOAD_NOT_REQUIRED ||
(form.upload_required() == USE_UPLOAD_RATES &&
base::RandDouble() > upload_rate)) {
VLOG(1) << "AutofillDownloadManager: Upload request is ignored.";
return false;
}
std::string form_xml;
if (!form.EncodeUploadRequest(available_field_types, form_was_autofilled,
&form_xml))
return false;
FormRequestData request_data;
request_data.form_signatures.push_back(form.FormSignature());
request_data.request_type = AutofillDownloadManager::REQUEST_UPLOAD;
return StartRequest(form_xml, request_data);
}
| 170,446 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool AXNodeObject::canSetValueAttribute() const {
if (equalIgnoringCase(getAttribute(aria_readonlyAttr), "true"))
return false;
if (isProgressIndicator() || isSlider())
return true;
if (isTextControl() && !isNativeTextControl())
return true;
return !isReadOnly();
}
Commit Message: Switch to equalIgnoringASCIICase throughout modules/accessibility
BUG=627682
Review-Url: https://codereview.chromium.org/2793913007
Cr-Commit-Position: refs/heads/master@{#461858}
CWE ID: CWE-254 | bool AXNodeObject::canSetValueAttribute() const {
if (equalIgnoringASCIICase(getAttribute(aria_readonlyAttr), "true"))
return false;
if (isProgressIndicator() || isSlider())
return true;
if (isTextControl() && !isNativeTextControl())
return true;
return !isReadOnly();
}
| 171,909 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void copy_asoundrc(void) {
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
pid_t child = fork();
if (child < 0)
errExit("fork");
if (child == 0) {
drop_privs(0);
int rv = copy_file(src, dest);
if (rv)
fprintf(stderr, "Warning: cannot transfer .asoundrc in private home directory\n");
else {
fs_logger2("clone", dest);
}
_exit(0);
}
waitpid(child, NULL, 0);
if (chown(dest, getuid(), getgid()) < 0)
errExit("chown");
if (chmod(dest, S_IRUSR | S_IWUSR) < 0)
errExit("chmod");
unlink(src);
}
Commit Message: security fix
CWE ID: CWE-269 | static void copy_asoundrc(void) {
char *src = RUN_ASOUNDRC_FILE ;
char *dest;
if (asprintf(&dest, "%s/.asoundrc", cfg.homedir) == -1)
errExit("asprintf");
if (is_link(dest)) {
fprintf(stderr, "Error: %s is a symbolic link\n", dest);
exit(1);
}
copy_file_as_user(src, dest, getuid(), getgid(), S_IRUSR | S_IWUSR); // regular user
fs_logger2("clone", dest);
unlink(src);
}
| 170,096 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool ComponentControllerImpl::BindToRequest(
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceRequest<fuchsia::sys::ComponentController>
controller_request) {
DCHECK(!service_directory_);
DCHECK(!view_provider_binding_);
url_ = GURL(*package.resolved_url);
if (!url_.is_valid()) {
LOG(ERROR) << "Rejected invalid URL: " << url_;
return false;
}
if (controller_request.is_valid()) {
controller_binding_.Bind(std::move(controller_request));
controller_binding_.set_error_handler(
fit::bind_member(this, &ComponentControllerImpl::Kill));
}
runner_->context()->CreateFrame(frame_observer_binding_.NewBinding(),
frame_.NewRequest());
frame_->GetNavigationController(navigation_controller_.NewRequest());
navigation_controller_->LoadUrl(url_.spec(), nullptr);
service_directory_ = std::make_unique<base::fuchsia::ServiceDirectory>(
std::move(startup_info.launch_info.directory_request));
view_provider_binding_ = std::make_unique<
base::fuchsia::ScopedServiceBinding<fuchsia::ui::viewsv1::ViewProvider>>(
service_directory_.get(), this);
return true;
}
Commit Message: [fuchsia] Implement browser tests for WebRunner Context service.
Tests may interact with the WebRunner FIDL services and the underlying
browser objects for end to end testing of service and browser
functionality.
* Add a browser test launcher main() for WebRunner.
* Add some simple navigation tests.
* Wire up GoBack()/GoForward() FIDL calls.
* Add embedded test server resources and initialization logic.
* Add missing deletion & notification calls to BrowserContext dtor.
* Use FIDL events for navigation state changes.
* Bug fixes:
** Move BrowserContext and Screen deletion to PostMainMessageLoopRun(),
so that they may use the MessageLoop during teardown.
** Fix Frame dtor to allow for null WindowTreeHosts (headless case)
** Fix std::move logic in Frame ctor which lead to no WebContents
observer being registered.
Bug: 871594
Change-Id: I36bcbd2436d534d366c6be4eeb54b9f9feadd1ac
Reviewed-on: https://chromium-review.googlesource.com/1164539
Commit-Queue: Kevin Marshall <[email protected]>
Reviewed-by: Wez <[email protected]>
Reviewed-by: Fabrice de Gans-Riberi <[email protected]>
Reviewed-by: Scott Violet <[email protected]>
Cr-Commit-Position: refs/heads/master@{#584155}
CWE ID: CWE-264 | bool ComponentControllerImpl::BindToRequest(
fuchsia::sys::Package package,
fuchsia::sys::StartupInfo startup_info,
fidl::InterfaceRequest<fuchsia::sys::ComponentController>
controller_request) {
DCHECK(!service_directory_);
DCHECK(!view_provider_binding_);
url_ = GURL(*package.resolved_url);
if (!url_.is_valid()) {
LOG(ERROR) << "Rejected invalid URL: " << url_;
return false;
}
if (controller_request.is_valid()) {
controller_binding_.Bind(std::move(controller_request));
controller_binding_.set_error_handler(
fit::bind_member(this, &ComponentControllerImpl::Kill));
}
runner_->context()->CreateFrame(frame_.NewRequest());
frame_->GetNavigationController(navigation_controller_.NewRequest());
navigation_controller_->LoadUrl(url_.spec(), nullptr);
service_directory_ = std::make_unique<base::fuchsia::ServiceDirectory>(
std::move(startup_info.launch_info.directory_request));
view_provider_binding_ = std::make_unique<
base::fuchsia::ScopedServiceBinding<fuchsia::ui::viewsv1::ViewProvider>>(
service_directory_.get(), this);
return true;
}
| 172,148 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool KeyMap::Press(const scoped_refptr<WindowProxy>& window,
const ui::KeyboardCode key_code,
const wchar_t& key) {
if (key_code == ui::VKEY_SHIFT) {
shift_ = !shift_;
} else if (key_code == ui::VKEY_CONTROL) {
control_ = !control_;
} else if (key_code == ui::VKEY_MENU) { // ALT
alt_ = !alt_;
} else if (key_code == ui::VKEY_COMMAND) {
command_ = !command_;
}
int modifiers = 0;
if (shift_ || shifted_keys_.find(key) != shifted_keys_.end()) {
modifiers = modifiers | ui::EF_SHIFT_DOWN;
}
if (control_) {
modifiers = modifiers | ui::EF_CONTROL_DOWN;
}
if (alt_) {
modifiers = modifiers | ui::EF_ALT_DOWN;
}
if (command_) {
VLOG(1) << "Pressing command key on linux!!";
modifiers = modifiers | ui::EF_COMMAND_DOWN;
}
window->SimulateOSKeyPress(key_code, modifiers);
return true;
}
Commit Message: In chromedriver, add /log url to get the contents of the chromedriver log
remotely. Also add a 'chrome.verbose' boolean startup option.
Remove usage of VLOG(1) in chromedriver. We do not need as complicated
logging as in Chrome.
BUG=85241
TEST=none
Review URL: http://codereview.chromium.org/7104085
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@88591 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool KeyMap::Press(const scoped_refptr<WindowProxy>& window,
const ui::KeyboardCode key_code,
const wchar_t& key) {
if (key_code == ui::VKEY_SHIFT) {
shift_ = !shift_;
} else if (key_code == ui::VKEY_CONTROL) {
control_ = !control_;
} else if (key_code == ui::VKEY_MENU) { // ALT
alt_ = !alt_;
} else if (key_code == ui::VKEY_COMMAND) {
command_ = !command_;
}
int modifiers = 0;
if (shift_ || shifted_keys_.find(key) != shifted_keys_.end()) {
modifiers = modifiers | ui::EF_SHIFT_DOWN;
}
if (control_) {
modifiers = modifiers | ui::EF_CONTROL_DOWN;
}
if (alt_) {
modifiers = modifiers | ui::EF_ALT_DOWN;
}
if (command_) {
LOG(INFO) << "Pressing command key on linux!!";
modifiers = modifiers | ui::EF_COMMAND_DOWN;
}
window->SimulateOSKeyPress(key_code, modifiers);
return true;
}
| 170,459 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void DataReductionProxyConfig::InitializeOnIOThread(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
WarmupURLFetcher::CreateCustomProxyConfigCallback
create_custom_proxy_config_callback,
NetworkPropertiesManager* manager,
const std::string& user_agent) {
DCHECK(thread_checker_.CalledOnValidThread());
network_properties_manager_ = manager;
network_properties_manager_->ResetWarmupURLFetchMetrics();
secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory));
warmup_url_fetcher_.reset(new WarmupURLFetcher(
create_custom_proxy_config_callback,
base::BindRepeating(
&DataReductionProxyConfig::HandleWarmupFetcherResponse,
base::Unretained(this)),
base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate,
base::Unretained(this)),
ui_task_runner_, user_agent));
AddDefaultProxyBypassRules();
network_connection_tracker_->AddNetworkConnectionObserver(this);
network_connection_tracker_->GetConnectionType(
&connection_type_,
base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged,
weak_factory_.GetWeakPtr()));
}
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 | void DataReductionProxyConfig::InitializeOnIOThread(
scoped_refptr<network::SharedURLLoaderFactory> url_loader_factory,
WarmupURLFetcher::CreateCustomProxyConfigCallback
create_custom_proxy_config_callback,
NetworkPropertiesManager* manager,
const std::string& user_agent) {
DCHECK(thread_checker_.CalledOnValidThread());
network_properties_manager_ = manager;
network_properties_manager_->ResetWarmupURLFetchMetrics();
if (!params::IsIncludedInHoldbackFieldTrial()) {
secure_proxy_checker_.reset(new SecureProxyChecker(url_loader_factory));
warmup_url_fetcher_.reset(new WarmupURLFetcher(
create_custom_proxy_config_callback,
base::BindRepeating(
&DataReductionProxyConfig::HandleWarmupFetcherResponse,
base::Unretained(this)),
base::BindRepeating(&DataReductionProxyConfig::GetHttpRttEstimate,
base::Unretained(this)),
ui_task_runner_, user_agent));
}
AddDefaultProxyBypassRules();
network_connection_tracker_->AddNetworkConnectionObserver(this);
network_connection_tracker_->GetConnectionType(
&connection_type_,
base::BindOnce(&DataReductionProxyConfig::OnConnectionChanged,
weak_factory_.GetWeakPtr()));
}
| 172,416 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: xsltNumberFormatAlpha(xmlBufferPtr buffer,
double number,
int is_upper)
{
char temp_string[sizeof(double) * CHAR_BIT * sizeof(xmlChar) + 1];
char *pointer;
int i;
char *alpha_list;
double alpha_size = (double)(sizeof(alpha_upper_list) - 1);
/* Build buffer from back */
pointer = &temp_string[sizeof(temp_string)];
*(--pointer) = 0;
alpha_list = (is_upper) ? alpha_upper_list : alpha_lower_list;
for (i = 1; i < (int)sizeof(temp_string); i++) {
number--;
*(--pointer) = alpha_list[((int)fmod(number, alpha_size))];
number /= alpha_size;
if (fabs(number) < 1.0)
break; /* for */
}
xmlBufferCCat(buffer, pointer);
}
Commit Message: Roll libxslt to 891681e3e948f31732229f53cb6db7215f740fc7
BUG=583156,583171
Review URL: https://codereview.chromium.org/1853083002
Cr-Commit-Position: refs/heads/master@{#385338}
CWE ID: CWE-119 | xsltNumberFormatAlpha(xmlBufferPtr buffer,
double number,
int is_upper)
{
char temp_string[sizeof(double) * CHAR_BIT * sizeof(xmlChar) + 1];
char *pointer;
int i;
char *alpha_list;
double alpha_size = (double)(sizeof(alpha_upper_list) - 1);
if (number < 1.0)
return;
/* Build buffer from back */
pointer = &temp_string[sizeof(temp_string)];
*(--pointer) = 0;
alpha_list = (is_upper) ? alpha_upper_list : alpha_lower_list;
for (i = 1; i < (int)sizeof(temp_string); i++) {
number--;
*(--pointer) = alpha_list[((int)fmod(number, alpha_size))];
number /= alpha_size;
if (number < 1.0)
break; /* for */
}
xmlBufferCCat(buffer, pointer);
}
| 173,307 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
{
AC3HeaderInfo *hdr = NULL;
struct eac3_info *info;
int num_blocks, ret;
if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
return AVERROR(ENOMEM);
info = track->eac3_priv;
if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
/* drop the packets until we see a good one */
if (!track->entry) {
av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
ret = 0;
} else
ret = AVERROR_INVALIDDATA;
goto end;
}
info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
num_blocks = hdr->num_blocks;
if (!info->ec3_done) {
/* AC-3 substream must be the first one */
if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
ret = AVERROR(EINVAL);
goto end;
}
/* this should always be the case, given that our AC-3 parser
* concatenates dependent frames to their independent parent */
if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
/* substream ids must be incremental */
if (hdr->substreamid > info->num_ind_sub + 1) {
ret = AVERROR(EINVAL);
goto end;
}
if (hdr->substreamid == info->num_ind_sub + 1) {
avpriv_request_sample(track->par, "Multiple independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
} else if (hdr->substreamid < info->num_ind_sub ||
hdr->substreamid == 0 && info->substream[0].bsid) {
info->ec3_done = 1;
goto concatenate;
}
}
/* fill the info needed for the "dec3" atom */
info->substream[hdr->substreamid].fscod = hdr->sr_code;
info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
info->substream[hdr->substreamid].acmod = hdr->channel_mode;
info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
/* Parse dependent substream(s), if any */
if (pkt->size != hdr->frame_size) {
int cumul_size = hdr->frame_size;
int parent = hdr->substreamid;
while (cumul_size != pkt->size) {
GetBitContext gbc;
int i;
ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
if (ret < 0)
goto end;
if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
ret = AVERROR(EINVAL);
goto end;
}
info->substream[parent].num_dep_sub++;
ret /= 8;
/* header is parsed up to lfeon, but custom channel map may be needed */
init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
/* skip bsid */
skip_bits(&gbc, 5);
/* skip volume control params */
for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
skip_bits(&gbc, 5); // skip dialog normalization
if (get_bits1(&gbc)) {
skip_bits(&gbc, 8); // skip compression gain word
}
}
/* get the dependent stream channel map, if exists */
if (get_bits1(&gbc))
info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
else
info->substream[parent].chan_loc |= hdr->channel_mode;
cumul_size += hdr->frame_size;
}
}
}
concatenate:
if (!info->num_blocks && num_blocks == 6) {
ret = pkt->size;
goto end;
}
else if (info->num_blocks + num_blocks > 6) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if (!info->num_blocks) {
ret = av_packet_ref(&info->pkt, pkt);
if (!ret)
info->num_blocks = num_blocks;
goto end;
} else {
if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
goto end;
memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
info->num_blocks += num_blocks;
info->pkt.duration += pkt->duration;
if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
goto end;
if (info->num_blocks != 6)
goto end;
av_packet_unref(pkt);
av_packet_move_ref(pkt, &info->pkt);
info->num_blocks = 0;
}
ret = pkt->size;
end:
av_free(hdr);
return ret;
}
Commit Message: avformat/movenc: Check that frame_types other than EAC3_FRAME_TYPE_INDEPENDENT have a supported substream id
Fixes: out of array access
Fixes: ffmpeg_bof_1.avi
Found-by: Thuan Pham, Marcel Böhme, Andrew Santosa and Alexandru Razvan Caciulescu with AFLSmart
Signed-off-by: Michael Niedermayer <[email protected]>
CWE ID: CWE-129 | static int handle_eac3(MOVMuxContext *mov, AVPacket *pkt, MOVTrack *track)
{
AC3HeaderInfo *hdr = NULL;
struct eac3_info *info;
int num_blocks, ret;
if (!track->eac3_priv && !(track->eac3_priv = av_mallocz(sizeof(*info))))
return AVERROR(ENOMEM);
info = track->eac3_priv;
if (avpriv_ac3_parse_header(&hdr, pkt->data, pkt->size) < 0) {
/* drop the packets until we see a good one */
if (!track->entry) {
av_log(mov, AV_LOG_WARNING, "Dropping invalid packet from start of the stream\n");
ret = 0;
} else
ret = AVERROR_INVALIDDATA;
goto end;
}
info->data_rate = FFMAX(info->data_rate, hdr->bit_rate / 1000);
num_blocks = hdr->num_blocks;
if (!info->ec3_done) {
/* AC-3 substream must be the first one */
if (hdr->bitstream_id <= 10 && hdr->substreamid != 0) {
ret = AVERROR(EINVAL);
goto end;
}
/* this should always be the case, given that our AC-3 parser
* concatenates dependent frames to their independent parent */
if (hdr->frame_type == EAC3_FRAME_TYPE_INDEPENDENT) {
/* substream ids must be incremental */
if (hdr->substreamid > info->num_ind_sub + 1) {
ret = AVERROR(EINVAL);
goto end;
}
if (hdr->substreamid == info->num_ind_sub + 1) {
avpriv_request_sample(track->par, "Multiple independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
} else if (hdr->substreamid < info->num_ind_sub ||
hdr->substreamid == 0 && info->substream[0].bsid) {
info->ec3_done = 1;
goto concatenate;
}
} else {
if (hdr->substreamid != 0) {
avpriv_request_sample(mov->fc, "Multiple non EAC3 independent substreams");
ret = AVERROR_PATCHWELCOME;
goto end;
}
}
/* fill the info needed for the "dec3" atom */
info->substream[hdr->substreamid].fscod = hdr->sr_code;
info->substream[hdr->substreamid].bsid = hdr->bitstream_id;
info->substream[hdr->substreamid].bsmod = hdr->bitstream_mode;
info->substream[hdr->substreamid].acmod = hdr->channel_mode;
info->substream[hdr->substreamid].lfeon = hdr->lfe_on;
/* Parse dependent substream(s), if any */
if (pkt->size != hdr->frame_size) {
int cumul_size = hdr->frame_size;
int parent = hdr->substreamid;
while (cumul_size != pkt->size) {
GetBitContext gbc;
int i;
ret = avpriv_ac3_parse_header(&hdr, pkt->data + cumul_size, pkt->size - cumul_size);
if (ret < 0)
goto end;
if (hdr->frame_type != EAC3_FRAME_TYPE_DEPENDENT) {
ret = AVERROR(EINVAL);
goto end;
}
info->substream[parent].num_dep_sub++;
ret /= 8;
/* header is parsed up to lfeon, but custom channel map may be needed */
init_get_bits8(&gbc, pkt->data + cumul_size + ret, pkt->size - cumul_size - ret);
/* skip bsid */
skip_bits(&gbc, 5);
/* skip volume control params */
for (i = 0; i < (hdr->channel_mode ? 1 : 2); i++) {
skip_bits(&gbc, 5); // skip dialog normalization
if (get_bits1(&gbc)) {
skip_bits(&gbc, 8); // skip compression gain word
}
}
/* get the dependent stream channel map, if exists */
if (get_bits1(&gbc))
info->substream[parent].chan_loc |= (get_bits(&gbc, 16) >> 5) & 0x1f;
else
info->substream[parent].chan_loc |= hdr->channel_mode;
cumul_size += hdr->frame_size;
}
}
}
concatenate:
if (!info->num_blocks && num_blocks == 6) {
ret = pkt->size;
goto end;
}
else if (info->num_blocks + num_blocks > 6) {
ret = AVERROR_INVALIDDATA;
goto end;
}
if (!info->num_blocks) {
ret = av_packet_ref(&info->pkt, pkt);
if (!ret)
info->num_blocks = num_blocks;
goto end;
} else {
if ((ret = av_grow_packet(&info->pkt, pkt->size)) < 0)
goto end;
memcpy(info->pkt.data + info->pkt.size - pkt->size, pkt->data, pkt->size);
info->num_blocks += num_blocks;
info->pkt.duration += pkt->duration;
if ((ret = av_copy_packet_side_data(&info->pkt, pkt)) < 0)
goto end;
if (info->num_blocks != 6)
goto end;
av_packet_unref(pkt);
av_packet_move_ref(pkt, &info->pkt);
info->num_blocks = 0;
}
ret = pkt->size;
end:
av_free(hdr);
return ret;
}
| 169,159 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int main()
{
gdImagePtr im;
char *buffer;
size_t size;
size = read_test_file(&buffer, "heap_overflow.tga");
im = gdImageCreateFromTgaPtr(size, (void *) buffer);
gdTestAssert(im == NULL);
free(buffer);
return gdNumFailures();
}
Commit Message: Fix OOB reads of the TGA decompression buffer
It is possible to craft TGA files which will overflow the decompression
buffer, but not the image's bitmap. Therefore we also have to check for
potential decompression buffer overflows.
This issue had been reported by Ibrahim El-Sayed to [email protected];
a modified case exposing an off-by-one error of the first patch had been
provided by Konrad Beckmann.
This commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906
as well.
CWE ID: CWE-125 | int main()
{
check_file("heap_overflow_1.tga");
check_file("heap_overflow_2.tga");
return gdNumFailures();
}
static void check_file(char *basename)
{
gdImagePtr im;
char *buffer;
size_t size;
size = read_test_file(&buffer, basename);
im = gdImageCreateFromTgaPtr(size, (void *) buffer);
gdTestAssert(im == NULL);
free(buffer);
}
| 170,121 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void LayerTreeHostQt::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
{
m_nonCompositedContentLayer->removeAllChildren();
if (graphicsLayer)
m_nonCompositedContentLayer->addChild(graphicsLayer);
}
Commit Message: [Qt][WK2] Allow transparent WebViews
https://bugs.webkit.org/show_bug.cgi?id=80608
Reviewed by Tor Arne Vestbø.
Added support for transparentBackground in QQuickWebViewExperimental.
This uses the existing drawsTransparentBackground property in WebKit2.
Also, changed LayerTreeHostQt to set the contentsOpaque flag when the root layer changes,
otherwise the change doesn't take effect.
A new API test was added.
* UIProcess/API/qt/qquickwebview.cpp:
(QQuickWebViewPrivate::setTransparentBackground):
(QQuickWebViewPrivate::transparentBackground):
(QQuickWebViewExperimental::transparentBackground):
(QQuickWebViewExperimental::setTransparentBackground):
* UIProcess/API/qt/qquickwebview_p.h:
* UIProcess/API/qt/qquickwebview_p_p.h:
(QQuickWebViewPrivate):
* UIProcess/API/qt/tests/qquickwebview/tst_qquickwebview.cpp:
(tst_QQuickWebView):
(tst_QQuickWebView::transparentWebViews):
* WebProcess/WebPage/qt/LayerTreeHostQt.cpp:
(WebKit::LayerTreeHostQt::LayerTreeHostQt):
(WebKit::LayerTreeHostQt::setRootCompositingLayer):
git-svn-id: svn://svn.chromium.org/blink/trunk@110254 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-189 | void LayerTreeHostQt::setRootCompositingLayer(WebCore::GraphicsLayer* graphicsLayer)
{
m_nonCompositedContentLayer->removeAllChildren();
m_nonCompositedContentLayer->setContentsOpaque(m_webPage->drawsBackground() && !m_webPage->drawsTransparentBackground());
if (graphicsLayer)
m_nonCompositedContentLayer->addChild(graphicsLayer);
}
| 170,619 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int hfsplus_set_posix_acl(struct inode *inode, struct posix_acl *acl,
int type)
{
int err;
char *xattr_name;
size_t size = 0;
char *value = NULL;
hfs_dbg(ACL_MOD, "[%s]: ino %lu\n", __func__, inode->i_ino);
switch (type) {
case ACL_TYPE_ACCESS:
xattr_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
err = posix_acl_equiv_mode(acl, &inode->i_mode);
if (err < 0)
return err;
}
err = 0;
break;
case ACL_TYPE_DEFAULT:
xattr_name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
if (unlikely(size > HFSPLUS_MAX_INLINE_DATA_SIZE))
return -ENOMEM;
value = (char *)hfsplus_alloc_attr_entry();
if (unlikely(!value))
return -ENOMEM;
err = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (unlikely(err < 0))
goto end_set_acl;
}
err = __hfsplus_setxattr(inode, xattr_name, value, size, 0);
end_set_acl:
hfsplus_destroy_attr_entry((hfsplus_attr_entry *)value);
if (!err)
set_cached_acl(inode, type, acl);
return err;
}
Commit Message: posix_acl: Clear SGID bit when setting file permissions
When file permissions are modified via chmod(2) and the user is not in
the owning group or capable of CAP_FSETID, the setgid bit is cleared in
inode_change_ok(). Setting a POSIX ACL via setxattr(2) sets the file
permissions as well as the new ACL, but doesn't clear the setgid bit in
a similar way; this allows to bypass the check in chmod(2). Fix that.
References: CVE-2016-7097
Reviewed-by: Christoph Hellwig <[email protected]>
Reviewed-by: Jeff Layton <[email protected]>
Signed-off-by: Jan Kara <[email protected]>
Signed-off-by: Andreas Gruenbacher <[email protected]>
CWE ID: CWE-285 | int hfsplus_set_posix_acl(struct inode *inode, struct posix_acl *acl,
int type)
{
int err;
char *xattr_name;
size_t size = 0;
char *value = NULL;
hfs_dbg(ACL_MOD, "[%s]: ino %lu\n", __func__, inode->i_ino);
switch (type) {
case ACL_TYPE_ACCESS:
xattr_name = XATTR_NAME_POSIX_ACL_ACCESS;
if (acl) {
err = posix_acl_update_mode(inode, &inode->i_mode, &acl);
if (err)
return err;
}
err = 0;
break;
case ACL_TYPE_DEFAULT:
xattr_name = XATTR_NAME_POSIX_ACL_DEFAULT;
if (!S_ISDIR(inode->i_mode))
return acl ? -EACCES : 0;
break;
default:
return -EINVAL;
}
if (acl) {
size = posix_acl_xattr_size(acl->a_count);
if (unlikely(size > HFSPLUS_MAX_INLINE_DATA_SIZE))
return -ENOMEM;
value = (char *)hfsplus_alloc_attr_entry();
if (unlikely(!value))
return -ENOMEM;
err = posix_acl_to_xattr(&init_user_ns, acl, value, size);
if (unlikely(err < 0))
goto end_set_acl;
}
err = __hfsplus_setxattr(inode, xattr_name, value, size, 0);
end_set_acl:
hfsplus_destroy_attr_entry((hfsplus_attr_entry *)value);
if (!err)
set_cached_acl(inode, type, acl);
return err;
}
| 166,973 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void usage_exit() {
fprintf(stderr, "Usage: %s <infile> <outfile>\n", exec_name);
exit(EXIT_FAILURE);
}
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 usage_exit() {
void usage_exit(void) {
fprintf(stderr, "Usage: %s <infile> <outfile>\n", exec_name);
exit(EXIT_FAILURE);
}
| 174,475 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */
{
xml_parser *parser;
int auto_detect = 0;
char *encoding_param = NULL;
int encoding_param_len = 0;
char *ns_param = NULL;
int ns_param_len = 0;
XML_Char *encoding;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? "|ss": "|s"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) {
RETURN_FALSE;
}
if (encoding_param != NULL) {
/* The supported encoding types are hardcoded here because
* we are limited to the encodings supported by expat/xmltok.
*/
if (encoding_param_len == 0) {
encoding = XML(default_encoding);
auto_detect = 1;
} else if (strcasecmp(encoding_param, "ISO-8859-1") == 0) {
encoding = "ISO-8859-1";
} else if (strcasecmp(encoding_param, "UTF-8") == 0) {
encoding = "UTF-8";
} else if (strcasecmp(encoding_param, "US-ASCII") == 0) {
encoding = "US-ASCII";
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "unsupported source encoding \"%s\"", encoding_param);
RETURN_FALSE;
}
} else {
encoding = XML(default_encoding);
}
if (ns_support && ns_param == NULL){
ns_param = ":";
}
parser = ecalloc(1, sizeof(xml_parser));
parser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding),
&php_xml_mem_hdlrs, ns_param);
parser->target_encoding = encoding;
parser->case_folding = 1;
parser->object = NULL;
parser->isparsing = 0;
XML_SetUserData(parser->parser, parser);
ZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser);
parser->index = Z_LVAL_P(return_value);
}
/* }}} */
Commit Message:
CWE ID: CWE-119 | static void php_xml_parser_create_impl(INTERNAL_FUNCTION_PARAMETERS, int ns_support) /* {{{ */
{
xml_parser *parser;
int auto_detect = 0;
char *encoding_param = NULL;
int encoding_param_len = 0;
char *ns_param = NULL;
int ns_param_len = 0;
XML_Char *encoding;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, (ns_support ? "|ss": "|s"), &encoding_param, &encoding_param_len, &ns_param, &ns_param_len) == FAILURE) {
RETURN_FALSE;
}
if (encoding_param != NULL) {
/* The supported encoding types are hardcoded here because
* we are limited to the encodings supported by expat/xmltok.
*/
if (encoding_param_len == 0) {
encoding = XML(default_encoding);
auto_detect = 1;
} else if (strcasecmp(encoding_param, "ISO-8859-1") == 0) {
encoding = "ISO-8859-1";
} else if (strcasecmp(encoding_param, "UTF-8") == 0) {
encoding = "UTF-8";
} else if (strcasecmp(encoding_param, "US-ASCII") == 0) {
encoding = "US-ASCII";
} else {
php_error_docref(NULL TSRMLS_CC, E_WARNING, "unsupported source encoding \"%s\"", encoding_param);
RETURN_FALSE;
}
} else {
encoding = XML(default_encoding);
}
if (ns_support && ns_param == NULL){
ns_param = ":";
}
parser = ecalloc(1, sizeof(xml_parser));
parser->parser = XML_ParserCreate_MM((auto_detect ? NULL : encoding),
&php_xml_mem_hdlrs, ns_param);
parser->target_encoding = encoding;
parser->case_folding = 1;
parser->object = NULL;
parser->isparsing = 0;
XML_SetUserData(parser->parser, parser);
ZEND_REGISTER_RESOURCE(return_value, parser,le_xml_parser);
parser->index = Z_LVAL_P(return_value);
}
/* }}} */
| 165,045 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui)
: ConstrainedWebDialogUI(web_ui),
initial_preview_start_time_(base::TimeTicks::Now()),
handler_(NULL),
source_is_modifiable_(true),
tab_closed_(false) {
Profile* profile = Profile::FromWebUI(web_ui);
ChromeURLDataManager::AddDataSource(profile, new PrintPreviewDataSource());
handler_ = new PrintPreviewHandler();
web_ui->AddMessageHandler(handler_);
preview_ui_addr_str_ = GetPrintPreviewUIAddress();
g_print_preview_request_id_map.Get().Set(preview_ui_addr_str_, -1);
}
Commit Message: Print preview: Use an ID instead of memory pointer string in WebUI.
BUG=144051
Review URL: https://chromiumcodereview.appspot.com/10870003
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@153342 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-200 | PrintPreviewUI::PrintPreviewUI(content::WebUI* web_ui)
: ConstrainedWebDialogUI(web_ui),
initial_preview_start_time_(base::TimeTicks::Now()),
id_(g_print_preview_ui_id_map.Get().Add(this)),
handler_(NULL),
source_is_modifiable_(true),
tab_closed_(false) {
Profile* profile = Profile::FromWebUI(web_ui);
ChromeURLDataManager::AddDataSource(profile, new PrintPreviewDataSource());
handler_ = new PrintPreviewHandler();
web_ui->AddMessageHandler(handler_);
g_print_preview_request_id_map.Get().Set(id_, -1);
}
| 170,841 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget)
{
WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container);
WebKitWebViewBasePrivate* priv = webView->priv;
if (WEBKIT_IS_WEB_VIEW_BASE(widget)
&& WebInspectorProxy::isInspectorPage(WEBKIT_WEB_VIEW_BASE(widget)->priv->pageProxy.get())) {
ASSERT(!priv->inspectorView);
priv->inspectorView = widget;
priv->inspectorViewHeight = gMinimumAttachedInspectorHeight;
} else {
GtkAllocation childAllocation;
gtk_widget_get_allocation(widget, &childAllocation);
priv->children.set(widget, childAllocation);
}
gtk_widget_set_parent(widget, GTK_WIDGET(container));
}
Commit Message: [GTK] Inspector should set a default attached height before being attached
https://bugs.webkit.org/show_bug.cgi?id=90767
Reviewed by Xan Lopez.
We are currently using the minimum attached height in
WebKitWebViewBase as the default height for the inspector when
attached. It would be easier for WebKitWebViewBase and embedders
implementing attach() if the inspector already had an attached
height set when it's being attached.
* UIProcess/API/gtk/WebKitWebViewBase.cpp:
(webkitWebViewBaseContainerAdd): Don't initialize
inspectorViewHeight.
(webkitWebViewBaseSetInspectorViewHeight): Allow to set the
inspector view height before having an inpector view, but only
queue a resize when the view already has an inspector view.
* UIProcess/API/gtk/tests/TestInspector.cpp:
(testInspectorDefault):
(testInspectorManualAttachDetach):
* UIProcess/gtk/WebInspectorProxyGtk.cpp:
(WebKit::WebInspectorProxy::platformAttach): Set the default
attached height before attach the inspector view.
git-svn-id: svn://svn.chromium.org/blink/trunk@124479 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-399 | static void webkitWebViewBaseContainerAdd(GtkContainer* container, GtkWidget* widget)
{
WebKitWebViewBase* webView = WEBKIT_WEB_VIEW_BASE(container);
WebKitWebViewBasePrivate* priv = webView->priv;
if (WEBKIT_IS_WEB_VIEW_BASE(widget)
&& WebInspectorProxy::isInspectorPage(WEBKIT_WEB_VIEW_BASE(widget)->priv->pageProxy.get())) {
ASSERT(!priv->inspectorView);
priv->inspectorView = widget;
} else {
GtkAllocation childAllocation;
gtk_widget_get_allocation(widget, &childAllocation);
priv->children.set(widget, childAllocation);
}
gtk_widget_set_parent(widget, GTK_WIDGET(container));
}
| 171,052 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int sequencer_write(int dev, struct file *file, const char __user *buf, int count)
{
unsigned char event_rec[EV_SZ], ev_code;
int p = 0, c, ev_size;
int mode = translate_mode(file);
dev = dev >> 4;
DEB(printk("sequencer_write(dev=%d, count=%d)\n", dev, count));
if (mode == OPEN_READ)
return -EIO;
c = count;
while (c >= 4)
{
if (copy_from_user((char *) event_rec, &(buf)[p], 4))
goto out;
ev_code = event_rec[0];
if (ev_code == SEQ_FULLSIZE)
{
int err, fmt;
dev = *(unsigned short *) &event_rec[2];
if (dev < 0 || dev >= max_synthdev || synth_devs[dev] == NULL)
return -ENXIO;
if (!(synth_open_mask & (1 << dev)))
return -ENXIO;
fmt = (*(short *) &event_rec[0]) & 0xffff;
err = synth_devs[dev]->load_patch(dev, fmt, buf, p + 4, c, 0);
if (err < 0)
return err;
return err;
}
if (ev_code >= 128)
{
if (seq_mode == SEQ_2 && ev_code == SEQ_EXTENDED)
{
printk(KERN_WARNING "Sequencer: Invalid level 2 event %x\n", ev_code);
return -EINVAL;
}
ev_size = 8;
if (c < ev_size)
{
if (!seq_playing)
seq_startplay();
return count - c;
}
if (copy_from_user((char *)&event_rec[4],
&(buf)[p + 4], 4))
goto out;
}
else
{
if (seq_mode == SEQ_2)
{
printk(KERN_WARNING "Sequencer: 4 byte event in level 2 mode\n");
return -EINVAL;
}
ev_size = 4;
if (event_rec[0] != SEQ_MIDIPUTC)
obsolete_api_used = 1;
}
if (event_rec[0] == SEQ_MIDIPUTC)
{
if (!midi_opened[event_rec[2]])
{
int err, mode;
int dev = event_rec[2];
if (dev >= max_mididev || midi_devs[dev]==NULL)
{
/*printk("Sequencer Error: Nonexistent MIDI device %d\n", dev);*/
return -ENXIO;
}
mode = translate_mode(file);
if ((err = midi_devs[dev]->open(dev, mode,
sequencer_midi_input, sequencer_midi_output)) < 0)
{
seq_reset();
printk(KERN_WARNING "Sequencer Error: Unable to open Midi #%d\n", dev);
return err;
}
midi_opened[dev] = 1;
}
}
if (!seq_queue(event_rec, (file->f_flags & (O_NONBLOCK) ? 1 : 0)))
{
int processed = count - c;
if (!seq_playing)
seq_startplay();
if (!processed && (file->f_flags & O_NONBLOCK))
return -EAGAIN;
else
return processed;
}
p += ev_size;
c -= ev_size;
}
if (!seq_playing)
seq_startplay();
out:
return count;
}
Commit Message: sound/oss: remove offset from load_patch callbacks
Was: [PATCH] sound/oss/midi_synth: prevent underflow, use of
uninitialized value, and signedness issue
The offset passed to midi_synth_load_patch() can be essentially
arbitrary. If it's greater than the header length, this will result in
a copy_from_user(dst, src, negative_val). While this will just return
-EFAULT on x86, on other architectures this may cause memory corruption.
Additionally, the length field of the sysex_info structure may not be
initialized prior to its use. Finally, a signed comparison may result
in an unintentionally large loop.
On suggestion by Takashi Iwai, version two removes the offset argument
from the load_patch callbacks entirely, which also resolves similar
issues in opl3. Compile tested only.
v3 adjusts comments and hopefully gets copy offsets right.
Signed-off-by: Dan Rosenberg <[email protected]>
Signed-off-by: Takashi Iwai <[email protected]>
CWE ID: CWE-189 | int sequencer_write(int dev, struct file *file, const char __user *buf, int count)
{
unsigned char event_rec[EV_SZ], ev_code;
int p = 0, c, ev_size;
int mode = translate_mode(file);
dev = dev >> 4;
DEB(printk("sequencer_write(dev=%d, count=%d)\n", dev, count));
if (mode == OPEN_READ)
return -EIO;
c = count;
while (c >= 4)
{
if (copy_from_user((char *) event_rec, &(buf)[p], 4))
goto out;
ev_code = event_rec[0];
if (ev_code == SEQ_FULLSIZE)
{
int err, fmt;
dev = *(unsigned short *) &event_rec[2];
if (dev < 0 || dev >= max_synthdev || synth_devs[dev] == NULL)
return -ENXIO;
if (!(synth_open_mask & (1 << dev)))
return -ENXIO;
fmt = (*(short *) &event_rec[0]) & 0xffff;
err = synth_devs[dev]->load_patch(dev, fmt, buf + p, c, 0);
if (err < 0)
return err;
return err;
}
if (ev_code >= 128)
{
if (seq_mode == SEQ_2 && ev_code == SEQ_EXTENDED)
{
printk(KERN_WARNING "Sequencer: Invalid level 2 event %x\n", ev_code);
return -EINVAL;
}
ev_size = 8;
if (c < ev_size)
{
if (!seq_playing)
seq_startplay();
return count - c;
}
if (copy_from_user((char *)&event_rec[4],
&(buf)[p + 4], 4))
goto out;
}
else
{
if (seq_mode == SEQ_2)
{
printk(KERN_WARNING "Sequencer: 4 byte event in level 2 mode\n");
return -EINVAL;
}
ev_size = 4;
if (event_rec[0] != SEQ_MIDIPUTC)
obsolete_api_used = 1;
}
if (event_rec[0] == SEQ_MIDIPUTC)
{
if (!midi_opened[event_rec[2]])
{
int err, mode;
int dev = event_rec[2];
if (dev >= max_mididev || midi_devs[dev]==NULL)
{
/*printk("Sequencer Error: Nonexistent MIDI device %d\n", dev);*/
return -ENXIO;
}
mode = translate_mode(file);
if ((err = midi_devs[dev]->open(dev, mode,
sequencer_midi_input, sequencer_midi_output)) < 0)
{
seq_reset();
printk(KERN_WARNING "Sequencer Error: Unable to open Midi #%d\n", dev);
return err;
}
midi_opened[dev] = 1;
}
}
if (!seq_queue(event_rec, (file->f_flags & (O_NONBLOCK) ? 1 : 0)))
{
int processed = count - c;
if (!seq_playing)
seq_startplay();
if (!processed && (file->f_flags & O_NONBLOCK))
return -EAGAIN;
else
return processed;
}
p += ev_size;
c -= ev_size;
}
if (!seq_playing)
seq_startplay();
out:
return count;
}
| 165,894 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) {
return ::SanitizeFrontendURL(url, content::kChromeDevToolsScheme,
chrome::kChromeUIDevToolsHost, SanitizeFrontendPath(url.path()), true);
}
Commit Message: DevTools: move front-end URL handling to DevToolsUIBindingds
BUG=662859
Review-Url: https://codereview.chromium.org/2607833002
Cr-Commit-Position: refs/heads/master@{#440926}
CWE ID: CWE-200 | GURL DevToolsUI::SanitizeFrontendURL(const GURL& url) {
| 172,461 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool SyncManager::SyncInternal::Init(
const FilePath& database_location,
const WeakHandle<JsEventHandler>& event_handler,
const std::string& sync_server_and_path,
int port,
bool use_ssl,
const scoped_refptr<base::TaskRunner>& blocking_task_runner,
HttpPostProviderFactory* post_factory,
ModelSafeWorkerRegistrar* model_safe_worker_registrar,
browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor,
ChangeDelegate* change_delegate,
const std::string& user_agent,
const SyncCredentials& credentials,
bool enable_sync_tabs_for_other_clients,
sync_notifier::SyncNotifier* sync_notifier,
const std::string& restored_key_for_bootstrapping,
TestingMode testing_mode,
Encryptor* encryptor,
UnrecoverableErrorHandler* unrecoverable_error_handler,
ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
CHECK(!initialized_);
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "Starting SyncInternal initialization.";
weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
blocking_task_runner_ = blocking_task_runner;
registrar_ = model_safe_worker_registrar;
change_delegate_ = change_delegate;
testing_mode_ = testing_mode;
enable_sync_tabs_for_other_clients_ = enable_sync_tabs_for_other_clients;
sync_notifier_.reset(sync_notifier);
AddObserver(&js_sync_manager_observer_);
SetJsEventHandler(event_handler);
AddObserver(&debug_info_event_listener_);
database_path_ = database_location.Append(
syncable::Directory::kSyncDatabaseFilename);
encryptor_ = encryptor;
unrecoverable_error_handler_ = unrecoverable_error_handler;
report_unrecoverable_error_function_ = report_unrecoverable_error_function;
share_.directory.reset(
new syncable::Directory(encryptor_,
unrecoverable_error_handler_,
report_unrecoverable_error_function_));
connection_manager_.reset(new SyncAPIServerConnectionManager(
sync_server_and_path, port, use_ssl, user_agent, post_factory));
net::NetworkChangeNotifier::AddIPAddressObserver(this);
observing_ip_address_changes_ = true;
connection_manager()->AddListener(this);
if (testing_mode_ == NON_TEST) {
DVLOG(1) << "Sync is bringing up SyncSessionContext.";
std::vector<SyncEngineEventListener*> listeners;
listeners.push_back(&allstatus_);
listeners.push_back(this);
SyncSessionContext* context = new SyncSessionContext(
connection_manager_.get(),
directory(),
model_safe_worker_registrar,
extensions_activity_monitor,
listeners,
&debug_info_event_listener_,
&traffic_recorder_);
context->set_account_name(credentials.email);
scheduler_.reset(new SyncScheduler(name_, context, new Syncer()));
}
bool signed_in = SignIn(credentials);
if (signed_in) {
if (scheduler()) {
scheduler()->Start(
browser_sync::SyncScheduler::CONFIGURATION_MODE, base::Closure());
}
initialized_ = true;
ReadTransaction trans(FROM_HERE, GetUserShare());
trans.GetCryptographer()->Bootstrap(restored_key_for_bootstrapping);
trans.GetCryptographer()->AddObserver(this);
}
FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
OnInitializationComplete(
MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
signed_in));
if (!signed_in && testing_mode_ == NON_TEST)
return false;
sync_notifier_->AddObserver(this);
return signed_in;
}
Commit Message: [Sync] Cleanup all tab sync enabling logic now that its on by default.
BUG=none
TEST=
Review URL: https://chromiumcodereview.appspot.com/10443046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@139462 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-362 | bool SyncManager::SyncInternal::Init(
const FilePath& database_location,
const WeakHandle<JsEventHandler>& event_handler,
const std::string& sync_server_and_path,
int port,
bool use_ssl,
const scoped_refptr<base::TaskRunner>& blocking_task_runner,
HttpPostProviderFactory* post_factory,
ModelSafeWorkerRegistrar* model_safe_worker_registrar,
browser_sync::ExtensionsActivityMonitor* extensions_activity_monitor,
ChangeDelegate* change_delegate,
const std::string& user_agent,
const SyncCredentials& credentials,
sync_notifier::SyncNotifier* sync_notifier,
const std::string& restored_key_for_bootstrapping,
TestingMode testing_mode,
Encryptor* encryptor,
UnrecoverableErrorHandler* unrecoverable_error_handler,
ReportUnrecoverableErrorFunction report_unrecoverable_error_function) {
CHECK(!initialized_);
DCHECK(thread_checker_.CalledOnValidThread());
DVLOG(1) << "Starting SyncInternal initialization.";
weak_handle_this_ = MakeWeakHandle(weak_ptr_factory_.GetWeakPtr());
blocking_task_runner_ = blocking_task_runner;
registrar_ = model_safe_worker_registrar;
change_delegate_ = change_delegate;
testing_mode_ = testing_mode;
sync_notifier_.reset(sync_notifier);
AddObserver(&js_sync_manager_observer_);
SetJsEventHandler(event_handler);
AddObserver(&debug_info_event_listener_);
database_path_ = database_location.Append(
syncable::Directory::kSyncDatabaseFilename);
encryptor_ = encryptor;
unrecoverable_error_handler_ = unrecoverable_error_handler;
report_unrecoverable_error_function_ = report_unrecoverable_error_function;
share_.directory.reset(
new syncable::Directory(encryptor_,
unrecoverable_error_handler_,
report_unrecoverable_error_function_));
connection_manager_.reset(new SyncAPIServerConnectionManager(
sync_server_and_path, port, use_ssl, user_agent, post_factory));
net::NetworkChangeNotifier::AddIPAddressObserver(this);
observing_ip_address_changes_ = true;
connection_manager()->AddListener(this);
if (testing_mode_ == NON_TEST) {
DVLOG(1) << "Sync is bringing up SyncSessionContext.";
std::vector<SyncEngineEventListener*> listeners;
listeners.push_back(&allstatus_);
listeners.push_back(this);
SyncSessionContext* context = new SyncSessionContext(
connection_manager_.get(),
directory(),
model_safe_worker_registrar,
extensions_activity_monitor,
listeners,
&debug_info_event_listener_,
&traffic_recorder_);
context->set_account_name(credentials.email);
scheduler_.reset(new SyncScheduler(name_, context, new Syncer()));
}
bool signed_in = SignIn(credentials);
if (signed_in) {
if (scheduler()) {
scheduler()->Start(
browser_sync::SyncScheduler::CONFIGURATION_MODE, base::Closure());
}
initialized_ = true;
ReadTransaction trans(FROM_HERE, GetUserShare());
trans.GetCryptographer()->Bootstrap(restored_key_for_bootstrapping);
trans.GetCryptographer()->AddObserver(this);
}
FOR_EACH_OBSERVER(SyncManager::Observer, observers_,
OnInitializationComplete(
MakeWeakHandle(weak_ptr_factory_.GetWeakPtr()),
signed_in));
if (!signed_in && testing_mode_ == NON_TEST)
return false;
sync_notifier_->AddObserver(this);
return signed_in;
}
| 170,793 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static EAS_RESULT Parse_wave (SDLS_SYNTHESIZER_DATA *pDLSData, EAS_I32 pos, EAS_U16 waveIndex)
{
EAS_RESULT result;
EAS_U32 temp;
EAS_I32 size;
EAS_I32 endChunk;
EAS_I32 chunkPos;
EAS_I32 wsmpPos = 0;
EAS_I32 fmtPos = 0;
EAS_I32 dataPos = 0;
EAS_I32 dataSize = 0;
S_WSMP_DATA *p;
void *pSample;
S_WSMP_DATA wsmp;
/* seek to start of chunk */
chunkPos = pos + 12;
if ((result = EAS_HWFileSeek(pDLSData->hwInstData, pDLSData->fileHandle, pos)) != EAS_SUCCESS)
return result;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* make sure it is a wave chunk */
if (temp != CHUNK_WAVE)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Offset in ptbl does not point to wave chunk\n"); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* read to end of chunk */
pos = chunkPos;
endChunk = pos + size;
while (pos < endChunk)
{
chunkPos = pos;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_WSMP:
wsmpPos = chunkPos + 8;
break;
case CHUNK_FMT:
fmtPos = chunkPos + 8;
break;
case CHUNK_DATA:
dataPos = chunkPos + 8;
dataSize = size;
break;
default:
break;
}
}
if (dataSize > MAX_DLS_WAVE_SIZE)
{
return EAS_ERROR_SOUND_LIBRARY;
}
/* for first pass, use temporary variable */
if (pDLSData->pDLS == NULL)
p = &wsmp;
else
p = &pDLSData->wsmpData[waveIndex];
/* set the defaults */
p->fineTune = 0;
p->unityNote = 60;
p->gain = 0;
p->loopStart = 0;
p->loopLength = 0;
/* must have a fmt chunk */
if (!fmtPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no fmt chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a data chunk */
if (!dataPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no data chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* parse the wsmp chunk */
if (wsmpPos)
{
if ((result = Parse_wsmp(pDLSData, wsmpPos, p)) != EAS_SUCCESS)
return result;
}
/* parse the fmt chunk */
if ((result = Parse_fmt(pDLSData, fmtPos, p)) != EAS_SUCCESS)
return result;
/* calculate the size of the wavetable needed. We need only half
* the memory for 16-bit samples when in 8-bit mode, and we need
* double the memory for 8-bit samples in 16-bit mode. For
* unlooped samples, we may use ADPCM. If so, we need only 1/4
* the memory.
*
* We also need to add one for looped samples to allow for
* the first sample to be copied to the end of the loop.
*/
/* use ADPCM encode for unlooped 16-bit samples if ADPCM is enabled */
/*lint -e{506} -e{774} groundwork for future version to support 8 & 16 bit */
if (bitDepth == 8)
{
if (p->bitsPerSample == 8)
size = dataSize;
else
/*lint -e{704} use shift for performance */
size = dataSize >> 1;
if (p->loopLength)
size++;
}
else
{
if (p->bitsPerSample == 16)
size = dataSize;
else
/*lint -e{703} use shift for performance */
size = dataSize << 1;
if (p->loopLength)
size += 2;
}
/* for first pass, add size to wave pool size and return */
if (pDLSData->pDLS == NULL)
{
pDLSData->wavePoolSize += (EAS_U32) size;
return EAS_SUCCESS;
}
/* allocate memory and read in the sample data */
pSample = pDLSData->pDLS->pDLSSamples + pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleOffsets[waveIndex] = pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleLen[waveIndex] = (EAS_U32) size;
pDLSData->wavePoolOffset += (EAS_U32) size;
if (pDLSData->wavePoolOffset > pDLSData->wavePoolSize)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Wave pool exceeded allocation\n"); */ }
return EAS_ERROR_SOUND_LIBRARY;
}
if ((result = Parse_data(pDLSData, dataPos, dataSize, p, pSample)) != EAS_SUCCESS)
return result;
return EAS_SUCCESS;
}
Commit Message: DLS parser: fix wave pool size check.
Bug: 21132860.
Change-Id: I8ae872ea2cc2e8fec5fa0b7815f0b6b31ce744ff
(cherry picked from commit 2d7f8e1be2241e48458f5d3cab5e90be2b07c699)
CWE ID: CWE-189 | static EAS_RESULT Parse_wave (SDLS_SYNTHESIZER_DATA *pDLSData, EAS_I32 pos, EAS_U16 waveIndex)
{
EAS_RESULT result;
EAS_U32 temp;
EAS_I32 size;
EAS_I32 endChunk;
EAS_I32 chunkPos;
EAS_I32 wsmpPos = 0;
EAS_I32 fmtPos = 0;
EAS_I32 dataPos = 0;
EAS_I32 dataSize = 0;
S_WSMP_DATA *p;
void *pSample;
S_WSMP_DATA wsmp;
/* seek to start of chunk */
chunkPos = pos + 12;
if ((result = EAS_HWFileSeek(pDLSData->hwInstData, pDLSData->fileHandle, pos)) != EAS_SUCCESS)
return result;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* make sure it is a wave chunk */
if (temp != CHUNK_WAVE)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Offset in ptbl does not point to wave chunk\n"); */ }
return EAS_ERROR_FILE_FORMAT;
}
/* read to end of chunk */
pos = chunkPos;
endChunk = pos + size;
while (pos < endChunk)
{
chunkPos = pos;
/* get the chunk type */
if ((result = NextChunk(pDLSData, &pos, &temp, &size)) != EAS_SUCCESS)
return result;
/* parse useful chunks */
switch (temp)
{
case CHUNK_WSMP:
wsmpPos = chunkPos + 8;
break;
case CHUNK_FMT:
fmtPos = chunkPos + 8;
break;
case CHUNK_DATA:
dataPos = chunkPos + 8;
dataSize = size;
break;
default:
break;
}
}
if (dataSize < 0 || dataSize > MAX_DLS_WAVE_SIZE)
{
return EAS_ERROR_SOUND_LIBRARY;
}
/* for first pass, use temporary variable */
if (pDLSData->pDLS == NULL)
p = &wsmp;
else
p = &pDLSData->wsmpData[waveIndex];
/* set the defaults */
p->fineTune = 0;
p->unityNote = 60;
p->gain = 0;
p->loopStart = 0;
p->loopLength = 0;
/* must have a fmt chunk */
if (!fmtPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no fmt chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* must have a data chunk */
if (!dataPos)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "DLS wave chunk has no data chunk\n"); */ }
return EAS_ERROR_UNRECOGNIZED_FORMAT;
}
/* parse the wsmp chunk */
if (wsmpPos)
{
if ((result = Parse_wsmp(pDLSData, wsmpPos, p)) != EAS_SUCCESS)
return result;
}
/* parse the fmt chunk */
if ((result = Parse_fmt(pDLSData, fmtPos, p)) != EAS_SUCCESS)
return result;
/* calculate the size of the wavetable needed. We need only half
* the memory for 16-bit samples when in 8-bit mode, and we need
* double the memory for 8-bit samples in 16-bit mode. For
* unlooped samples, we may use ADPCM. If so, we need only 1/4
* the memory.
*
* We also need to add one for looped samples to allow for
* the first sample to be copied to the end of the loop.
*/
/* use ADPCM encode for unlooped 16-bit samples if ADPCM is enabled */
/*lint -e{506} -e{774} groundwork for future version to support 8 & 16 bit */
if (bitDepth == 8)
{
if (p->bitsPerSample == 8)
size = dataSize;
else
/*lint -e{704} use shift for performance */
size = dataSize >> 1;
if (p->loopLength)
size++;
}
else
{
if (p->bitsPerSample == 16)
size = dataSize;
else
/*lint -e{703} use shift for performance */
size = dataSize << 1;
if (p->loopLength)
size += 2;
}
/* for first pass, add size to wave pool size and return */
if (pDLSData->pDLS == NULL)
{
pDLSData->wavePoolSize += (EAS_U32) size;
return EAS_SUCCESS;
}
/* allocate memory and read in the sample data */
pSample = pDLSData->pDLS->pDLSSamples + pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleOffsets[waveIndex] = pDLSData->wavePoolOffset;
pDLSData->pDLS->pDLSSampleLen[waveIndex] = (EAS_U32) size;
pDLSData->wavePoolOffset += (EAS_U32) size;
if (pDLSData->wavePoolOffset > pDLSData->wavePoolSize)
{
{ /* dpp: EAS_ReportEx(_EAS_SEVERITY_ERROR, "Wave pool exceeded allocation\n"); */ }
return EAS_ERROR_SOUND_LIBRARY;
}
if ((result = Parse_data(pDLSData, dataPos, dataSize, p, pSample)) != EAS_SUCCESS)
return result;
return EAS_SUCCESS;
}
| 173,356 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
WebContentsImpl* focused_web_contents = GetFocusedWebContents();
if (focused_web_contents->ShowingInterstitialPage()) {
return static_cast<RenderFrameHostImpl*>(
focused_web_contents->GetRenderManager()
->interstitial_page()
->GetMainFrame())
->GetRenderWidgetHost();
}
return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
}
Commit Message: Don't show current RenderWidgetHostView while interstitial is showing.
Also moves interstitial page tracking from RenderFrameHostManager to
WebContents, since interstitial pages are not frame-specific. This was
necessary for subframes to detect if an interstitial page is showing.
BUG=729105
TEST=See comment 13 of bug for repro steps
CQ_INCLUDE_TRYBOTS=master.tryserver.chromium.linux:linux_site_isolation
Review-Url: https://codereview.chromium.org/2938313002
Cr-Commit-Position: refs/heads/master@{#480117}
CWE ID: CWE-20 | RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
WebContentsImpl* focused_web_contents = GetFocusedWebContents();
if (focused_web_contents->ShowingInterstitialPage()) {
return static_cast<RenderFrameHostImpl*>(
focused_web_contents->interstitial_page_->GetMainFrame())
->GetRenderWidgetHost();
}
return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
}
| 172,330 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: long mkvparser::UnserializeInt(IMkvReader* pReader, long long pos, long size,
long long& result) {
assert(pReader);
assert(pos >= 0);
assert(size > 0);
assert(size <= 8);
{
signed char b;
const long status = pReader->Read(pos, 1, (unsigned char*)&b);
if (status < 0)
return status;
result = b;
++pos;
}
for (long i = 1; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
return 0; // success
}
Commit Message: external/libvpx/libwebm: Update snapshot
Update libwebm snapshot. This update contains security fixes from upstream.
Upstream git hash: 229f49347d19b0ca0941e072b199a242ef6c5f2b
BUG=23167726
Change-Id: Id3e140e7b31ae11294724b1ecfe2e9c83b4d4207
(cherry picked from commit d0281a15b3c6bd91756e453cc9398c5ef412d99a)
CWE ID: CWE-20 | long mkvparser::UnserializeInt(IMkvReader* pReader, long long pos, long size,
long UnserializeInt(IMkvReader* pReader, long long pos, long long size,
long long& result_ref) {
if (!pReader || pos < 0 || size < 1 || size > 8)
return E_FILE_FORMAT_INVALID;
signed char first_byte = 0;
const long status = pReader->Read(pos, 1, (unsigned char*)&first_byte);
if (status < 0)
return status;
unsigned long long result = first_byte;
++pos;
for (long i = 1; i < size; ++i) {
unsigned char b;
const long status = pReader->Read(pos, 1, &b);
if (status < 0)
return status;
result <<= 8;
result |= b;
++pos;
}
result_ref = static_cast<long long>(result);
return 0;
}
| 173,866 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v = CALLOC_STRUCT(vrend_vertex_element_array);
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (!v)
return ENOMEM;
if (num_elements > PIPE_MAX_ATTRIBS)
return EINVAL;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
desc = util_format_description(elements[i].src_format);
if (!desc) {
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
if (vrend_state.have_vertex_attrib_binding) {
glGenVertexArrays(1, &v->id);
glBindVertexArray(v->id);
for (i = 0; i < num_elements; i++) {
struct vrend_vertex_element *ve = &v->elements[i];
if (util_format_is_pure_integer(ve->base.src_format))
glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset);
else
glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset);
glVertexAttribBinding(i, ve->base.vertex_buffer_index);
glVertexBindingDivisor(i, ve->base.instance_divisor);
glEnableVertexAttribArray(i);
}
}
ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle,
VIRGL_OBJECT_VERTEX_ELEMENTS);
if (!ret_handle) {
FREE(v);
return ENOMEM;
}
return 0;
}
Commit Message:
CWE ID: CWE-772 | int vrend_create_vertex_elements_state(struct vrend_context *ctx,
uint32_t handle,
unsigned num_elements,
const struct pipe_vertex_element *elements)
{
struct vrend_vertex_element_array *v;
const struct util_format_description *desc;
GLenum type;
int i;
uint32_t ret_handle;
if (num_elements > PIPE_MAX_ATTRIBS)
return EINVAL;
v = CALLOC_STRUCT(vrend_vertex_element_array);
if (!v)
return ENOMEM;
v->count = num_elements;
for (i = 0; i < num_elements; i++) {
memcpy(&v->elements[i].base, &elements[i], sizeof(struct pipe_vertex_element));
desc = util_format_description(elements[i].src_format);
if (!desc) {
FREE(v);
return EINVAL;
}
type = GL_FALSE;
if (desc->channel[0].type == UTIL_FORMAT_TYPE_FLOAT) {
if (desc->channel[0].size == 32)
type = GL_FLOAT;
else if (desc->channel[0].size == 64)
type = GL_DOUBLE;
else if (desc->channel[0].size == 16)
type = GL_HALF_FLOAT;
} else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 8)
type = GL_UNSIGNED_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 8)
type = GL_BYTE;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 16)
type = GL_UNSIGNED_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 16)
type = GL_SHORT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_UNSIGNED &&
desc->channel[0].size == 32)
type = GL_UNSIGNED_INT;
else if (desc->channel[0].type == UTIL_FORMAT_TYPE_SIGNED &&
desc->channel[0].size == 32)
type = GL_INT;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SSCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_SNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_SNORM)
type = GL_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R10G10B10A2_USCALED ||
elements[i].src_format == PIPE_FORMAT_R10G10B10A2_UNORM ||
elements[i].src_format == PIPE_FORMAT_B10G10R10A2_UNORM)
type = GL_UNSIGNED_INT_2_10_10_10_REV;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
type = GL_UNSIGNED_INT_10F_11F_11F_REV;
if (type == GL_FALSE) {
report_context_error(ctx, VIRGL_ERROR_CTX_ILLEGAL_VERTEX_FORMAT, elements[i].src_format);
FREE(v);
return EINVAL;
}
v->elements[i].type = type;
if (desc->channel[0].normalized)
v->elements[i].norm = GL_TRUE;
if (desc->nr_channels == 4 && desc->swizzle[0] == UTIL_FORMAT_SWIZZLE_Z)
v->elements[i].nr_chan = GL_BGRA;
else if (elements[i].src_format == PIPE_FORMAT_R11G11B10_FLOAT)
v->elements[i].nr_chan = 3;
else
v->elements[i].nr_chan = desc->nr_channels;
}
if (vrend_state.have_vertex_attrib_binding) {
glGenVertexArrays(1, &v->id);
glBindVertexArray(v->id);
for (i = 0; i < num_elements; i++) {
struct vrend_vertex_element *ve = &v->elements[i];
if (util_format_is_pure_integer(ve->base.src_format))
glVertexAttribIFormat(i, ve->nr_chan, ve->type, ve->base.src_offset);
else
glVertexAttribFormat(i, ve->nr_chan, ve->type, ve->norm, ve->base.src_offset);
glVertexAttribBinding(i, ve->base.vertex_buffer_index);
glVertexBindingDivisor(i, ve->base.instance_divisor);
glEnableVertexAttribArray(i);
}
}
ret_handle = vrend_renderer_object_insert(ctx, v, sizeof(struct vrend_vertex_element), handle,
VIRGL_OBJECT_VERTEX_ELEMENTS);
if (!ret_handle) {
FREE(v);
return ENOMEM;
}
return 0;
}
| 164,944 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: InputMethodDescriptors* ChromeOSGetSupportedInputMethodDescriptors() {
InputMethodDescriptors* input_methods = new InputMethodDescriptors;
for (size_t i = 0; i < arraysize(chromeos::kIBusEngines); ++i) {
if (InputMethodIdIsWhitelisted(chromeos::kIBusEngines[i].name)) {
input_methods->push_back(chromeos::CreateInputMethodDescriptor(
chromeos::kIBusEngines[i].name,
chromeos::kIBusEngines[i].longname,
chromeos::kIBusEngines[i].layout,
chromeos::kIBusEngines[i].language));
}
}
return input_methods;
}
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 | InputMethodDescriptors* ChromeOSGetSupportedInputMethodDescriptors() {
virtual void RemoveObserver(Observer* observer) {
}
| 170,523 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
zval_dtor(data);
FREE_ZVAL(data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
Commit Message:
CWE ID: | static inline int process_nested_data(UNSERIALIZE_PARAMETER, HashTable *ht, long elements, int objprops)
{
while (elements-- > 0) {
zval *key, *data, **old_data;
ALLOC_INIT_ZVAL(key);
if (!php_var_unserialize(&key, p, max, NULL TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
if (Z_TYPE_P(key) != IS_LONG && Z_TYPE_P(key) != IS_STRING) {
zval_dtor(key);
FREE_ZVAL(key);
return 0;
}
ALLOC_INIT_ZVAL(data);
if (!php_var_unserialize(&data, p, max, var_hash TSRMLS_CC)) {
zval_dtor(key);
FREE_ZVAL(key);
zval_dtor(data);
FREE_ZVAL(data);
return 0;
}
if (!objprops) {
switch (Z_TYPE_P(key)) {
case IS_LONG:
if (zend_hash_index_find(ht, Z_LVAL_P(key), (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_index_update(ht, Z_LVAL_P(key), &data, sizeof(data), NULL);
break;
case IS_STRING:
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_symtable_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data, sizeof(data), NULL);
break;
}
} else {
/* object properties should include no integers */
convert_to_string(key);
if (zend_symtable_find(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, (void **)&old_data)==SUCCESS) {
var_push_dtor(var_hash, old_data);
}
zend_hash_update(ht, Z_STRVAL_P(key), Z_STRLEN_P(key) + 1, &data,
sizeof data, NULL);
}
if (elements && *(*p-1) != ';' && *(*p-1) != '}') {
(*p)--;
return 0;
}
}
| 164,893 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int uio_mmap_physical(struct vm_area_struct *vma)
{
struct uio_device *idev = vma->vm_private_data;
int mi = uio_find_mem_index(vma);
if (mi < 0)
return -EINVAL;
vma->vm_ops = &uio_physical_vm_ops;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
return remap_pfn_range(vma,
vma->vm_start,
idev->info->mem[mi].addr >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
Commit Message: Fix a few incorrectly checked [io_]remap_pfn_range() calls
Nico Golde reports a few straggling uses of [io_]remap_pfn_range() that
really should use the vm_iomap_memory() helper. This trivially converts
two of them to the helper, and comments about why the third one really
needs to continue to use remap_pfn_range(), and adds the missing size
check.
Reported-by: Nico Golde <[email protected]>
Cc: [email protected]
Signed-off-by: Linus Torvalds <[email protected].
CWE ID: CWE-119 | static int uio_mmap_physical(struct vm_area_struct *vma)
{
struct uio_device *idev = vma->vm_private_data;
int mi = uio_find_mem_index(vma);
struct uio_mem *mem;
if (mi < 0)
return -EINVAL;
mem = idev->info->mem + mi;
if (vma->vm_end - vma->vm_start > mem->size)
return -EINVAL;
vma->vm_ops = &uio_physical_vm_ops;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
/*
* We cannot use the vm_iomap_memory() helper here,
* because vma->vm_pgoff is the map index we looked
* up above in uio_find_mem_index(), rather than an
* actual page offset into the mmap.
*
* So we just do the physical mmap without a page
* offset.
*/
return remap_pfn_range(vma,
vma->vm_start,
mem->addr >> PAGE_SHIFT,
vma->vm_end - vma->vm_start,
vma->vm_page_prot);
}
| 165,934 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_akcipher rakcipher;
strlcpy(rakcipher.type, "akcipher", sizeof(rakcipher.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER,
sizeof(struct crypto_report_akcipher), &rakcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
Commit Message: crypto: user - fix leaking uninitialized memory to userspace
All bytes of the NETLINK_CRYPTO report structures must be initialized,
since they are copied to userspace. The change from strncpy() to
strlcpy() broke this. As a minimal fix, change it back.
Fixes: 4473710df1f8 ("crypto: user - Prepare for CRYPTO_MAX_ALG_NAME expansion")
Cc: <[email protected]> # v4.12+
Signed-off-by: Eric Biggers <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>
CWE ID: | static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg)
{
struct crypto_report_akcipher rakcipher;
strncpy(rakcipher.type, "akcipher", sizeof(rakcipher.type));
if (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER,
sizeof(struct crypto_report_akcipher), &rakcipher))
goto nla_put_failure;
return 0;
nla_put_failure:
return -EMSGSIZE;
}
| 168,964 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SecurityContext::SecurityContext()
: m_mayDisplaySeamlesslyWithParent(false)
, m_haveInitializedSecurityOrigin(false)
, m_sandboxFlags(SandboxNone)
{
}
Commit Message: Refactoring: Move m_mayDisplaySeamlesslyWithParent down to Document
The member is used only in Document, thus no reason to
stay in SecurityContext.
TEST=none
BUG=none
[email protected], abarth, haraken, hayato
Review URL: https://codereview.chromium.org/27615003
git-svn-id: svn://svn.chromium.org/blink/trunk@159829 bbb929c8-8fbe-4397-9dbb-9b2b20218538
CWE ID: CWE-20 | SecurityContext::SecurityContext()
: m_haveInitializedSecurityOrigin(false)
, m_sandboxFlags(SandboxNone)
{
}
| 170,700 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void opj_get_all_encoding_parameters( const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res,
OPJ_UINT32 ** p_resolutions )
{
/* loop*/
OPJ_UINT32 compno, resno;
/* pointers*/
const opj_tcp_t *tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* to store l_dx, l_dy, w and h for each resolution and component.*/
OPJ_UINT32 * lResolutionPtr;
/* position in x and y of tile*/
OPJ_UINT32 p, q;
/* preconditions in debug*/
assert(p_cp != 00);
assert(p_image != 00);
assert(tileno < p_cp->tw * p_cp->th);
/* initializations*/
tcp = &p_cp->tcps [tileno];
l_tccp = tcp->tccps;
l_img_comp = p_image->comps;
/* position in x and y of tile*/
p = tileno % p_cp->tw;
q = tileno / p_cp->tw;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */
*p_tx0 = opj_int_max((OPJ_INT32)(p_cp->tx0 + p * p_cp->tdx), (OPJ_INT32)p_image->x0);
*p_tx1 = opj_int_min((OPJ_INT32)(p_cp->tx0 + (p + 1) * p_cp->tdx), (OPJ_INT32)p_image->x1);
*p_ty0 = opj_int_max((OPJ_INT32)(p_cp->ty0 + q * p_cp->tdy), (OPJ_INT32)p_image->y0);
*p_ty1 = opj_int_min((OPJ_INT32)(p_cp->ty0 + (q + 1) * p_cp->tdy), (OPJ_INT32)p_image->y1);
/* max precision and resolution is 0 (can only grow)*/
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min*/
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* aritmetic variables to calculate*/
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph;
lResolutionPtr = p_resolutions[compno];
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts*/
l_level_no = l_tccp->numresolutions - 1;
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height*/
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
*lResolutionPtr++ = l_pdx;
*lResolutionPtr++ = l_pdy;
l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no));
/* take the minimum size for l_dx for each comp and resolution*/
*p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx);
*p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy);
/* various calculations of extents*/
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy);
*lResolutionPtr++ = l_pw;
*lResolutionPtr++ = l_ph;
l_product = l_pw * l_ph;
/* update precision*/
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
--l_level_no;
}
++l_tccp;
++l_img_comp;
}
}
Commit Message: [trunk] fixed a buffer overflow in opj_tcd_init_decode_tile
Update issue 431
CWE ID: CWE-190 | void opj_get_all_encoding_parameters( const opj_image_t *p_image,
const opj_cp_t *p_cp,
OPJ_UINT32 tileno,
OPJ_INT32 * p_tx0,
OPJ_INT32 * p_tx1,
OPJ_INT32 * p_ty0,
OPJ_INT32 * p_ty1,
OPJ_UINT32 * p_dx_min,
OPJ_UINT32 * p_dy_min,
OPJ_UINT32 * p_max_prec,
OPJ_UINT32 * p_max_res,
OPJ_UINT32 ** p_resolutions )
{
/* loop*/
OPJ_UINT32 compno, resno;
/* pointers*/
const opj_tcp_t *tcp = 00;
const opj_tccp_t * l_tccp = 00;
const opj_image_comp_t * l_img_comp = 00;
/* to store l_dx, l_dy, w and h for each resolution and component.*/
OPJ_UINT32 * lResolutionPtr;
/* position in x and y of tile*/
OPJ_UINT32 p, q;
/* preconditions in debug*/
assert(p_cp != 00);
assert(p_image != 00);
assert(tileno < p_cp->tw * p_cp->th);
/* initializations*/
tcp = &p_cp->tcps [tileno];
l_tccp = tcp->tccps;
l_img_comp = p_image->comps;
/* position in x and y of tile*/
p = tileno % p_cp->tw;
q = tileno / p_cp->tw;
/* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */
*p_tx0 = (OPJ_INT32)opj_uint_max(p_cp->tx0 + p * p_cp->tdx, p_image->x0);
*p_tx1 = (OPJ_INT32)opj_uint_min(p_cp->tx0 + (p + 1) * p_cp->tdx, p_image->x1);
*p_ty0 = (OPJ_INT32)opj_uint_max(p_cp->ty0 + q * p_cp->tdy, p_image->y0);
*p_ty1 = (OPJ_INT32)opj_uint_min(p_cp->ty0 + (q + 1) * p_cp->tdy, p_image->y1);
/* max precision and resolution is 0 (can only grow)*/
*p_max_prec = 0;
*p_max_res = 0;
/* take the largest value for dx_min and dy_min*/
*p_dx_min = 0x7fffffff;
*p_dy_min = 0x7fffffff;
for (compno = 0; compno < p_image->numcomps; ++compno) {
/* aritmetic variables to calculate*/
OPJ_UINT32 l_level_no;
OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
OPJ_INT32 l_px0, l_py0, l_px1, py1;
OPJ_UINT32 l_product;
OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
OPJ_UINT32 l_pdx, l_pdy , l_pw , l_ph;
lResolutionPtr = p_resolutions[compno];
l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);
if (l_tccp->numresolutions > *p_max_res) {
*p_max_res = l_tccp->numresolutions;
}
/* use custom size for precincts*/
l_level_no = l_tccp->numresolutions - 1;
for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
OPJ_UINT32 l_dx, l_dy;
/* precinct width and height*/
l_pdx = l_tccp->prcw[resno];
l_pdy = l_tccp->prch[resno];
*lResolutionPtr++ = l_pdx;
*lResolutionPtr++ = l_pdy;
l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no));
l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no));
/* take the minimum size for l_dx for each comp and resolution*/
*p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dx_min, (OPJ_INT32)l_dx);
*p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32)*p_dy_min, (OPJ_INT32)l_dy);
/* various calculations of extents*/
l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
l_pw = (l_rx0==l_rx1)?0:(OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
l_ph = (l_ry0==l_ry1)?0:(OPJ_UINT32)((py1 - l_py0) >> l_pdy);
*lResolutionPtr++ = l_pw;
*lResolutionPtr++ = l_ph;
l_product = l_pw * l_ph;
/* update precision*/
if (l_product > *p_max_prec) {
*p_max_prec = l_product;
}
--l_level_no;
}
++l_tccp;
++l_img_comp;
}
}
| 170,246 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: pdf_t *pdf_new(const char *name)
{
const char *n;
pdf_t *pdf;
pdf = calloc(1, sizeof(pdf_t));
if (name)
{
/* Just get the file name (not path) */
if ((n = strrchr(name, '/')))
++n;
else
n = name;
pdf->name = malloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
pdf->name = malloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
return pdf;
}
Commit Message: Zero and sanity check all dynamic allocs.
This addresses the memory issues in Issue #6 expressed in
calloc_some.pdf and malloc_some.pdf
CWE ID: CWE-787 | pdf_t *pdf_new(const char *name)
{
const char *n;
pdf_t *pdf;
pdf = safe_calloc(sizeof(pdf_t));
if (name)
{
/* Just get the file name (not path) */
if ((n = strrchr(name, '/')))
++n;
else
n = name;
pdf->name = safe_calloc(strlen(n) + 1);
strcpy(pdf->name, n);
}
else /* !name */
{
pdf->name = safe_calloc(strlen("Unknown") + 1);
strcpy(pdf->name, "Unknown");
}
return pdf;
}
| 169,573 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ContentEncoding::ContentEncryption::ContentEncryption()
: algo(0),
key_id(NULL),
key_id_len(0),
signature(NULL),
signature_len(0),
sig_key_id(NULL),
sig_key_id_len(0),
sig_algo(0),
sig_hash_algo(0) {
}
Commit Message: libwebm: Pull from upstream
Rolling mkvparser from upstream. Primarily for fixing a bug on parsing
failures with certain Opus WebM files.
Upstream commit hash of this pull: 574045edd4ecbeb802ee3f1d214b5510269852ae
The diff is so huge because there were some style clean ups upstream.
But it was ensured that there were no breaking changes when the style
clean ups was done upstream.
Change-Id: Ib6e907175484b4b0ae1b55ab39522ea3188ad039
CWE ID: CWE-119 | ContentEncoding::ContentEncryption::ContentEncryption()
: algo(0),
key_id(NULL),
key_id_len(0),
signature(NULL),
signature_len(0),
sig_key_id(NULL),
sig_key_id_len(0),
sig_algo(0),
| 174,252 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: OMX_ERRORTYPE SoftMP3::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioMp3:
{
OMX_AUDIO_PARAM_MP3TYPE *mp3Params =
(OMX_AUDIO_PARAM_MP3TYPE *)params;
if (mp3Params->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
mp3Params->nChannels = mNumChannels;
mp3Params->nBitRate = 0 /* unknown */;
mp3Params->nSampleRate = mSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
Commit Message: DO NOT MERGE Verify OMX buffer sizes prior to access
Bug: 27207275
Change-Id: I4412825d1ee233d993af0a67708bea54304ff62d
CWE ID: CWE-119 | OMX_ERRORTYPE SoftMP3::internalGetParameter(
OMX_INDEXTYPE index, OMX_PTR params) {
switch (index) {
case OMX_IndexParamAudioPcm:
{
OMX_AUDIO_PARAM_PCMMODETYPE *pcmParams =
(OMX_AUDIO_PARAM_PCMMODETYPE *)params;
if (!isValidOMXParam(pcmParams)) {
return OMX_ErrorBadParameter;
}
if (pcmParams->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
pcmParams->eNumData = OMX_NumericalDataSigned;
pcmParams->eEndian = OMX_EndianBig;
pcmParams->bInterleaved = OMX_TRUE;
pcmParams->nBitPerSample = 16;
pcmParams->ePCMMode = OMX_AUDIO_PCMModeLinear;
pcmParams->eChannelMapping[0] = OMX_AUDIO_ChannelLF;
pcmParams->eChannelMapping[1] = OMX_AUDIO_ChannelRF;
pcmParams->nChannels = mNumChannels;
pcmParams->nSamplingRate = mSamplingRate;
return OMX_ErrorNone;
}
case OMX_IndexParamAudioMp3:
{
OMX_AUDIO_PARAM_MP3TYPE *mp3Params =
(OMX_AUDIO_PARAM_MP3TYPE *)params;
if (!isValidOMXParam(mp3Params)) {
return OMX_ErrorBadParameter;
}
if (mp3Params->nPortIndex > 1) {
return OMX_ErrorUndefined;
}
mp3Params->nChannels = mNumChannels;
mp3Params->nBitRate = 0 /* unknown */;
mp3Params->nSampleRate = mSamplingRate;
return OMX_ErrorNone;
}
default:
return SimpleSoftOMXComponent::internalGetParameter(index, params);
}
}
| 174,211 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas,
bool active,
SkColor stroke_color) const {
SkPath outer_path =
GetPath(TabStyle::PathType::kBorder, canvas->image_scale(), active);
gfx::ScopedCanvas scoped_canvas(canvas);
float scale = canvas->UndoDeviceScaleFactor();
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(stroke_color);
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(GetStrokeThickness(active) * scale);
canvas->DrawPath(outer_path, flags);
}
Commit Message: Paint tab groups with the group color.
* The background of TabGroupHeader now uses the group color.
* The backgrounds of tabs in the group are tinted with the group color.
This treatment, along with the colors chosen, are intended to be
a placeholder.
Bug: 905491
Change-Id: Ic808548f8eba23064606e7fb8c9bba281d0d117f
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/1610504
Commit-Queue: Bret Sepulveda <[email protected]>
Reviewed-by: Taylor Bergquist <[email protected]>
Cr-Commit-Position: refs/heads/master@{#660498}
CWE ID: CWE-20 | void GM2TabStyle::PaintBackgroundStroke(gfx::Canvas* canvas,
TabState active_state,
SkColor stroke_color) const {
SkPath outer_path =
GetPath(TabStyle::PathType::kBorder, canvas->image_scale(),
active_state == TAB_ACTIVE);
gfx::ScopedCanvas scoped_canvas(canvas);
float scale = canvas->UndoDeviceScaleFactor();
cc::PaintFlags flags;
flags.setAntiAlias(true);
flags.setColor(stroke_color);
flags.setStyle(cc::PaintFlags::kStroke_Style);
flags.setStrokeWidth(GetStrokeThickness(active_state == TAB_ACTIVE) * scale);
canvas->DrawPath(outer_path, flags);
}
| 172,522 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array(
v8::Isolate* isolate,
v8::Local<v8::Object> creation_context,
const base::ListValue* val) const {
v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize()));
for (size_t i = 0; i < val->GetSize(); ++i) {
const base::Value* child = NULL;
CHECK(val->Get(i, &child));
v8::Local<v8::Value> child_v8 =
ToV8ValueImpl(isolate, creation_context, child);
CHECK(!child_v8.IsEmpty());
v8::TryCatch try_catch(isolate);
result->Set(static_cast<uint32_t>(i), child_v8);
if (try_catch.HasCaught())
LOG(ERROR) << "Setter for index " << i << " threw an exception.";
}
return result;
}
Commit Message: V8ValueConverter::ToV8Value should not trigger setters
BUG=606390
Review URL: https://codereview.chromium.org/1918793003
Cr-Commit-Position: refs/heads/master@{#390045}
CWE ID: | v8::Local<v8::Value> V8ValueConverterImpl::ToV8Array(
v8::Isolate* isolate,
v8::Local<v8::Object> creation_context,
const base::ListValue* val) const {
v8::Local<v8::Array> result(v8::Array::New(isolate, val->GetSize()));
// TODO(robwu): Callers should pass in the context.
v8::Local<v8::Context> context = isolate->GetCurrentContext();
for (size_t i = 0; i < val->GetSize(); ++i) {
const base::Value* child = NULL;
CHECK(val->Get(i, &child));
v8::Local<v8::Value> child_v8 =
ToV8ValueImpl(isolate, creation_context, child);
CHECK(!child_v8.IsEmpty());
v8::Maybe<bool> maybe =
result->CreateDataProperty(context, static_cast<uint32_t>(i), child_v8);
if (!maybe.IsJust() || !maybe.FromJust())
LOG(ERROR) << "Failed to set value at index " << i;
}
return result;
}
| 173,283 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: status_t DRMSource::read(MediaBuffer **buffer, const ReadOptions *options) {
Mutex::Autolock autoLock(mDRMLock);
status_t err;
if ((err = mOriginalMediaSource->read(buffer, options)) != OK) {
return err;
}
size_t len = (*buffer)->range_length();
char *src = (char *)(*buffer)->data() + (*buffer)->range_offset();
DrmBuffer encryptedDrmBuffer(src, len);
DrmBuffer decryptedDrmBuffer;
decryptedDrmBuffer.length = len;
decryptedDrmBuffer.data = new char[len];
DrmBuffer *pDecryptedDrmBuffer = &decryptedDrmBuffer;
if ((err = mDrmManagerClient->decrypt(mDecryptHandle, mTrackId,
&encryptedDrmBuffer, &pDecryptedDrmBuffer)) != NO_ERROR) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return err;
}
CHECK(pDecryptedDrmBuffer == &decryptedDrmBuffer);
const char *mime;
CHECK(getFormat()->findCString(kKeyMIMEType, &mime));
if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) && !mWantsNALFragments) {
uint8_t *dstData = (uint8_t*)src;
size_t srcOffset = 0;
size_t dstOffset = 0;
len = decryptedDrmBuffer.length;
while (srcOffset < len) {
CHECK(srcOffset + mNALLengthSize <= len);
size_t nalLength = 0;
const uint8_t* data = (const uint8_t*)(&decryptedDrmBuffer.data[srcOffset]);
switch (mNALLengthSize) {
case 1:
nalLength = *data;
break;
case 2:
nalLength = U16_AT(data);
break;
case 3:
nalLength = ((size_t)data[0] << 16) | U16_AT(&data[1]);
break;
case 4:
nalLength = U32_AT(data);
break;
default:
CHECK(!"Should not be here.");
break;
}
srcOffset += mNALLengthSize;
size_t end = srcOffset + nalLength;
if (end > len || end < srcOffset) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
CHECK(dstOffset + 4 <= (*buffer)->size());
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &decryptedDrmBuffer.data[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, len);
(*buffer)->set_range((*buffer)->range_offset(), dstOffset);
} else {
memcpy(src, decryptedDrmBuffer.data, decryptedDrmBuffer.length);
(*buffer)->set_range((*buffer)->range_offset(), decryptedDrmBuffer.length);
}
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return OK;
}
Commit Message: Fix security vulnerability in libstagefright
bug: 28175045
Change-Id: Icee6c7eb5b761da4aa3e412fb71825508d74d38f
CWE ID: CWE-119 | status_t DRMSource::read(MediaBuffer **buffer, const ReadOptions *options) {
Mutex::Autolock autoLock(mDRMLock);
status_t err;
if ((err = mOriginalMediaSource->read(buffer, options)) != OK) {
return err;
}
size_t len = (*buffer)->range_length();
char *src = (char *)(*buffer)->data() + (*buffer)->range_offset();
DrmBuffer encryptedDrmBuffer(src, len);
DrmBuffer decryptedDrmBuffer;
decryptedDrmBuffer.length = len;
decryptedDrmBuffer.data = new char[len];
DrmBuffer *pDecryptedDrmBuffer = &decryptedDrmBuffer;
if ((err = mDrmManagerClient->decrypt(mDecryptHandle, mTrackId,
&encryptedDrmBuffer, &pDecryptedDrmBuffer)) != NO_ERROR) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return err;
}
CHECK(pDecryptedDrmBuffer == &decryptedDrmBuffer);
const char *mime;
CHECK(getFormat()->findCString(kKeyMIMEType, &mime));
if (!strcasecmp(mime, MEDIA_MIMETYPE_VIDEO_AVC) && !mWantsNALFragments) {
uint8_t *dstData = (uint8_t*)src;
size_t srcOffset = 0;
size_t dstOffset = 0;
len = decryptedDrmBuffer.length;
while (srcOffset < len) {
CHECK(srcOffset + mNALLengthSize <= len);
size_t nalLength = 0;
const uint8_t* data = (const uint8_t*)(&decryptedDrmBuffer.data[srcOffset]);
switch (mNALLengthSize) {
case 1:
nalLength = *data;
break;
case 2:
nalLength = U16_AT(data);
break;
case 3:
nalLength = ((size_t)data[0] << 16) | U16_AT(&data[1]);
break;
case 4:
nalLength = U32_AT(data);
break;
default:
CHECK(!"Should not be here.");
break;
}
srcOffset += mNALLengthSize;
size_t end = srcOffset + nalLength;
if (end > len || end < srcOffset) {
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return ERROR_MALFORMED;
}
if (nalLength == 0) {
continue;
}
if (dstOffset > SIZE_MAX - 4 ||
dstOffset + 4 > SIZE_MAX - nalLength ||
dstOffset + 4 + nalLength > (*buffer)->size()) {
(*buffer)->release();
(*buffer) = NULL;
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return ERROR_MALFORMED;
}
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 0;
dstData[dstOffset++] = 1;
memcpy(&dstData[dstOffset], &decryptedDrmBuffer.data[srcOffset], nalLength);
srcOffset += nalLength;
dstOffset += nalLength;
}
CHECK_EQ(srcOffset, len);
(*buffer)->set_range((*buffer)->range_offset(), dstOffset);
} else {
memcpy(src, decryptedDrmBuffer.data, decryptedDrmBuffer.length);
(*buffer)->set_range((*buffer)->range_offset(), decryptedDrmBuffer.length);
}
if (decryptedDrmBuffer.data) {
delete [] decryptedDrmBuffer.data;
decryptedDrmBuffer.data = NULL;
}
return OK;
}
| 173,768 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: bool FileUtilProxy::Read(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
int bytes_to_read,
ReadCallback* callback) {
if (bytes_to_read < 0)
return false;
return Start(FROM_HERE, message_loop_proxy,
new RelayRead(file, offset, bytes_to_read, callback));
}
Commit Message: Fix a small leak in FileUtilProxy
BUG=none
TEST=green mem bots
Review URL: http://codereview.chromium.org/7669046
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@97451 0039d316-1c4b-4281-b951-d872f2087c98
CWE ID: CWE-399 | bool FileUtilProxy::Read(
scoped_refptr<MessageLoopProxy> message_loop_proxy,
PlatformFile file,
int64 offset,
int bytes_to_read,
ReadCallback* callback) {
if (bytes_to_read < 0) {
delete callback;
return false;
}
return Start(FROM_HERE, message_loop_proxy,
new RelayRead(file, offset, bytes_to_read, callback));
}
| 170,273 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb,
struct ip_options *opt)
{
struct tcp_options_received tcp_opt;
u8 *hash_location;
struct inet_request_sock *ireq;
struct tcp_request_sock *treq;
struct tcp_sock *tp = tcp_sk(sk);
const struct tcphdr *th = tcp_hdr(skb);
__u32 cookie = ntohl(th->ack_seq) - 1;
struct sock *ret = sk;
struct request_sock *req;
int mss;
struct rtable *rt;
__u8 rcv_wscale;
bool ecn_ok;
if (!sysctl_tcp_syncookies || !th->ack || th->rst)
goto out;
if (tcp_synq_no_recent_overflow(sk) ||
(mss = cookie_check(skb, cookie)) == 0) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED);
goto out;
}
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV);
/* check for timestamp cookie support */
memset(&tcp_opt, 0, sizeof(tcp_opt));
tcp_parse_options(skb, &tcp_opt, &hash_location, 0);
if (!cookie_check_timestamp(&tcp_opt, &ecn_ok))
goto out;
ret = NULL;
req = inet_reqsk_alloc(&tcp_request_sock_ops); /* for safety */
if (!req)
goto out;
ireq = inet_rsk(req);
treq = tcp_rsk(req);
treq->rcv_isn = ntohl(th->seq) - 1;
treq->snt_isn = cookie;
req->mss = mss;
ireq->loc_port = th->dest;
ireq->rmt_port = th->source;
ireq->loc_addr = ip_hdr(skb)->daddr;
ireq->rmt_addr = ip_hdr(skb)->saddr;
ireq->ecn_ok = ecn_ok;
ireq->snd_wscale = tcp_opt.snd_wscale;
ireq->sack_ok = tcp_opt.sack_ok;
ireq->wscale_ok = tcp_opt.wscale_ok;
ireq->tstamp_ok = tcp_opt.saw_tstamp;
req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0;
/* We throwed the options of the initial SYN away, so we hope
* the ACK carries the same options again (see RFC1122 4.2.3.8)
*/
if (opt && opt->optlen) {
int opt_size = sizeof(struct ip_options) + opt->optlen;
ireq->opt = kmalloc(opt_size, GFP_ATOMIC);
if (ireq->opt != NULL && ip_options_echo(ireq->opt, skb)) {
kfree(ireq->opt);
ireq->opt = NULL;
}
}
if (security_inet_conn_request(sk, skb, req)) {
reqsk_free(req);
goto out;
}
req->expires = 0UL;
req->retrans = 0;
/*
* We need to lookup the route here to get at the correct
* window size. We should better make sure that the window size
* hasn't changed since we received the original syn, but I see
* no easy way to do this.
*/
{
struct flowi4 fl4;
flowi4_init_output(&fl4, 0, sk->sk_mark, RT_CONN_FLAGS(sk),
RT_SCOPE_UNIVERSE, IPPROTO_TCP,
inet_sk_flowi_flags(sk),
(opt && opt->srr) ? opt->faddr : ireq->rmt_addr,
ireq->loc_addr, th->source, th->dest);
security_req_classify_flow(req, flowi4_to_flowi(&fl4));
rt = ip_route_output_key(sock_net(sk), &fl4);
if (IS_ERR(rt)) {
reqsk_free(req);
goto out;
}
}
/* Try to redo what tcp_v4_send_synack did. */
req->window_clamp = tp->window_clamp ? :dst_metric(&rt->dst, RTAX_WINDOW);
tcp_select_initial_window(tcp_full_space(sk), req->mss,
&req->rcv_wnd, &req->window_clamp,
ireq->wscale_ok, &rcv_wscale,
dst_metric(&rt->dst, RTAX_INITRWND));
ireq->rcv_wscale = rcv_wscale;
ret = get_cookie_sock(sk, skb, req, &rt->dst);
out: return ret;
}
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 | struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb,
struct ip_options *opt)
{
struct tcp_options_received tcp_opt;
u8 *hash_location;
struct inet_request_sock *ireq;
struct tcp_request_sock *treq;
struct tcp_sock *tp = tcp_sk(sk);
const struct tcphdr *th = tcp_hdr(skb);
__u32 cookie = ntohl(th->ack_seq) - 1;
struct sock *ret = sk;
struct request_sock *req;
int mss;
struct rtable *rt;
__u8 rcv_wscale;
bool ecn_ok;
if (!sysctl_tcp_syncookies || !th->ack || th->rst)
goto out;
if (tcp_synq_no_recent_overflow(sk) ||
(mss = cookie_check(skb, cookie)) == 0) {
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED);
goto out;
}
NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV);
/* check for timestamp cookie support */
memset(&tcp_opt, 0, sizeof(tcp_opt));
tcp_parse_options(skb, &tcp_opt, &hash_location, 0);
if (!cookie_check_timestamp(&tcp_opt, &ecn_ok))
goto out;
ret = NULL;
req = inet_reqsk_alloc(&tcp_request_sock_ops); /* for safety */
if (!req)
goto out;
ireq = inet_rsk(req);
treq = tcp_rsk(req);
treq->rcv_isn = ntohl(th->seq) - 1;
treq->snt_isn = cookie;
req->mss = mss;
ireq->loc_port = th->dest;
ireq->rmt_port = th->source;
ireq->loc_addr = ip_hdr(skb)->daddr;
ireq->rmt_addr = ip_hdr(skb)->saddr;
ireq->ecn_ok = ecn_ok;
ireq->snd_wscale = tcp_opt.snd_wscale;
ireq->sack_ok = tcp_opt.sack_ok;
ireq->wscale_ok = tcp_opt.wscale_ok;
ireq->tstamp_ok = tcp_opt.saw_tstamp;
req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0;
/* We throwed the options of the initial SYN away, so we hope
* the ACK carries the same options again (see RFC1122 4.2.3.8)
*/
if (opt && opt->optlen) {
int opt_size = sizeof(struct ip_options_rcu) + opt->optlen;
ireq->opt = kmalloc(opt_size, GFP_ATOMIC);
if (ireq->opt != NULL && ip_options_echo(&ireq->opt->opt, skb)) {
kfree(ireq->opt);
ireq->opt = NULL;
}
}
if (security_inet_conn_request(sk, skb, req)) {
reqsk_free(req);
goto out;
}
req->expires = 0UL;
req->retrans = 0;
/*
* We need to lookup the route here to get at the correct
* window size. We should better make sure that the window size
* hasn't changed since we received the original syn, but I see
* no easy way to do this.
*/
{
struct flowi4 fl4;
flowi4_init_output(&fl4, 0, sk->sk_mark, RT_CONN_FLAGS(sk),
RT_SCOPE_UNIVERSE, IPPROTO_TCP,
inet_sk_flowi_flags(sk),
(opt && opt->srr) ? opt->faddr : ireq->rmt_addr,
ireq->loc_addr, th->source, th->dest);
security_req_classify_flow(req, flowi4_to_flowi(&fl4));
rt = ip_route_output_key(sock_net(sk), &fl4);
if (IS_ERR(rt)) {
reqsk_free(req);
goto out;
}
}
/* Try to redo what tcp_v4_send_synack did. */
req->window_clamp = tp->window_clamp ? :dst_metric(&rt->dst, RTAX_WINDOW);
tcp_select_initial_window(tcp_full_space(sk), req->mss,
&req->rcv_wnd, &req->window_clamp,
ireq->wscale_ok, &rcv_wscale,
dst_metric(&rt->dst, RTAX_INITRWND));
ireq->rcv_wscale = rcv_wscale;
ret = get_cookie_sock(sk, skb, req, &rt->dst);
out: return ret;
}
| 165,569 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize,
size_t gcInfoIndex) {
size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize;
#if defined(ADDRESS_SANITIZER)
largeObjectSize += allocationGranularity;
#endif
getThreadState()->shouldFlushHeapDoesNotContainCache();
PageMemory* pageMemory = PageMemory::allocate(
largeObjectSize, getThreadState()->heap().getRegionTree());
Address largeObjectAddress = pageMemory->writableStart();
Address headerAddress =
largeObjectAddress + LargeObjectPage::pageHeaderSize();
#if DCHECK_IS_ON()
for (size_t i = 0; i < largeObjectSize; ++i)
ASSERT(!largeObjectAddress[i]);
#endif
ASSERT(gcInfoIndex > 0);
HeapObjectHeader* header = new (NotNull, headerAddress)
HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex);
Address result = headerAddress + sizeof(*header);
ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask));
LargeObjectPage* largeObject = new (largeObjectAddress)
LargeObjectPage(pageMemory, this, allocationSize);
ASSERT(header->checkHeader());
ASAN_POISON_MEMORY_REGION(header, sizeof(*header));
ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(),
allocationGranularity);
largeObject->link(&m_firstPage);
getThreadState()->heap().heapStats().increaseAllocatedSpace(
largeObject->size());
getThreadState()->increaseAllocatedObjectSize(largeObject->size());
return result;
}
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 | Address LargeObjectArena::doAllocateLargeObjectPage(size_t allocationSize,
size_t gcInfoIndex) {
size_t largeObjectSize = LargeObjectPage::pageHeaderSize() + allocationSize;
#if defined(ADDRESS_SANITIZER)
largeObjectSize += allocationGranularity;
#endif
getThreadState()->shouldFlushHeapDoesNotContainCache();
PageMemory* pageMemory = PageMemory::allocate(
largeObjectSize, getThreadState()->heap().getRegionTree());
Address largeObjectAddress = pageMemory->writableStart();
Address headerAddress =
largeObjectAddress + LargeObjectPage::pageHeaderSize();
#if DCHECK_IS_ON()
for (size_t i = 0; i < largeObjectSize; ++i)
ASSERT(!largeObjectAddress[i]);
#endif
ASSERT(gcInfoIndex > 0);
HeapObjectHeader* header = new (NotNull, headerAddress)
HeapObjectHeader(largeObjectSizeInHeader, gcInfoIndex);
Address result = headerAddress + sizeof(*header);
ASSERT(!(reinterpret_cast<uintptr_t>(result) & allocationMask));
LargeObjectPage* largeObject = new (largeObjectAddress)
LargeObjectPage(pageMemory, this, allocationSize);
header->checkHeader();
ASAN_POISON_MEMORY_REGION(header, sizeof(*header));
ASAN_POISON_MEMORY_REGION(largeObject->getAddress() + largeObject->size(),
allocationGranularity);
largeObject->link(&m_firstPage);
getThreadState()->heap().heapStats().increaseAllocatedSpace(
largeObject->size());
getThreadState()->increaseAllocatedObjectSize(largeObject->size());
return result;
}
| 172,709 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
UINT16 data_size, UINT8 *p_data, UINT16 evt)
{
UINT8 app_idx, mcl_idx, mdl_idx;
btif_hl_mdl_cb_t *p_dcb;
tBTA_HL_STATUS status = BTA_HL_STATUS_FAIL;
int r;
BTIF_TRACE_DEBUG("%s app_id=%d mdl_handle=0x%x data_size=%d",
__FUNCTION__,app_id, mdl_handle, data_size);
if (btif_hl_find_mdl_idx_using_handle(mdl_handle, &app_idx, &mcl_idx, &mdl_idx))
{
p_dcb = BTIF_HL_GET_MDL_CB_PTR(app_idx, mcl_idx, mdl_idx);
if ((p_dcb->p_rx_pkt = (UINT8 *)btif_hl_get_buf(data_size)) != NULL)
{
memcpy(p_dcb->p_rx_pkt, p_data, data_size);
if (p_dcb->p_scb)
{
BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=0x%x mdl_idx=0x%x data_size=%d",
app_idx, mcl_idx, mdl_idx, data_size);
r = send(p_dcb->p_scb->socket_id[1], p_dcb->p_rx_pkt, data_size, 0);
if (r == data_size)
{
BTIF_TRACE_DEBUG("socket send success data_size=%d", data_size);
status = BTA_HL_STATUS_OK;
}
else
{
BTIF_TRACE_ERROR("socket send failed r=%d data_size=%d",r, data_size);
}
}
btif_hl_free_buf((void **) &p_dcb->p_rx_pkt);
}
}
bta_hl_ci_put_rx_data(mdl_handle, status, evt);
}
Commit Message: DO NOT MERGE Fix potential DoS caused by delivering signal to BT process
Bug: 28885210
Change-Id: I63866d894bfca47464d6e42e3fb0357c4f94d360
Conflicts:
btif/co/bta_hh_co.c
btif/src/btif_core.c
Merge conflict resolution of ag/1161415 (referencing ag/1164670)
- Directly into mnc-mr2-release
CWE ID: CWE-284 | void bta_hl_co_put_rx_data (UINT8 app_id, tBTA_HL_MDL_HANDLE mdl_handle,
UINT16 data_size, UINT8 *p_data, UINT16 evt)
{
UINT8 app_idx, mcl_idx, mdl_idx;
btif_hl_mdl_cb_t *p_dcb;
tBTA_HL_STATUS status = BTA_HL_STATUS_FAIL;
int r;
BTIF_TRACE_DEBUG("%s app_id=%d mdl_handle=0x%x data_size=%d",
__FUNCTION__,app_id, mdl_handle, data_size);
if (btif_hl_find_mdl_idx_using_handle(mdl_handle, &app_idx, &mcl_idx, &mdl_idx))
{
p_dcb = BTIF_HL_GET_MDL_CB_PTR(app_idx, mcl_idx, mdl_idx);
if ((p_dcb->p_rx_pkt = (UINT8 *)btif_hl_get_buf(data_size)) != NULL)
{
memcpy(p_dcb->p_rx_pkt, p_data, data_size);
if (p_dcb->p_scb)
{
BTIF_TRACE_DEBUG("app_idx=%d mcl_idx=0x%x mdl_idx=0x%x data_size=%d",
app_idx, mcl_idx, mdl_idx, data_size);
r = TEMP_FAILURE_RETRY(send(p_dcb->p_scb->socket_id[1], p_dcb->p_rx_pkt, data_size, 0));
if (r == data_size)
{
BTIF_TRACE_DEBUG("socket send success data_size=%d", data_size);
status = BTA_HL_STATUS_OK;
}
else
{
BTIF_TRACE_ERROR("socket send failed r=%d data_size=%d",r, data_size);
}
}
btif_hl_free_buf((void **) &p_dcb->p_rx_pkt);
}
}
bta_hl_ci_put_rx_data(mdl_handle, status, evt);
}
| 173,434 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: ChopUpSingleUncompressedStrip(TIFF* tif)
{
register TIFFDirectory *td = &tif->tif_dir;
uint64 bytecount;
uint64 offset;
uint32 rowblock;
uint64 rowblockbytes;
uint64 stripbytes;
uint32 strip;
uint64 nstrips64;
uint32 nstrips32;
uint32 rowsperstrip;
uint64* newcounts;
uint64* newoffsets;
bytecount = td->td_stripbytecount[0];
offset = td->td_stripoffset[0];
assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
if ((td->td_photometric == PHOTOMETRIC_YCBCR)&&
(!isUpSampled(tif)))
rowblock = td->td_ycbcrsubsampling[1];
else
rowblock = 1;
rowblockbytes = TIFFVTileSize64(tif, rowblock);
/*
* Make the rows hold at least one scanline, but fill specified amount
* of data if possible.
*/
if (rowblockbytes > STRIP_SIZE_DEFAULT) {
stripbytes = rowblockbytes;
rowsperstrip = rowblock;
} else if (rowblockbytes > 0 ) {
uint32 rowblocksperstrip;
rowblocksperstrip = (uint32) (STRIP_SIZE_DEFAULT / rowblockbytes);
rowsperstrip = rowblocksperstrip * rowblock;
stripbytes = rowblocksperstrip * rowblockbytes;
}
else
return;
/*
* never increase the number of strips in an image
*/
if (rowsperstrip >= td->td_rowsperstrip)
return;
nstrips64 = TIFFhowmany_64(bytecount, stripbytes);
if ((nstrips64==0)||(nstrips64>0xFFFFFFFF)) /* something is wonky, do nothing. */
return;
nstrips32 = (uint32)nstrips64;
newcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64),
"for chopped \"StripByteCounts\" array");
newoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips32, sizeof (uint64),
"for chopped \"StripOffsets\" array");
if (newcounts == NULL || newoffsets == NULL) {
/*
* Unable to allocate new strip information, give up and use
* the original one strip information.
*/
if (newcounts != NULL)
_TIFFfree(newcounts);
if (newoffsets != NULL)
_TIFFfree(newoffsets);
return;
}
/*
* Fill the strip information arrays with new bytecounts and offsets
* that reflect the broken-up format.
*/
for (strip = 0; strip < nstrips32; strip++) {
if (stripbytes > bytecount)
stripbytes = bytecount;
newcounts[strip] = stripbytes;
newoffsets[strip] = offset;
offset += stripbytes;
bytecount -= stripbytes;
}
/*
* Replace old single strip info with multi-strip info.
*/
td->td_stripsperimage = td->td_nstrips = nstrips32;
TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
_TIFFfree(td->td_stripbytecount);
_TIFFfree(td->td_stripoffset);
td->td_stripbytecount = newcounts;
td->td_stripoffset = newoffsets;
td->td_stripbytecountsorted = 1;
}
Commit Message: * libtiff/tif_dirread.c: modify ChopUpSingleUncompressedStrip() to
instanciate compute ntrips as TIFFhowmany_32(td->td_imagelength, rowsperstrip),
instead of a logic based on the total size of data. Which is faulty is
the total size of data is not sufficient to fill the whole image, and thus
results in reading outside of the StripByCounts/StripOffsets arrays when
using TIFFReadScanline().
Reported by Agostino Sarubbo.
Fixes http://bugzilla.maptools.org/show_bug.cgi?id=2608.
* libtiff/tif_strip.c: revert the change in TIFFNumberOfStrips() done
for http://bugzilla.maptools.org/show_bug.cgi?id=2587 / CVE-2016-9273 since
the above change is a better fix that makes it unnecessary.
CWE ID: CWE-125 | ChopUpSingleUncompressedStrip(TIFF* tif)
{
register TIFFDirectory *td = &tif->tif_dir;
uint64 bytecount;
uint64 offset;
uint32 rowblock;
uint64 rowblockbytes;
uint64 stripbytes;
uint32 strip;
uint32 nstrips;
uint32 rowsperstrip;
uint64* newcounts;
uint64* newoffsets;
bytecount = td->td_stripbytecount[0];
offset = td->td_stripoffset[0];
assert(td->td_planarconfig == PLANARCONFIG_CONTIG);
if ((td->td_photometric == PHOTOMETRIC_YCBCR)&&
(!isUpSampled(tif)))
rowblock = td->td_ycbcrsubsampling[1];
else
rowblock = 1;
rowblockbytes = TIFFVTileSize64(tif, rowblock);
/*
* Make the rows hold at least one scanline, but fill specified amount
* of data if possible.
*/
if (rowblockbytes > STRIP_SIZE_DEFAULT) {
stripbytes = rowblockbytes;
rowsperstrip = rowblock;
} else if (rowblockbytes > 0 ) {
uint32 rowblocksperstrip;
rowblocksperstrip = (uint32) (STRIP_SIZE_DEFAULT / rowblockbytes);
rowsperstrip = rowblocksperstrip * rowblock;
stripbytes = rowblocksperstrip * rowblockbytes;
}
else
return;
/*
* never increase the number of rows per strip
*/
if (rowsperstrip >= td->td_rowsperstrip)
return;
nstrips = TIFFhowmany_32(td->td_imagelength, rowsperstrip);
if( nstrips == 0 )
return;
newcounts = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),
"for chopped \"StripByteCounts\" array");
newoffsets = (uint64*) _TIFFCheckMalloc(tif, nstrips, sizeof (uint64),
"for chopped \"StripOffsets\" array");
if (newcounts == NULL || newoffsets == NULL) {
/*
* Unable to allocate new strip information, give up and use
* the original one strip information.
*/
if (newcounts != NULL)
_TIFFfree(newcounts);
if (newoffsets != NULL)
_TIFFfree(newoffsets);
return;
}
/*
* Fill the strip information arrays with new bytecounts and offsets
* that reflect the broken-up format.
*/
for (strip = 0; strip < nstrips; strip++) {
if (stripbytes > bytecount)
stripbytes = bytecount;
newcounts[strip] = stripbytes;
newoffsets[strip] = stripbytes ? offset : 0;
offset += stripbytes;
bytecount -= stripbytes;
}
/*
* Replace old single strip info with multi-strip info.
*/
td->td_stripsperimage = td->td_nstrips = nstrips;
TIFFSetField(tif, TIFFTAG_ROWSPERSTRIP, rowsperstrip);
_TIFFfree(td->td_stripbytecount);
_TIFFfree(td->td_stripoffset);
td->td_stripbytecount = newcounts;
td->td_stripoffset = newoffsets;
td->td_stripbytecountsorted = 1;
}
| 168,462 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: GF_Err sgpd_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length);
if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index);
fprintf(trace, ">\n");
for (i=0; i<gf_list_count(ptr->group_descriptions); i++) {
void *entry = gf_list_get(ptr->group_descriptions, i);
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no");
if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)
fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);
fprintf(trace, "/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type);
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {
fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
}
fprintf(trace, "\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
fprintf(trace, "\"/>\n");
}
}
if (!ptr->size) {
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n");
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n");
}
}
gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace);
return GF_OK;
}
Commit Message: fixed 2 possible heap overflows (inc. #1088)
CWE ID: CWE-125 | GF_Err sgpd_dump(GF_Box *a, FILE * trace)
{
u32 i;
GF_SampleGroupDescriptionBox *ptr = (GF_SampleGroupDescriptionBox*) a;
if (!a) return GF_BAD_PARAM;
gf_isom_box_dump_start(a, "SampleGroupDescriptionBox", trace);
if (ptr->grouping_type)
fprintf(trace, "grouping_type=\"%s\"", gf_4cc_to_str(ptr->grouping_type) );
if (ptr->version==1) fprintf(trace, " default_length=\"%d\"", ptr->default_length);
if ((ptr->version>=2) && ptr->default_description_index) fprintf(trace, " default_group_index=\"%d\"", ptr->default_description_index);
fprintf(trace, ">\n");
for (i=0; i<gf_list_count(ptr->group_descriptions); i++) {
void *entry = gf_list_get(ptr->group_descriptions, i);
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"%d\" />\n", ((GF_RollRecoveryEntry*)entry)->roll_distance );
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"%d\"/>\n", ((GF_TemporalLevelEntry*)entry)->level_independently_decodable);
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"%s\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known ? "yes" : "no");
if (((GF_VisualRandomAccessEntry*)entry)->num_leading_samples_known)
fprintf(trace, " num_leading_samples=\"%d\"", ((GF_VisualRandomAccessEntry*)entry)->num_leading_samples);
fprintf(trace, "/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"%d\"/>\n", ((GF_SYNCEntry*)entry)->NALU_type);
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"%d\" IV_size=\"%d\" KID=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected, ((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->KID, 16);
if ((((GF_CENCSampleEncryptionGroupEntry*)entry)->IsProtected == 1) && !((GF_CENCSampleEncryptionGroupEntry*)entry)->Per_Sample_IV_size) {
fprintf(trace, "\" constant_IV_size=\"%d\" constant_IV=\"", ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
dump_data_hex(trace, (char *)((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV, ((GF_CENCSampleEncryptionGroupEntry*)entry)->constant_IV_size);
}
fprintf(trace, "\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(entry, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"%d\" SAP_type=\"%d\" />\n", ((GF_SAPEntry*)entry)->dependent_flag, ((GF_SAPEntry*)entry)->SAP_type);
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"%d\" data=\"", ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
dump_data(trace, (char *) ((GF_DefaultSampleGroupDescriptionEntry*)entry)->data, ((GF_DefaultSampleGroupDescriptionEntry*)entry)->length);
fprintf(trace, "\"/>\n");
}
}
if (!ptr->size) {
switch (ptr->grouping_type) {
case GF_ISOM_SAMPLE_GROUP_ROLL:
fprintf(trace, "<RollRecoveryEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_PROL:
fprintf(trace, "<AudioPreRollEntry roll_distance=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_TELE:
fprintf(trace, "<TemporalLevelEntry level_independently_decodable=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_RAP:
fprintf(trace, "<VisualRandomAccessEntry num_leading_samples_known=\"yes|no\" num_leading_samples=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SYNC:
fprintf(trace, "<SyncSampleGroupEntry NAL_unit_type=\"\" />\n");
break;
case GF_ISOM_SAMPLE_GROUP_SEIG:
fprintf(trace, "<CENCSampleEncryptionGroupEntry IsEncrypted=\"\" IV_size=\"\" KID=\"\" constant_IV_size=\"\" constant_IV=\"\"/>\n");
break;
case GF_ISOM_SAMPLE_GROUP_OINF:
oinf_entry_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_LINF:
linf_dump(NULL, trace);
break;
case GF_ISOM_SAMPLE_GROUP_TRIF:
trif_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_NALM:
nalm_dump(trace, NULL, 0);
break;
case GF_ISOM_SAMPLE_GROUP_SAP:
fprintf(trace, "<SAPEntry dependent_flag=\"\" SAP_type=\"\" />\n");
break;
default:
fprintf(trace, "<DefaultSampleGroupDescriptionEntry size=\"\" data=\"\"/>\n");
}
}
gf_isom_box_dump_done("SampleGroupDescriptionBox", a, trace);
return GF_OK;
}
| 169,171 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk);
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk))) ||
(write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
Commit Message: issue #27, do not overwrite stack on corrupt RF64 file
CWE ID: CWE-119 | int WriteRiffHeader (FILE *outfile, WavpackContext *wpc, int64_t total_samples, int qmode)
{
int do_rf64 = 0, write_junk = 1, table_length = 0;
ChunkHeader ds64hdr, datahdr, fmthdr;
RiffChunkHeader riffhdr;
DS64Chunk ds64_chunk;
CS64Chunk cs64_chunk;
JunkChunk junkchunk;
WaveHeader wavhdr;
uint32_t bcount;
int64_t total_data_bytes, total_riff_bytes;
int num_channels = WavpackGetNumChannels (wpc);
int32_t channel_mask = WavpackGetChannelMask (wpc);
int32_t sample_rate = WavpackGetSampleRate (wpc);
int bytes_per_sample = WavpackGetBytesPerSample (wpc);
int bits_per_sample = WavpackGetBitsPerSample (wpc);
int format = WavpackGetFloatNormExp (wpc) ? 3 : 1;
int wavhdrsize = 16;
if (format == 3 && WavpackGetFloatNormExp (wpc) != 127) {
error_line ("can't create valid RIFF wav header for non-normalized floating data!");
return FALSE;
}
if (total_samples == -1)
total_samples = 0x7ffff000 / (bytes_per_sample * num_channels);
total_data_bytes = total_samples * bytes_per_sample * num_channels;
if (total_data_bytes > 0xff000000) {
if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so rf64", total_data_bytes);
write_junk = 0;
do_rf64 = 1;
}
else if (debug_logging_mode)
error_line ("total_data_bytes = %lld, so riff", total_data_bytes);
CLEAR (wavhdr);
wavhdr.FormatTag = format;
wavhdr.NumChannels = num_channels;
wavhdr.SampleRate = sample_rate;
wavhdr.BytesPerSecond = sample_rate * num_channels * bytes_per_sample;
wavhdr.BlockAlign = bytes_per_sample * num_channels;
wavhdr.BitsPerSample = bits_per_sample;
if (num_channels > 2 || channel_mask != 0x5 - num_channels) {
wavhdrsize = sizeof (wavhdr);
wavhdr.cbSize = 22;
wavhdr.ValidBitsPerSample = bits_per_sample;
wavhdr.SubFormat = format;
wavhdr.ChannelMask = channel_mask;
wavhdr.FormatTag = 0xfffe;
wavhdr.BitsPerSample = bytes_per_sample * 8;
wavhdr.GUID [4] = 0x10;
wavhdr.GUID [6] = 0x80;
wavhdr.GUID [9] = 0xaa;
wavhdr.GUID [11] = 0x38;
wavhdr.GUID [12] = 0x9b;
wavhdr.GUID [13] = 0x71;
}
strncpy (riffhdr.ckID, do_rf64 ? "RF64" : "RIFF", sizeof (riffhdr.ckID));
strncpy (riffhdr.formType, "WAVE", sizeof (riffhdr.formType));
total_riff_bytes = sizeof (riffhdr) + wavhdrsize + sizeof (datahdr) + ((total_data_bytes + 1) & ~(int64_t)1);
if (do_rf64) total_riff_bytes += sizeof (ds64hdr) + sizeof (ds64_chunk);
total_riff_bytes += table_length * sizeof (CS64Chunk);
if (write_junk) total_riff_bytes += sizeof (junkchunk);
strncpy (fmthdr.ckID, "fmt ", sizeof (fmthdr.ckID));
strncpy (datahdr.ckID, "data", sizeof (datahdr.ckID));
fmthdr.ckSize = wavhdrsize;
if (write_junk) {
CLEAR (junkchunk);
strncpy (junkchunk.ckID, "junk", sizeof (junkchunk.ckID));
junkchunk.ckSize = sizeof (junkchunk) - 8;
WavpackNativeToLittleEndian (&junkchunk, ChunkHeaderFormat);
}
if (do_rf64) {
strncpy (ds64hdr.ckID, "ds64", sizeof (ds64hdr.ckID));
ds64hdr.ckSize = sizeof (ds64_chunk) + (table_length * sizeof (CS64Chunk));
CLEAR (ds64_chunk);
ds64_chunk.riffSize64 = total_riff_bytes;
ds64_chunk.dataSize64 = total_data_bytes;
ds64_chunk.sampleCount64 = total_samples;
ds64_chunk.tableLength = table_length;
riffhdr.ckSize = (uint32_t) -1;
datahdr.ckSize = (uint32_t) -1;
WavpackNativeToLittleEndian (&ds64hdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&ds64_chunk, DS64ChunkFormat);
}
else {
riffhdr.ckSize = (uint32_t) total_riff_bytes;
datahdr.ckSize = (uint32_t) total_data_bytes;
}
// this "table" is just a dummy placeholder for testing (normally not written)
if (table_length) {
strncpy (cs64_chunk.ckID, "dmmy", sizeof (cs64_chunk.ckID));
cs64_chunk.chunkSize64 = 12345678;
WavpackNativeToLittleEndian (&cs64_chunk, CS64ChunkFormat);
}
WavpackNativeToLittleEndian (&riffhdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&fmthdr, ChunkHeaderFormat);
WavpackNativeToLittleEndian (&wavhdr, WaveHeaderFormat);
WavpackNativeToLittleEndian (&datahdr, ChunkHeaderFormat);
if (!DoWriteFile (outfile, &riffhdr, sizeof (riffhdr), &bcount) || bcount != sizeof (riffhdr) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64hdr, sizeof (ds64hdr), &bcount) || bcount != sizeof (ds64hdr))) ||
(do_rf64 && (!DoWriteFile (outfile, &ds64_chunk, sizeof (ds64_chunk), &bcount) || bcount != sizeof (ds64_chunk)))) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
// again, this is normally not written except for testing
while (table_length--)
if (!DoWriteFile (outfile, &cs64_chunk, sizeof (cs64_chunk), &bcount) || bcount != sizeof (cs64_chunk)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
if ((write_junk && (!DoWriteFile (outfile, &junkchunk, sizeof (junkchunk), &bcount) || bcount != sizeof (junkchunk))) ||
!DoWriteFile (outfile, &fmthdr, sizeof (fmthdr), &bcount) || bcount != sizeof (fmthdr) ||
!DoWriteFile (outfile, &wavhdr, wavhdrsize, &bcount) || bcount != wavhdrsize ||
!DoWriteFile (outfile, &datahdr, sizeof (datahdr), &bcount) || bcount != sizeof (datahdr)) {
error_line ("can't write .WAV data, disk probably full!");
return FALSE;
}
return TRUE;
}
| 169,335 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: SampleTable::SampleTable(const sp<DataSource> &source)
: mDataSource(source),
mChunkOffsetOffset(-1),
mChunkOffsetType(0),
mNumChunkOffsets(0),
mSampleToChunkOffset(-1),
mNumSampleToChunkOffsets(0),
mSampleSizeOffset(-1),
mSampleSizeFieldSize(0),
mDefaultSampleSize(0),
mNumSampleSizes(0),
mTimeToSampleCount(0),
mTimeToSample(NULL),
mSampleTimeEntries(NULL),
mCompositionTimeDeltaEntries(NULL),
mNumCompositionTimeDeltaEntries(0),
mCompositionDeltaLookup(new CompositionDeltaLookup),
mSyncSampleOffset(-1),
mNumSyncSamples(0),
mSyncSamples(NULL),
mLastSyncSampleIndex(0),
mSampleToChunkEntries(NULL) {
mSampleIterator = new SampleIterator(this);
}
Commit Message: Resolve merge conflict when cp'ing ag/931301 to mnc-mr1-release
Change-Id: I079d1db2d30d126f8aed348bd62451acf741037d
CWE ID: CWE-20 | SampleTable::SampleTable(const sp<DataSource> &source)
: mDataSource(source),
mChunkOffsetOffset(-1),
mChunkOffsetType(0),
mNumChunkOffsets(0),
mSampleToChunkOffset(-1),
mNumSampleToChunkOffsets(0),
mSampleSizeOffset(-1),
mSampleSizeFieldSize(0),
mDefaultSampleSize(0),
mNumSampleSizes(0),
mTimeToSampleCount(0),
mTimeToSample(),
mSampleTimeEntries(NULL),
mCompositionTimeDeltaEntries(NULL),
mNumCompositionTimeDeltaEntries(0),
mCompositionDeltaLookup(new CompositionDeltaLookup),
mSyncSampleOffset(-1),
mNumSyncSamples(0),
mSyncSamples(NULL),
mLastSyncSampleIndex(0),
mSampleToChunkEntries(NULL) {
mSampleIterator = new SampleIterator(this);
}
| 174,171 |
Analyze the following vulnerable code snippet, the commit message, and the CWE ID. Determine the impact category of this vulnerability. Respond with the corrected function only. Remember, I want response with just the fixed code only, No explanation. | Code: static long media_device_enum_entities(struct media_device *mdev,
struct media_entity_desc __user *uent)
{
struct media_entity *ent;
struct media_entity_desc u_ent;
if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id)))
return -EFAULT;
ent = find_entity(mdev, u_ent.id);
if (ent == NULL)
return -EINVAL;
u_ent.id = ent->id;
if (ent->name) {
strncpy(u_ent.name, ent->name, sizeof(u_ent.name));
u_ent.name[sizeof(u_ent.name) - 1] = '\0';
} else {
memset(u_ent.name, 0, sizeof(u_ent.name));
}
u_ent.type = ent->type;
u_ent.revision = ent->revision;
u_ent.flags = ent->flags;
u_ent.group_id = ent->group_id;
u_ent.pads = ent->num_pads;
u_ent.links = ent->num_links - ent->num_backlinks;
memcpy(&u_ent.raw, &ent->info, sizeof(ent->info));
if (copy_to_user(uent, &u_ent, sizeof(u_ent)))
return -EFAULT;
return 0;
}
Commit Message: [media] media-device: fix infoleak in ioctl media_enum_entities()
This fixes CVE-2014-1739.
Signed-off-by: Salva Peiró <[email protected]>
Acked-by: Laurent Pinchart <[email protected]>
Cc: [email protected]
Signed-off-by: Mauro Carvalho Chehab <[email protected]>
CWE ID: CWE-200 | static long media_device_enum_entities(struct media_device *mdev,
struct media_entity_desc __user *uent)
{
struct media_entity *ent;
struct media_entity_desc u_ent;
memset(&u_ent, 0, sizeof(u_ent));
if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id)))
return -EFAULT;
ent = find_entity(mdev, u_ent.id);
if (ent == NULL)
return -EINVAL;
u_ent.id = ent->id;
if (ent->name) {
strncpy(u_ent.name, ent->name, sizeof(u_ent.name));
u_ent.name[sizeof(u_ent.name) - 1] = '\0';
} else {
memset(u_ent.name, 0, sizeof(u_ent.name));
}
u_ent.type = ent->type;
u_ent.revision = ent->revision;
u_ent.flags = ent->flags;
u_ent.group_id = ent->group_id;
u_ent.pads = ent->num_pads;
u_ent.links = ent->num_links - ent->num_backlinks;
memcpy(&u_ent.raw, &ent->info, sizeof(ent->info));
if (copy_to_user(uent, &u_ent, sizeof(u_ent)))
return -EFAULT;
return 0;
}
| 166,433 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.