func_name
stringlengths 2
53
| func_src_before
stringlengths 63
114k
| func_src_after
stringlengths 86
114k
| line_changes
dict | char_changes
dict | commit_link
stringlengths 66
117
| file_name
stringlengths 5
72
| vul_type
stringclasses 9
values |
---|---|---|---|---|---|---|---|
multiSelect | static int multiSelect(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int rc = SQLITE_OK; /* Success code from a subroutine */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest dest; /* Alternative data destination */
Select *pDelete = 0; /* Chain of simple selects to delete */
sqlite3 *db; /* Database connection */
/* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
*/
assert( p && p->pPrior ); /* Calling function guarantees this much */
assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
assert( p->selFlags & SF_Compound );
db = pParse->db;
pPrior = p->pPrior;
dest = *pDest;
if( pPrior->pOrderBy || pPrior->pLimit ){
sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
rc = 1;
goto multi_select_end;
}
v = sqlite3GetVdbe(pParse);
assert( v!=0 ); /* The VDBE already created by calling function */
/* Create the destination temporary table if necessary
*/
if( dest.eDest==SRT_EphemTab ){
assert( p->pEList );
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
dest.eDest = SRT_Table;
}
/* Special handling for a compound-select that originates as a VALUES clause.
*/
if( p->selFlags & SF_MultiValue ){
rc = multiSelectValues(pParse, p, &dest);
if( rc>=0 ) goto multi_select_end;
rc = SQLITE_OK;
}
/* Make sure all SELECTs in the statement have the same number of elements
** in their result sets.
*/
assert( p->pEList && pPrior->pEList );
assert( p->pEList->nExpr==pPrior->pEList->nExpr );
#ifndef SQLITE_OMIT_CTE
if( p->selFlags & SF_Recursive ){
generateWithRecursiveQuery(pParse, p, &dest);
}else
#endif
/* Compound SELECTs that have an ORDER BY clause are handled separately.
*/
if( p->pOrderBy ){
return multiSelectOrderBy(pParse, p, pDest);
}else{
#ifndef SQLITE_OMIT_EXPLAIN
if( pPrior->pPrior==0 ){
ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
}
#endif
/* Generate code for the left and right SELECT statements.
*/
switch( p->op ){
case TK_ALL: {
int addr = 0;
int nLimit;
assert( !pPrior->pLimit );
pPrior->iLimit = p->iLimit;
pPrior->iOffset = p->iOffset;
pPrior->pLimit = p->pLimit;
rc = sqlite3Select(pParse, pPrior, &dest);
p->pLimit = 0;
if( rc ){
goto multi_select_end;
}
p->pPrior = 0;
p->iLimit = pPrior->iLimit;
p->iOffset = pPrior->iOffset;
if( p->iLimit ){
addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
VdbeComment((v, "Jump ahead if LIMIT reached"));
if( p->iOffset ){
sqlite3VdbeAddOp3(v, OP_OffsetLimit,
p->iLimit, p->iOffset+1, p->iOffset);
}
}
ExplainQueryPlan((pParse, 1, "UNION ALL"));
rc = sqlite3Select(pParse, p, &dest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
if( pPrior->pLimit
&& sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
&& nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
){
p->nSelectRow = sqlite3LogEst((u64)nLimit);
}
if( addr ){
sqlite3VdbeJumpHere(v, addr);
}
break;
}
case TK_EXCEPT:
case TK_UNION: {
int unionTab; /* Cursor number of the temp table holding result */
u8 op = 0; /* One of the SRT_ operations to apply to self */
int priorOp; /* The SRT_ operation to apply to prior selects */
Expr *pLimit; /* Saved values of p->nLimit */
int addr;
SelectDest uniondest;
testcase( p->op==TK_EXCEPT );
testcase( p->op==TK_UNION );
priorOp = SRT_Union;
if( dest.eDest==priorOp ){
/* We can reuse a temporary table generated by a SELECT to our
** right.
*/
assert( p->pLimit==0 ); /* Not allowed on leftward elements */
unionTab = dest.iSDParm;
}else{
/* We will need to create our own temporary table to hold the
** intermediate results.
*/
unionTab = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
}
/* Code the SELECT statements to our left
*/
assert( !pPrior->pOrderBy );
sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
rc = sqlite3Select(pParse, pPrior, &uniondest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT statement
*/
if( p->op==TK_EXCEPT ){
op = SRT_Except;
}else{
assert( p->op==TK_UNION );
op = SRT_Union;
}
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
uniondest.eDest = op;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &uniondest);
testcase( rc!=SQLITE_OK );
/* Query flattening in sqlite3Select() might refill p->pOrderBy.
** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
sqlite3ExprListDelete(db, p->pOrderBy);
pDelete = p->pPrior;
p->pPrior = pPrior;
p->pOrderBy = 0;
if( p->op==TK_UNION ){
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
p->iLimit = 0;
p->iOffset = 0;
/* Convert the data in the temporary table into whatever form
** it is that we currently need.
*/
assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
if( dest.eDest!=priorOp ){
int iCont, iBreak, iStart;
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
iStart = sqlite3VdbeCurrentAddr(v);
selectInnerLoop(pParse, p, unionTab,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
}
break;
}
default: assert( p->op==TK_INTERSECT ); {
int tab1, tab2;
int iCont, iBreak, iStart;
Expr *pLimit;
int addr;
SelectDest intersectdest;
int r1;
/* INTERSECT is different from the others since it requires
** two temporary tables. Hence it has its own case. Begin
** by allocating the tables we will need.
*/
tab1 = pParse->nTab++;
tab2 = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
/* Code the SELECTs to our left into temporary table "tab1".
*/
sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
rc = sqlite3Select(pParse, pPrior, &intersectdest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT into temporary table "tab2"
*/
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
assert( p->addrOpenEphm[1] == -1 );
p->addrOpenEphm[1] = addr;
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
intersectdest.iSDParm = tab2;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &intersectdest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
if( p->nSelectRow>pPrior->nSelectRow ){
p->nSelectRow = pPrior->nSelectRow;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
/* Generate code to take the intersection of the two temporary
** tables.
*/
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
r1 = sqlite3GetTempReg(pParse);
iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r1);
selectInnerLoop(pParse, p, tab1,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
break;
}
}
#ifndef SQLITE_OMIT_EXPLAIN
if( p->pNext==0 ){
ExplainQueryPlanPop(pParse);
}
#endif
}
/* Compute collating sequences used by
** temporary tables needed to implement the compound select.
** Attach the KeyInfo structure to all temporary tables.
**
** This section is run by the right-most SELECT statement only.
** SELECT statements to the left always skip this part. The right-most
** SELECT might also skip this part if it has no ORDER BY clause and
** no temp tables are required.
*/
if( p->selFlags & SF_UsesEphemeral ){
int i; /* Loop counter */
KeyInfo *pKeyInfo; /* Collating sequence for the result set */
Select *pLoop; /* For looping through SELECT statements */
CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
int nCol; /* Number of columns in result set */
assert( p->pNext==0 );
nCol = p->pEList->nExpr;
pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
if( !pKeyInfo ){
rc = SQLITE_NOMEM_BKPT;
goto multi_select_end;
}
for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
*apColl = multiSelectCollSeq(pParse, p, i);
if( 0==*apColl ){
*apColl = db->pDfltColl;
}
}
for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
for(i=0; i<2; i++){
int addr = pLoop->addrOpenEphm[i];
if( addr<0 ){
/* If [0] is unused then [1] is also unused. So we can
** always safely abort as soon as the first unused slot is found */
assert( pLoop->addrOpenEphm[1]<0 );
break;
}
sqlite3VdbeChangeP2(v, addr, nCol);
sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
P4_KEYINFO);
pLoop->addrOpenEphm[i] = -1;
}
}
sqlite3KeyInfoUnref(pKeyInfo);
}
multi_select_end:
pDest->iSdst = dest.iSdst;
pDest->nSdst = dest.nSdst;
sqlite3SelectDelete(db, pDelete);
return rc;
} | static int multiSelect(
Parse *pParse, /* Parsing context */
Select *p, /* The right-most of SELECTs to be coded */
SelectDest *pDest /* What to do with query results */
){
int rc = SQLITE_OK; /* Success code from a subroutine */
Select *pPrior; /* Another SELECT immediately to our left */
Vdbe *v; /* Generate code to this VDBE */
SelectDest dest; /* Alternative data destination */
Select *pDelete = 0; /* Chain of simple selects to delete */
sqlite3 *db; /* Database connection */
/* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
*/
assert( p && p->pPrior ); /* Calling function guarantees this much */
assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
assert( p->selFlags & SF_Compound );
db = pParse->db;
pPrior = p->pPrior;
dest = *pDest;
if( pPrior->pOrderBy || pPrior->pLimit ){
sqlite3ErrorMsg(pParse,"%s clause should come after %s not before",
pPrior->pOrderBy!=0 ? "ORDER BY" : "LIMIT", selectOpName(p->op));
rc = 1;
goto multi_select_end;
}
v = sqlite3GetVdbe(pParse);
assert( v!=0 ); /* The VDBE already created by calling function */
/* Create the destination temporary table if necessary
*/
if( dest.eDest==SRT_EphemTab ){
assert( p->pEList );
sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
dest.eDest = SRT_Table;
}
/* Special handling for a compound-select that originates as a VALUES clause.
*/
if( p->selFlags & SF_MultiValue ){
rc = multiSelectValues(pParse, p, &dest);
if( rc>=0 ) goto multi_select_end;
rc = SQLITE_OK;
}
/* Make sure all SELECTs in the statement have the same number of elements
** in their result sets.
*/
assert( p->pEList && pPrior->pEList );
assert( p->pEList->nExpr==pPrior->pEList->nExpr );
#ifndef SQLITE_OMIT_CTE
if( p->selFlags & SF_Recursive ){
generateWithRecursiveQuery(pParse, p, &dest);
}else
#endif
/* Compound SELECTs that have an ORDER BY clause are handled separately.
*/
if( p->pOrderBy ){
return multiSelectOrderBy(pParse, p, pDest);
}else{
#ifndef SQLITE_OMIT_EXPLAIN
if( pPrior->pPrior==0 ){
ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
}
#endif
/* Generate code for the left and right SELECT statements.
*/
switch( p->op ){
case TK_ALL: {
int addr = 0;
int nLimit;
assert( !pPrior->pLimit );
pPrior->iLimit = p->iLimit;
pPrior->iOffset = p->iOffset;
pPrior->pLimit = p->pLimit;
rc = sqlite3Select(pParse, pPrior, &dest);
p->pLimit = 0;
if( rc ){
goto multi_select_end;
}
p->pPrior = 0;
p->iLimit = pPrior->iLimit;
p->iOffset = pPrior->iOffset;
if( p->iLimit ){
addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
VdbeComment((v, "Jump ahead if LIMIT reached"));
if( p->iOffset ){
sqlite3VdbeAddOp3(v, OP_OffsetLimit,
p->iLimit, p->iOffset+1, p->iOffset);
}
}
ExplainQueryPlan((pParse, 1, "UNION ALL"));
rc = sqlite3Select(pParse, p, &dest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
if( pPrior->pLimit
&& sqlite3ExprIsInteger(pPrior->pLimit->pLeft, &nLimit)
&& nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
){
p->nSelectRow = sqlite3LogEst((u64)nLimit);
}
if( addr ){
sqlite3VdbeJumpHere(v, addr);
}
break;
}
case TK_EXCEPT:
case TK_UNION: {
int unionTab; /* Cursor number of the temp table holding result */
u8 op = 0; /* One of the SRT_ operations to apply to self */
int priorOp; /* The SRT_ operation to apply to prior selects */
Expr *pLimit; /* Saved values of p->nLimit */
int addr;
SelectDest uniondest;
testcase( p->op==TK_EXCEPT );
testcase( p->op==TK_UNION );
priorOp = SRT_Union;
if( dest.eDest==priorOp ){
/* We can reuse a temporary table generated by a SELECT to our
** right.
*/
assert( p->pLimit==0 ); /* Not allowed on leftward elements */
unionTab = dest.iSDParm;
}else{
/* We will need to create our own temporary table to hold the
** intermediate results.
*/
unionTab = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
}
/* Code the SELECT statements to our left
*/
assert( !pPrior->pOrderBy );
sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
rc = sqlite3Select(pParse, pPrior, &uniondest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT statement
*/
if( p->op==TK_EXCEPT ){
op = SRT_Except;
}else{
assert( p->op==TK_UNION );
op = SRT_Union;
}
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
uniondest.eDest = op;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &uniondest);
testcase( rc!=SQLITE_OK );
/* Query flattening in sqlite3Select() might refill p->pOrderBy.
** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
sqlite3ExprListDelete(db, p->pOrderBy);
pDelete = p->pPrior;
p->pPrior = pPrior;
p->pOrderBy = 0;
if( p->op==TK_UNION ){
p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
p->iLimit = 0;
p->iOffset = 0;
/* Convert the data in the temporary table into whatever form
** it is that we currently need.
*/
assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
if( dest.eDest!=priorOp ){
int iCont, iBreak, iStart;
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
iStart = sqlite3VdbeCurrentAddr(v);
selectInnerLoop(pParse, p, unionTab,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
}
break;
}
default: assert( p->op==TK_INTERSECT ); {
int tab1, tab2;
int iCont, iBreak, iStart;
Expr *pLimit;
int addr;
SelectDest intersectdest;
int r1;
/* INTERSECT is different from the others since it requires
** two temporary tables. Hence it has its own case. Begin
** by allocating the tables we will need.
*/
tab1 = pParse->nTab++;
tab2 = pParse->nTab++;
assert( p->pOrderBy==0 );
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
assert( p->addrOpenEphm[0] == -1 );
p->addrOpenEphm[0] = addr;
findRightmost(p)->selFlags |= SF_UsesEphemeral;
assert( p->pEList );
/* Code the SELECTs to our left into temporary table "tab1".
*/
sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
rc = sqlite3Select(pParse, pPrior, &intersectdest);
if( rc ){
goto multi_select_end;
}
/* Code the current SELECT into temporary table "tab2"
*/
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
assert( p->addrOpenEphm[1] == -1 );
p->addrOpenEphm[1] = addr;
p->pPrior = 0;
pLimit = p->pLimit;
p->pLimit = 0;
intersectdest.iSDParm = tab2;
ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
selectOpName(p->op)));
rc = sqlite3Select(pParse, p, &intersectdest);
testcase( rc!=SQLITE_OK );
pDelete = p->pPrior;
p->pPrior = pPrior;
if( p->nSelectRow>pPrior->nSelectRow ){
p->nSelectRow = pPrior->nSelectRow;
}
sqlite3ExprDelete(db, p->pLimit);
p->pLimit = pLimit;
/* Generate code to take the intersection of the two temporary
** tables.
*/
assert( p->pEList );
iBreak = sqlite3VdbeMakeLabel(pParse);
iCont = sqlite3VdbeMakeLabel(pParse);
computeLimitRegisters(pParse, p, iBreak);
sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
r1 = sqlite3GetTempReg(pParse);
iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
VdbeCoverage(v);
sqlite3ReleaseTempReg(pParse, r1);
selectInnerLoop(pParse, p, tab1,
0, 0, &dest, iCont, iBreak);
sqlite3VdbeResolveLabel(v, iCont);
sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
sqlite3VdbeResolveLabel(v, iBreak);
sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
break;
}
}
#ifndef SQLITE_OMIT_EXPLAIN
if( p->pNext==0 ){
ExplainQueryPlanPop(pParse);
}
#endif
}
if( pParse->nErr ) goto multi_select_end;
/* Compute collating sequences used by
** temporary tables needed to implement the compound select.
** Attach the KeyInfo structure to all temporary tables.
**
** This section is run by the right-most SELECT statement only.
** SELECT statements to the left always skip this part. The right-most
** SELECT might also skip this part if it has no ORDER BY clause and
** no temp tables are required.
*/
if( p->selFlags & SF_UsesEphemeral ){
int i; /* Loop counter */
KeyInfo *pKeyInfo; /* Collating sequence for the result set */
Select *pLoop; /* For looping through SELECT statements */
CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
int nCol; /* Number of columns in result set */
assert( p->pNext==0 );
nCol = p->pEList->nExpr;
pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
if( !pKeyInfo ){
rc = SQLITE_NOMEM_BKPT;
goto multi_select_end;
}
for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
*apColl = multiSelectCollSeq(pParse, p, i);
if( 0==*apColl ){
*apColl = db->pDfltColl;
}
}
for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
for(i=0; i<2; i++){
int addr = pLoop->addrOpenEphm[i];
if( addr<0 ){
/* If [0] is unused then [1] is also unused. So we can
** always safely abort as soon as the first unused slot is found */
assert( pLoop->addrOpenEphm[1]<0 );
break;
}
sqlite3VdbeChangeP2(v, addr, nCol);
sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
P4_KEYINFO);
pLoop->addrOpenEphm[i] = -1;
}
}
sqlite3KeyInfoUnref(pKeyInfo);
}
multi_select_end:
pDest->iSdst = dest.iSdst;
pDest->nSdst = dest.nSdst;
sqlite3SelectDelete(db, pDelete);
return rc;
} | {
"deleted": [],
"added": [
{
"line_no": 288,
"char_start": 10153,
"char_end": 10197,
"line": " if( pParse->nErr ) goto multi_select_end;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 10155,
"char_end": 10199,
"chars": "if( pParse->nErr ) goto multi_select_end;\n "
}
]
} | github.com/sqlite/sqlite/commit/8428b3b437569338a9d1e10c4cd8154acbe33089 | src/select.c | cwe-476 |
r_pkcs7_parse_cms | 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;
} | 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;
} | {
"deleted": [
{
"line_no": 12,
"char_start": 258,
"char_end": 375,
"line": "\tif (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {\n"
}
],
"added": [
{
"line_no": 12,
"char_start": 258,
"char_end": 327,
"line": "\tif (!object || object->list.length != 2 || !object->list.objects ||\n"
},
{
"line_no": 13,
"char_start": 327,
"char_end": 385,
"line": "\t\t!object->list.objects[0] || !object->list.objects[1] ||\n"
},
{
"line_no": 14,
"char_start": 385,
"char_end": 432,
"line": "\t\tobject->list.objects[1]->list.length != 1) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 323,
"char_end": 350,
"chars": " ||\n\t\t!object->list.objects"
},
{
"char_start": 357,
"char_end": 387,
"chars": "!object->list.objects[1] ||\n\t\t"
}
]
} | github.com/radare/radare2/commit/7ab66cca5bbdf6cb2d69339ef4f513d95e532dbf | libr/util/r_pkcs7.c | cwe-476 |
ReadDCMImage | static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
explicit_vr[MagickPathExtent],
implicit_vr[MagickPathExtent],
magick[MagickPathExtent],
photometric[MagickPathExtent];
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
index,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
polarity,
sequence,
use_explicit;
MagickOffsetType
offset;
Quantum
*scale;
register ssize_t
i,
x;
register Quantum
*q;
register unsigned char
*p;
size_t
bits_allocated,
bytes_per_pixel,
colors,
depth,
height,
length,
mask,
max_value,
number_scenes,
quantum,
samples_per_pixel,
signed_data,
significant_bits,
status,
width,
window_width;
ssize_t
count,
rescale_intercept,
rescale_slope,
scene,
window_center,
y;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent);
bits_allocated=8;
bytes_per_pixel=1;
polarity=MagickFalse;
data=(unsigned char *) NULL;
depth=8;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
max_value=255UL;
mask=0xffff;
number_scenes=1;
rescale_intercept=0;
rescale_slope=1;
samples_per_pixel=1;
scale=(Quantum *) NULL;
sequence=MagickFalse;
signed_data=(~0UL);
significant_bits=0;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
window_center=0;
window_width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"UL",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"FL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MagickPathExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MagickPathExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
count,
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
if (count < 1)
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
bits_allocated=(size_t) datum;
bytes_per_pixel=1;
if (datum > 8)
bytes_per_pixel=2;
depth=bits_allocated;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << bits_allocated)-1;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
significant_bits=(size_t) datum;
bytes_per_pixel=1;
if (significant_bits > 8)
bytes_per_pixel=2;
depth=significant_bits;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << significant_bits)-1;
mask=(size_t) GetQuantumRange(significant_bits);
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
window_center=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
window_width=StringToUnsignedLong((char *) data);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
rescale_intercept=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
rescale_slope=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data,exception);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (signed_data == 0xffff)
signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MagickPathExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"jpeg:%s",filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"j2k:%s",filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property,exception),exception);
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(depth)+1);
scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
if (scale == (Quantum *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(depth);
for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)
scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1))
{
size_t
one;
one=1;
if (colors == 0)
colors=one << depth;
if (AcquireImageColormap(image,one << depth,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].green=(MagickRealType) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].blue=(MagickRealType) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
image->colormap[i].green=(MagickRealType) index;
image->colormap[i].blue=(MagickRealType) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
if (stream_info->segment_count > 1)
{
bytes_per_pixel=1;
depth=8;
}
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
}
if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 3:
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
int
byte;
PixelPacket
pixel;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
if ((window_center != 0) && (window_width == 0))
window_width=(size_t) window_center;
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
window_width=0;
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
if (signed_data)
pixel_value=ReadDCMSignedShort(stream_info,image);
else
pixel_value=ReadDCMShort(stream_info,image);
if (polarity != MagickFalse)
pixel_value=(int)max_value-pixel_value;
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMSignedShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) index,q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) pixel.red,q);
SetPixelGreen(image,(Quantum) pixel.green,q);
SetPixelBlue(image,(Quantum) pixel.blue,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (stream_info->segment_count > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
pixel_value=(int) (polarity != MagickFalse ?
(max_value-ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
if (signed_data == 1)
pixel_value=((signed short) pixel_value);
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) (((size_t)
GetPixelIndex(image,q)) | (((size_t) index) << 8)),q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) |
(((size_t) pixel.red) << 8)),q);
SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) |
(((size_t) pixel.green) << 8)),q);
SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) |
(((size_t) pixel.blue) << 8)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (scale != (Quantum *) NULL)
scale=(Quantum *) RelinquishMagickMemory(scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | static Image *ReadDCMImage(const ImageInfo *image_info,ExceptionInfo *exception)
{
char
explicit_vr[MagickPathExtent],
implicit_vr[MagickPathExtent],
magick[MagickPathExtent],
photometric[MagickPathExtent];
DCMStreamInfo
*stream_info;
Image
*image;
int
*bluemap,
datum,
*greenmap,
*graymap,
index,
*redmap;
MagickBooleanType
explicit_file,
explicit_retry,
polarity,
sequence,
use_explicit;
MagickOffsetType
offset;
Quantum
*scale;
register ssize_t
i,
x;
register Quantum
*q;
register unsigned char
*p;
size_t
bits_allocated,
bytes_per_pixel,
colors,
depth,
height,
length,
mask,
max_value,
number_scenes,
quantum,
samples_per_pixel,
signed_data,
significant_bits,
status,
width,
window_width;
ssize_t
count,
rescale_intercept,
rescale_slope,
scene,
window_center,
y;
unsigned char
*data;
unsigned short
group,
element;
/*
Open image file.
*/
assert(image_info != (const ImageInfo *) NULL);
assert(image_info->signature == MagickCoreSignature);
if (image_info->debug != MagickFalse)
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
image_info->filename);
assert(exception != (ExceptionInfo *) NULL);
assert(exception->signature == MagickCoreSignature);
image=AcquireImage(image_info,exception);
status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
if (status == MagickFalse)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image->depth=8UL;
image->endian=LSBEndian;
/*
Read DCM preamble.
*/
stream_info=(DCMStreamInfo *) AcquireMagickMemory(sizeof(*stream_info));
if (stream_info == (DCMStreamInfo *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
(void) ResetMagickMemory(stream_info,0,sizeof(*stream_info));
count=ReadBlob(image,128,(unsigned char *) magick);
if (count != 128)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
count=ReadBlob(image,4,(unsigned char *) magick);
if ((count != 4) || (LocaleNCompare(magick,"DICM",4) != 0))
{
offset=SeekBlob(image,0L,SEEK_SET);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
}
/*
Read DCM Medical image.
*/
(void) CopyMagickString(photometric,"MONOCHROME1 ",MagickPathExtent);
bits_allocated=8;
bytes_per_pixel=1;
polarity=MagickFalse;
data=(unsigned char *) NULL;
depth=8;
element=0;
explicit_vr[2]='\0';
explicit_file=MagickFalse;
colors=0;
redmap=(int *) NULL;
greenmap=(int *) NULL;
bluemap=(int *) NULL;
graymap=(int *) NULL;
height=0;
max_value=255UL;
mask=0xffff;
number_scenes=1;
rescale_intercept=0;
rescale_slope=1;
samples_per_pixel=1;
scale=(Quantum *) NULL;
sequence=MagickFalse;
signed_data=(~0UL);
significant_bits=0;
use_explicit=MagickFalse;
explicit_retry = MagickFalse;
width=0;
window_center=0;
window_width=0;
for (group=0; (group != 0x7FE0) || (element != 0x0010) ||
(sequence != MagickFalse); )
{
/*
Read a group.
*/
image->offset=(ssize_t) TellBlob(image);
group=ReadBlobLSBShort(image);
element=ReadBlobLSBShort(image);
if ((group != 0x0002) && (image->endian == MSBEndian))
{
group=(unsigned short) ((group << 8) | ((group >> 8) & 0xFF));
element=(unsigned short) ((element << 8) | ((element >> 8) & 0xFF));
}
quantum=0;
/*
Find corresponding VR for this group and element.
*/
for (i=0; dicom_info[i].group < 0xffff; i++)
if ((group == dicom_info[i].group) && (element == dicom_info[i].element))
break;
(void) CopyMagickString(implicit_vr,dicom_info[i].vr,MagickPathExtent);
count=ReadBlob(image,2,(unsigned char *) explicit_vr);
if (count != 2)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
/*
Check for "explicitness", but meta-file headers always explicit.
*/
if ((explicit_file == MagickFalse) && (group != 0x0002))
explicit_file=(isupper((unsigned char) *explicit_vr) != MagickFalse) &&
(isupper((unsigned char) *(explicit_vr+1)) != MagickFalse) ?
MagickTrue : MagickFalse;
use_explicit=((group == 0x0002) && (explicit_retry == MagickFalse)) ||
(explicit_file != MagickFalse) ? MagickTrue : MagickFalse;
if ((use_explicit != MagickFalse) && (strncmp(implicit_vr,"xs",2) == 0))
(void) CopyMagickString(implicit_vr,explicit_vr,MagickPathExtent);
if ((use_explicit == MagickFalse) || (strncmp(implicit_vr,"!!",2) == 0))
{
offset=SeekBlob(image,(MagickOffsetType) -2,SEEK_CUR);
if (offset < 0)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
quantum=4;
}
else
{
/*
Assume explicit type.
*/
quantum=2;
if ((strncmp(explicit_vr,"OB",2) == 0) ||
(strncmp(explicit_vr,"UN",2) == 0) ||
(strncmp(explicit_vr,"OW",2) == 0) ||
(strncmp(explicit_vr,"SQ",2) == 0))
{
(void) ReadBlobLSBShort(image);
quantum=4;
}
}
datum=0;
if (quantum == 4)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if (quantum == 2)
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
quantum=0;
length=1;
if (datum != 0)
{
if ((strncmp(implicit_vr,"SS",2) == 0) ||
(strncmp(implicit_vr,"US",2) == 0))
quantum=2;
else
if ((strncmp(implicit_vr,"UL",2) == 0) ||
(strncmp(implicit_vr,"SL",2) == 0) ||
(strncmp(implicit_vr,"FL",2) == 0))
quantum=4;
else
if (strncmp(implicit_vr,"FD",2) != 0)
quantum=1;
else
quantum=8;
if (datum != ~0)
length=(size_t) datum/quantum;
else
{
/*
Sequence and item of undefined length.
*/
quantum=0;
length=0;
}
}
if (image_info->verbose != MagickFalse)
{
/*
Display Dicom info.
*/
if (use_explicit == MagickFalse)
explicit_vr[0]='\0';
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
(void) FormatLocaleFile(stdout,"0x%04lX %4ld %s-%s (0x%04lx,0x%04lx)",
(unsigned long) image->offset,(long) length,implicit_vr,explicit_vr,
(unsigned long) group,(unsigned long) element);
if (dicom_info[i].description != (char *) NULL)
(void) FormatLocaleFile(stdout," %s",dicom_info[i].description);
(void) FormatLocaleFile(stdout,": ");
}
if ((sequence == MagickFalse) && (group == 0x7FE0) && (element == 0x0010))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"\n");
break;
}
/*
Allocate space and read an array.
*/
data=(unsigned char *) NULL;
if ((length == 1) && (quantum == 1))
datum=ReadBlobByte(image);
else
if ((length == 1) && (quantum == 2))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedShort(image);
else
datum=ReadBlobSignedShort(image);
}
else
if ((length == 1) && (quantum == 4))
{
if (group == 0x0002)
datum=ReadBlobLSBSignedLong(image);
else
datum=ReadBlobSignedLong(image);
}
else
if ((quantum != 0) && (length != 0))
{
if (~length >= 1)
data=(unsigned char *) AcquireQuantumMemory(length+1,quantum*
sizeof(*data));
if (data == (unsigned char *) NULL)
ThrowReaderException(ResourceLimitError,
"MemoryAllocationFailed");
count=ReadBlob(image,(size_t) quantum*length,data);
if (count != (ssize_t) (quantum*length))
{
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"count=%d quantum=%d "
"length=%d group=%d\n",(int) count,(int) quantum,(int)
length,(int) group);
ThrowReaderException(CorruptImageError,
"InsufficientImageDataInFile");
}
data[length*quantum]='\0';
}
else
if ((unsigned int) datum == 0xFFFFFFFFU)
{
sequence=MagickTrue;
continue;
}
if ((unsigned int) ((group << 16) | element) == 0xFFFEE0DD)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
sequence=MagickFalse;
continue;
}
if (sequence != MagickFalse)
{
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
continue;
}
switch (group)
{
case 0x0002:
{
switch (element)
{
case 0x0010:
{
char
transfer_syntax[MagickPathExtent];
/*
Transfer Syntax.
*/
if ((datum == 0) && (explicit_retry == MagickFalse))
{
explicit_retry=MagickTrue;
(void) SeekBlob(image,(MagickOffsetType) 0,SEEK_SET);
group=0;
element=0;
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,
"Corrupted image - trying explicit format\n");
break;
}
*transfer_syntax='\0';
if (data != (unsigned char *) NULL)
(void) CopyMagickString(transfer_syntax,(char *) data,
MagickPathExtent);
if (image_info->verbose != MagickFalse)
(void) FormatLocaleFile(stdout,"transfer_syntax=%s\n",
(const char *) transfer_syntax);
if (strncmp(transfer_syntax,"1.2.840.10008.1.2",17) == 0)
{
int
count,
subtype,
type;
type=1;
subtype=0;
if (strlen(transfer_syntax) > 17)
{
count=sscanf(transfer_syntax+17,".%d.%d",&type,&subtype);
if (count < 1)
ThrowReaderException(CorruptImageError,
"ImproperImageHeader");
}
switch (type)
{
case 1:
{
image->endian=LSBEndian;
break;
}
case 2:
{
image->endian=MSBEndian;
break;
}
case 4:
{
if ((subtype >= 80) && (subtype <= 81))
image->compression=JPEGCompression;
else
if ((subtype >= 90) && (subtype <= 93))
image->compression=JPEG2000Compression;
else
image->compression=JPEGCompression;
break;
}
case 5:
{
image->compression=RLECompression;
break;
}
}
}
break;
}
default:
break;
}
break;
}
case 0x0028:
{
switch (element)
{
case 0x0002:
{
/*
Samples per pixel.
*/
samples_per_pixel=(size_t) datum;
break;
}
case 0x0004:
{
/*
Photometric interpretation.
*/
if (data == (unsigned char *) NULL)
break;
for (i=0; i < (ssize_t) MagickMin(length,MagickPathExtent-1); i++)
photometric[i]=(char) data[i];
photometric[i]='\0';
polarity=LocaleCompare(photometric,"MONOCHROME1 ") == 0 ?
MagickTrue : MagickFalse;
break;
}
case 0x0006:
{
/*
Planar configuration.
*/
if (datum == 1)
image->interlace=PlaneInterlace;
break;
}
case 0x0008:
{
/*
Number of frames.
*/
if (data == (unsigned char *) NULL)
break;
number_scenes=StringToUnsignedLong((char *) data);
break;
}
case 0x0010:
{
/*
Image rows.
*/
height=(size_t) datum;
break;
}
case 0x0011:
{
/*
Image columns.
*/
width=(size_t) datum;
break;
}
case 0x0100:
{
/*
Bits allocated.
*/
bits_allocated=(size_t) datum;
bytes_per_pixel=1;
if (datum > 8)
bytes_per_pixel=2;
depth=bits_allocated;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << bits_allocated)-1;
break;
}
case 0x0101:
{
/*
Bits stored.
*/
significant_bits=(size_t) datum;
bytes_per_pixel=1;
if (significant_bits > 8)
bytes_per_pixel=2;
depth=significant_bits;
if (depth > 32)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
max_value=(1UL << significant_bits)-1;
mask=(size_t) GetQuantumRange(significant_bits);
break;
}
case 0x0102:
{
/*
High bit.
*/
break;
}
case 0x0103:
{
/*
Pixel representation.
*/
signed_data=(size_t) datum;
break;
}
case 0x1050:
{
/*
Visible pixel range: center.
*/
if (data != (unsigned char *) NULL)
window_center=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1051:
{
/*
Visible pixel range: width.
*/
if (data != (unsigned char *) NULL)
window_width=StringToUnsignedLong((char *) data);
break;
}
case 0x1052:
{
/*
Rescale intercept
*/
if (data != (unsigned char *) NULL)
rescale_intercept=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1053:
{
/*
Rescale slope
*/
if (data != (unsigned char *) NULL)
rescale_slope=(ssize_t) StringToLong((char *) data);
break;
}
case 0x1200:
case 0x3006:
{
/*
Populate graymap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/bytes_per_pixel);
datum=(int) colors;
graymap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*graymap));
if (graymap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) colors; i++)
if (bytes_per_pixel == 1)
graymap[i]=(int) data[i];
else
graymap[i]=(int) ((short *) data)[i];
break;
}
case 0x1201:
{
unsigned short
index;
/*
Populate redmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
redmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*redmap));
if (redmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
redmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1202:
{
unsigned short
index;
/*
Populate greenmap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
greenmap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*greenmap));
if (greenmap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
greenmap[i]=(int) index;
p+=2;
}
break;
}
case 0x1203:
{
unsigned short
index;
/*
Populate bluemap.
*/
if (data == (unsigned char *) NULL)
break;
colors=(size_t) (length/2);
datum=(int) colors;
bluemap=(int *) AcquireQuantumMemory((size_t) colors,
sizeof(*bluemap));
if (bluemap == (int *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
p=data;
for (i=0; i < (ssize_t) colors; i++)
{
if (image->endian == MSBEndian)
index=(unsigned short) ((*p << 8) | *(p+1));
else
index=(unsigned short) (*p | (*(p+1) << 8));
bluemap[i]=(int) index;
p+=2;
}
break;
}
default:
break;
}
break;
}
case 0x2050:
{
switch (element)
{
case 0x0020:
{
if ((data != (unsigned char *) NULL) &&
(strncmp((char *) data,"INVERSE",7) == 0))
polarity=MagickTrue;
break;
}
default:
break;
}
break;
}
default:
break;
}
if (data != (unsigned char *) NULL)
{
char
*attribute;
for (i=0; dicom_info[i].description != (char *) NULL; i++)
if ((group == dicom_info[i].group) &&
(element == dicom_info[i].element))
break;
if (dicom_info[i].description != (char *) NULL)
{
attribute=AcquireString("dcm:");
(void) ConcatenateString(&attribute,dicom_info[i].description);
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i == (ssize_t) length) || (length > 4))
{
(void) SubstituteString(&attribute," ","");
(void) SetImageProperty(image,attribute,(char *) data,exception);
}
attribute=DestroyString(attribute);
}
}
if (image_info->verbose != MagickFalse)
{
if (data == (unsigned char *) NULL)
(void) FormatLocaleFile(stdout,"%d\n",datum);
else
{
/*
Display group data.
*/
for (i=0; i < (ssize_t) MagickMax(length,4); i++)
if (isprint((int) data[i]) == MagickFalse)
break;
if ((i != (ssize_t) length) && (length <= 4))
{
ssize_t
j;
datum=0;
for (j=(ssize_t) length-1; j >= 0; j--)
datum=(256*datum+data[j]);
(void) FormatLocaleFile(stdout,"%d",datum);
}
else
for (i=0; i < (ssize_t) length; i++)
if (isprint((int) data[i]) != MagickFalse)
(void) FormatLocaleFile(stdout,"%c",data[i]);
else
(void) FormatLocaleFile(stdout,"%c",'.');
(void) FormatLocaleFile(stdout,"\n");
}
}
if (data != (unsigned char *) NULL)
data=(unsigned char *) RelinquishMagickMemory(data);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
}
if ((width == 0) || (height == 0))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
image->columns=(size_t) width;
image->rows=(size_t) height;
if (signed_data == 0xffff)
signed_data=(size_t) (significant_bits == 16 ? 1 : 0);
if ((image->compression == JPEGCompression) ||
(image->compression == JPEG2000Compression))
{
Image
*images;
ImageInfo
*read_info;
int
c;
size_t
length;
unsigned int
tag;
/*
Read offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
/*
Handle non-native image formats.
*/
read_info=CloneImageInfo(image_info);
SetImageInfoBlob(read_info,(void *) NULL,0);
images=NewImageList();
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
char
filename[MagickPathExtent];
const char
*property;
FILE
*file;
Image
*jpeg_image;
int
unique_file;
unsigned int
tag;
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
length=(size_t) ReadBlobLSBLong(image);
if (tag == 0xFFFEE0DD)
break; /* sequence delimiter tag */
if (tag != 0xFFFEE000)
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
file=(FILE *) NULL;
unique_file=AcquireUniqueFileResource(filename);
if (unique_file != -1)
file=fdopen(unique_file,"wb");
if (file == (FILE *) NULL)
{
(void) RelinquishUniqueFileResource(filename);
ThrowFileException(exception,FileOpenError,
"UnableToCreateTemporaryFile",filename);
break;
}
for ( ; length != 0; length--)
{
c=ReadBlobByte(image);
if (c == EOF)
{
ThrowFileException(exception,CorruptImageError,
"UnexpectedEndOfFile",image->filename);
break;
}
(void) fputc(c,file);
}
(void) fclose(file);
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"jpeg:%s",filename);
if (image->compression == JPEG2000Compression)
(void) FormatLocaleString(read_info->filename,MagickPathExtent,
"j2k:%s",filename);
jpeg_image=ReadImage(read_info,exception);
if (jpeg_image != (Image *) NULL)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
(void) SetImageProperty(jpeg_image,property,
GetImageProperty(image,property,exception),exception);
property=GetNextImageProperty(image);
}
AppendImageToList(&images,jpeg_image);
}
(void) RelinquishUniqueFileResource(filename);
}
read_info=DestroyImageInfo(read_info);
image=DestroyImage(image);
return(GetFirstImageInList(images));
}
if (depth != (1UL*MAGICKCORE_QUANTUM_DEPTH))
{
QuantumAny
range;
size_t
length;
/*
Compute pixel scaling table.
*/
length=(size_t) (GetQuantumRange(depth)+1);
scale=(Quantum *) AcquireQuantumMemory(length,sizeof(*scale));
if (scale == (Quantum *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
range=GetQuantumRange(depth);
for (i=0; i <= (ssize_t) GetQuantumRange(depth); i++)
scale[i]=ScaleAnyToQuantum((size_t) i,range);
}
if (image->compression == RLECompression)
{
size_t
length;
unsigned int
tag;
/*
Read RLE offset table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
(void) tag;
length=(size_t) ReadBlobLSBLong(image);
stream_info->offset_count=length >> 2;
if (stream_info->offset_count != 0)
{
MagickOffsetType
offset;
stream_info->offsets=(ssize_t *) AcquireQuantumMemory(
stream_info->offset_count,sizeof(*stream_info->offsets));
if (stream_info->offsets == (ssize_t *) NULL)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]=(ssize_t) ReadBlobLSBSignedLong(image);
offset=TellBlob(image);
for (i=0; i < (ssize_t) stream_info->offset_count; i++)
stream_info->offsets[i]+=offset;
}
}
for (scene=0; scene < (ssize_t) number_scenes; scene++)
{
if (image_info->ping != MagickFalse)
break;
image->columns=(size_t) width;
image->rows=(size_t) height;
image->depth=depth;
status=SetImageExtent(image,image->columns,image->rows,exception);
if (status == MagickFalse)
break;
image->colorspace=RGBColorspace;
if ((image->colormap == (PixelInfo *) NULL) && (samples_per_pixel == 1))
{
size_t
one;
one=1;
if (colors == 0)
colors=one << depth;
if (AcquireImageColormap(image,one << depth,exception) == MagickFalse)
ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed");
if (redmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=redmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
}
if (greenmap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=greenmap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].green=(MagickRealType) index;
}
if (bluemap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=bluemap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].blue=(MagickRealType) index;
}
if (graymap != (int *) NULL)
for (i=0; i < (ssize_t) colors; i++)
{
index=graymap[i];
if ((scale != (Quantum *) NULL) && (index <= (int) max_value))
index=(int) scale[index];
image->colormap[i].red=(MagickRealType) index;
image->colormap[i].green=(MagickRealType) index;
image->colormap[i].blue=(MagickRealType) index;
}
}
if (image->compression == RLECompression)
{
unsigned int
tag;
/*
Read RLE segment table.
*/
for (i=0; i < (ssize_t) stream_info->remaining; i++)
(void) ReadBlobByte(image);
tag=(ReadBlobLSBShort(image) << 16) | ReadBlobLSBShort(image);
stream_info->remaining=(size_t) ReadBlobLSBLong(image);
if ((tag != 0xFFFEE000) || (stream_info->remaining <= 64) ||
(EOFBlob(image) != MagickFalse))
ThrowReaderException(CorruptImageError,"ImproperImageHeader");
stream_info->count=0;
stream_info->segment_count=ReadBlobLSBLong(image);
if (stream_info->segment_count > 1)
{
bytes_per_pixel=1;
depth=8;
}
for (i=0; i < 15; i++)
stream_info->segments[i]=(ssize_t) ReadBlobLSBSignedLong(image);
stream_info->remaining-=64;
}
if ((samples_per_pixel > 1) && (image->interlace == PlaneInterlace))
{
/*
Convert Planar RGB DCM Medical image to pixel packets.
*/
for (i=0; i < (ssize_t) samples_per_pixel; i++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
switch ((int) i)
{
case 0:
{
SetPixelRed(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 1:
{
SetPixelGreen(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 2:
{
SetPixelBlue(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
case 3:
{
SetPixelAlpha(image,ScaleCharToQuantum((unsigned char)
ReadDCMByte(stream_info,image)),q);
break;
}
default:
break;
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
}
else
{
const char
*option;
int
byte;
PixelPacket
pixel;
/*
Convert DCM Medical image to pixel packets.
*/
byte=0;
i=0;
if ((window_center != 0) && (window_width == 0))
window_width=(size_t) window_center;
option=GetImageOption(image_info,"dcm:display-range");
if (option != (const char *) NULL)
{
if (LocaleCompare(option,"reset") == 0)
window_width=0;
}
(void) ResetMagickMemory(&pixel,0,sizeof(pixel));
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
if (signed_data)
pixel_value=ReadDCMSignedShort(stream_info,image);
else
pixel_value=ReadDCMShort(stream_info,image);
if (polarity != MagickFalse)
pixel_value=(int)max_value-pixel_value;
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMSignedShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) index,q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
if (pixel.red <= GetQuantumRange(depth))
pixel.red=scale[pixel.red];
if (pixel.green <= GetQuantumRange(depth))
pixel.green=scale[pixel.green];
if (pixel.blue <= GetQuantumRange(depth))
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) pixel.red,q);
SetPixelGreen(image,(Quantum) pixel.green,q);
SetPixelBlue(image,(Quantum) pixel.blue,q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
if (stream_info->segment_count > 1)
for (y=0; y < (ssize_t) image->rows; y++)
{
q=QueueAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (samples_per_pixel == 1)
{
int
pixel_value;
if (bytes_per_pixel == 1)
pixel_value=polarity != MagickFalse ?
((int) max_value-ReadDCMByte(stream_info,image)) :
ReadDCMByte(stream_info,image);
else
if ((bits_allocated != 12) || (significant_bits != 12))
{
pixel_value=(int) (polarity != MagickFalse ?
(max_value-ReadDCMShort(stream_info,image)) :
ReadDCMShort(stream_info,image));
if (signed_data == 1)
pixel_value=((signed short) pixel_value);
}
else
{
if ((i & 0x01) != 0)
pixel_value=(ReadDCMByte(stream_info,image) << 8) |
byte;
else
{
pixel_value=ReadDCMShort(stream_info,image);
byte=(int) (pixel_value & 0x0f);
pixel_value>>=4;
}
i++;
}
index=(pixel_value*rescale_slope)+rescale_intercept;
if (window_width == 0)
{
if (signed_data == 1)
index-=32767;
}
else
{
ssize_t
window_max,
window_min;
window_min=(ssize_t) ceil((double) window_center-
(window_width-1.0)/2.0-0.5);
window_max=(ssize_t) floor((double) window_center+
(window_width-1.0)/2.0+0.5);
if ((ssize_t)index <= window_min)
index=0;
else
if ((ssize_t)index > window_max)
index=(int) max_value;
else
index=(int) (max_value*(((index-window_center-
0.5)/(window_width-1))+0.5));
}
index&=mask;
index=(int) ConstrainColormapIndex(image,(size_t) index,
exception);
SetPixelIndex(image,(Quantum) (((size_t)
GetPixelIndex(image,q)) | (((size_t) index) << 8)),q);
pixel.red=(unsigned int) image->colormap[index].red;
pixel.green=(unsigned int) image->colormap[index].green;
pixel.blue=(unsigned int) image->colormap[index].blue;
}
else
{
if (bytes_per_pixel == 1)
{
pixel.red=(unsigned int) ReadDCMByte(stream_info,image);
pixel.green=(unsigned int) ReadDCMByte(stream_info,image);
pixel.blue=(unsigned int) ReadDCMByte(stream_info,image);
}
else
{
pixel.red=ReadDCMShort(stream_info,image);
pixel.green=ReadDCMShort(stream_info,image);
pixel.blue=ReadDCMShort(stream_info,image);
}
pixel.red&=mask;
pixel.green&=mask;
pixel.blue&=mask;
if (scale != (Quantum *) NULL)
{
pixel.red=scale[pixel.red];
pixel.green=scale[pixel.green];
pixel.blue=scale[pixel.blue];
}
}
SetPixelRed(image,(Quantum) (((size_t) GetPixelRed(image,q)) |
(((size_t) pixel.red) << 8)),q);
SetPixelGreen(image,(Quantum) (((size_t) GetPixelGreen(image,q)) |
(((size_t) pixel.green) << 8)),q);
SetPixelBlue(image,(Quantum) (((size_t) GetPixelBlue(image,q)) |
(((size_t) pixel.blue) << 8)),q);
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image->previous == (Image *) NULL)
{
status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y,
image->rows);
if (status == MagickFalse)
break;
}
}
}
if (SetImageGray(image,exception) != MagickFalse)
(void) SetImageColorspace(image,GRAYColorspace,exception);
if (EOFBlob(image) != MagickFalse)
{
ThrowFileException(exception,CorruptImageError,"UnexpectedEndOfFile",
image->filename);
break;
}
/*
Proceed to next image.
*/
if (image_info->number_scenes != 0)
if (image->scene >= (image_info->scene+image_info->number_scenes-1))
break;
if (scene < (ssize_t) (number_scenes-1))
{
/*
Allocate next image structure.
*/
AcquireNextImage(image_info,image,exception);
if (GetNextImageInList(image) == (Image *) NULL)
{
image=DestroyImageList(image);
return((Image *) NULL);
}
image=SyncNextImageInList(image);
status=SetImageProgress(image,LoadImagesTag,TellBlob(image),
GetBlobSize(image));
if (status == MagickFalse)
break;
}
}
/*
Free resources.
*/
if (stream_info->offsets != (ssize_t *) NULL)
stream_info->offsets=(ssize_t *)
RelinquishMagickMemory(stream_info->offsets);
stream_info=(DCMStreamInfo *) RelinquishMagickMemory(stream_info);
if (scale != (Quantum *) NULL)
scale=(Quantum *) RelinquishMagickMemory(scale);
if (graymap != (int *) NULL)
graymap=(int *) RelinquishMagickMemory(graymap);
if (bluemap != (int *) NULL)
bluemap=(int *) RelinquishMagickMemory(bluemap);
if (greenmap != (int *) NULL)
greenmap=(int *) RelinquishMagickMemory(greenmap);
if (redmap != (int *) NULL)
redmap=(int *) RelinquishMagickMemory(redmap);
(void) CloseBlob(image);
return(GetFirstImageInList(image));
} | {
"deleted": [
{
"line_no": 899,
"char_start": 26296,
"char_end": 26359,
"line": " for (i=0; i < (ssize_t) (GetQuantumRange(depth)+1); i++)\n"
},
{
"line_no": 1190,
"char_start": 36778,
"char_end": 36826,
"line": " pixel.red=scale[pixel.red];\n"
},
{
"line_no": 1191,
"char_start": 36826,
"char_end": 36878,
"line": " pixel.green=scale[pixel.green];\n"
},
{
"line_no": 1192,
"char_start": 36878,
"char_end": 36928,
"line": " pixel.blue=scale[pixel.blue];\n"
}
],
"added": [
{
"line_no": 441,
"char_start": 12526,
"char_end": 12574,
"line": " if (data == (unsigned char *) NULL)\n"
},
{
"line_no": 442,
"char_start": 12574,
"char_end": 12595,
"line": " break;\n"
},
{
"line_no": 464,
"char_start": 13197,
"char_end": 13245,
"line": " if (data == (unsigned char *) NULL)\n"
},
{
"line_no": 465,
"char_start": 13245,
"char_end": 13266,
"line": " break;\n"
},
{
"line_no": 903,
"char_start": 26434,
"char_end": 26494,
"line": " for (i=0; i <= (ssize_t) GetQuantumRange(depth); i++)\n"
},
{
"line_no": 1194,
"char_start": 36913,
"char_end": 36974,
"line": " if (pixel.red <= GetQuantumRange(depth))\n"
},
{
"line_no": 1195,
"char_start": 36974,
"char_end": 37024,
"line": " pixel.red=scale[pixel.red];\n"
},
{
"line_no": 1196,
"char_start": 37024,
"char_end": 37087,
"line": " if (pixel.green <= GetQuantumRange(depth))\n"
},
{
"line_no": 1197,
"char_start": 37087,
"char_end": 37141,
"line": " pixel.green=scale[pixel.green];\n"
},
{
"line_no": 1198,
"char_start": 37141,
"char_end": 37203,
"line": " if (pixel.blue <= GetQuantumRange(depth))\n"
},
{
"line_no": 1199,
"char_start": 37203,
"char_end": 37255,
"line": " pixel.blue=scale[pixel.blue];\n"
}
]
} | {
"deleted": [
{
"char_start": 26326,
"char_end": 26327,
"chars": "("
},
{
"char_start": 26348,
"char_end": 26351,
"chars": ")+1"
}
],
"added": [
{
"char_start": 12538,
"char_end": 12607,
"chars": "if (data == (unsigned char *) NULL)\n break;\n "
},
{
"char_start": 13196,
"char_end": 13265,
"chars": "\n if (data == (unsigned char *) NULL)\n break;"
},
{
"char_start": 26453,
"char_end": 26454,
"chars": "="
},
{
"char_start": 36933,
"char_end": 36996,
"chars": "if (pixel.red <= GetQuantumRange(depth))\n "
},
{
"char_start": 37044,
"char_end": 37109,
"chars": "if (pixel.green <= GetQuantumRange(depth))\n "
},
{
"char_start": 37141,
"char_end": 37205,
"chars": " if (pixel.blue <= GetQuantumRange(depth))\n "
}
]
} | github.com/ImageMagick/ImageMagick/commit/5511ef530576ed18fd636baa3bb4eda3d667665d | coders/dcm.c | cwe-476 |
hash_accept | static int hash_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
struct ahash_request *req = &ctx->req;
char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];
struct sock *sk2;
struct alg_sock *ask2;
struct hash_ctx *ctx2;
int err;
err = crypto_ahash_export(req, state);
if (err)
return err;
err = af_alg_accept(ask->parent, newsock);
if (err)
return err;
sk2 = newsock->sk;
ask2 = alg_sk(sk2);
ctx2 = ask2->private;
ctx2->more = 1;
err = crypto_ahash_import(&ctx2->req, state);
if (err) {
sock_orphan(sk2);
sock_put(sk2);
}
return err;
} | static int hash_accept(struct socket *sock, struct socket *newsock, int flags)
{
struct sock *sk = sock->sk;
struct alg_sock *ask = alg_sk(sk);
struct hash_ctx *ctx = ask->private;
struct ahash_request *req = &ctx->req;
char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];
struct sock *sk2;
struct alg_sock *ask2;
struct hash_ctx *ctx2;
bool more;
int err;
lock_sock(sk);
more = ctx->more;
err = more ? crypto_ahash_export(req, state) : 0;
release_sock(sk);
if (err)
return err;
err = af_alg_accept(ask->parent, newsock);
if (err)
return err;
sk2 = newsock->sk;
ask2 = alg_sk(sk2);
ctx2 = ask2->private;
ctx2->more = more;
if (!more)
return err;
err = crypto_ahash_import(&ctx2->req, state);
if (err) {
sock_orphan(sk2);
sock_put(sk2);
}
return err;
} | {
"deleted": [
{
"line_no": 13,
"char_start": 365,
"char_end": 405,
"line": "\terr = crypto_ahash_export(req, state);\n"
},
{
"line_no": 24,
"char_start": 563,
"char_end": 580,
"line": "\tctx2->more = 1;\n"
}
],
"added": [
{
"line_no": 11,
"char_start": 354,
"char_end": 366,
"line": "\tbool more;\n"
},
{
"line_no": 14,
"char_start": 377,
"char_end": 393,
"line": "\tlock_sock(sk);\n"
},
{
"line_no": 15,
"char_start": 393,
"char_end": 412,
"line": "\tmore = ctx->more;\n"
},
{
"line_no": 16,
"char_start": 412,
"char_end": 463,
"line": "\terr = more ? crypto_ahash_export(req, state) : 0;\n"
},
{
"line_no": 17,
"char_start": 463,
"char_end": 482,
"line": "\trelease_sock(sk);\n"
},
{
"line_no": 18,
"char_start": 482,
"char_end": 483,
"line": "\n"
},
{
"line_no": 29,
"char_start": 641,
"char_end": 661,
"line": "\tctx2->more = more;\n"
},
{
"line_no": 30,
"char_start": 661,
"char_end": 662,
"line": "\n"
},
{
"line_no": 31,
"char_start": 662,
"char_end": 674,
"line": "\tif (!more)\n"
},
{
"line_no": 32,
"char_start": 674,
"char_end": 688,
"line": "\t\treturn err;\n"
}
]
} | {
"deleted": [
{
"char_start": 577,
"char_end": 578,
"chars": "1"
}
],
"added": [
{
"char_start": 355,
"char_end": 367,
"chars": "bool more;\n\t"
},
{
"char_start": 378,
"char_end": 413,
"chars": "lock_sock(sk);\n\tmore = ctx->more;\n\t"
},
{
"char_start": 418,
"char_end": 425,
"chars": " more ?"
},
{
"char_start": 457,
"char_end": 461,
"chars": " : 0"
},
{
"char_start": 462,
"char_end": 482,
"chars": "\n\trelease_sock(sk);\n"
},
{
"char_start": 655,
"char_end": 686,
"chars": "more;\n\n\tif (!more)\n\t\treturn err"
}
]
} | github.com/torvalds/linux/commit/4afa5f9617927453ac04b24b584f6c718dfb4f45 | crypto/algif_hash.c | cwe-476 |
php_wddx_pop_element | */
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
} else {
stack->done = 1;
}
efree(ent1);
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
} | */
static void php_wddx_pop_element(void *user_data, const XML_Char *name)
{
st_entry *ent1, *ent2;
wddx_stack *stack = (wddx_stack *)user_data;
HashTable *target_hash;
zend_class_entry **pce;
zval *obj;
zval *tmp;
TSRMLS_FETCH();
/* OBJECTS_FIXME */
if (stack->top == 0) {
return;
}
if (!strcmp(name, EL_STRING) || !strcmp(name, EL_NUMBER) ||
!strcmp(name, EL_BOOLEAN) || !strcmp(name, EL_NULL) ||
!strcmp(name, EL_ARRAY) || !strcmp(name, EL_STRUCT) ||
!strcmp(name, EL_RECORDSET) || !strcmp(name, EL_BINARY) ||
!strcmp(name, EL_DATETIME)) {
wddx_stack_top(stack, (void**)&ent1);
if (!ent1->data) {
if (stack->top > 1) {
stack->top--;
} else {
stack->done = 1;
}
efree(ent1);
return;
}
if (!strcmp(name, EL_BINARY)) {
int new_len=0;
unsigned char *new_str;
new_str = php_base64_decode(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data), &new_len);
STR_FREE(Z_STRVAL_P(ent1->data));
if (new_str) {
Z_STRVAL_P(ent1->data) = new_str;
Z_STRLEN_P(ent1->data) = new_len;
} else {
ZVAL_EMPTY_STRING(ent1->data);
}
}
/* Call __wakeup() method on the object. */
if (Z_TYPE_P(ent1->data) == IS_OBJECT) {
zval *fname, *retval = NULL;
MAKE_STD_ZVAL(fname);
ZVAL_STRING(fname, "__wakeup", 1);
call_user_function_ex(NULL, &ent1->data, fname, &retval, 0, 0, 0, NULL TSRMLS_CC);
zval_dtor(fname);
FREE_ZVAL(fname);
if (retval) {
zval_ptr_dtor(&retval);
}
}
if (stack->top > 1) {
stack->top--;
wddx_stack_top(stack, (void**)&ent2);
/* if non-existent field */
if (ent2->type == ST_FIELD && ent2->data == NULL) {
zval_ptr_dtor(&ent1->data);
efree(ent1);
return;
}
if (Z_TYPE_P(ent2->data) == IS_ARRAY || Z_TYPE_P(ent2->data) == IS_OBJECT) {
target_hash = HASH_OF(ent2->data);
if (ent1->varname) {
if (!strcmp(ent1->varname, PHP_CLASS_NAME_VAR) &&
Z_TYPE_P(ent1->data) == IS_STRING && Z_STRLEN_P(ent1->data) &&
ent2->type == ST_STRUCT && Z_TYPE_P(ent2->data) == IS_ARRAY) {
zend_bool incomplete_class = 0;
zend_str_tolower(Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
if (zend_hash_find(EG(class_table), Z_STRVAL_P(ent1->data),
Z_STRLEN_P(ent1->data)+1, (void **) &pce)==FAILURE) {
incomplete_class = 1;
pce = &PHP_IC_ENTRY;
}
/* Initialize target object */
MAKE_STD_ZVAL(obj);
object_init_ex(obj, *pce);
/* Merge current hashtable with object's default properties */
zend_hash_merge(Z_OBJPROP_P(obj),
Z_ARRVAL_P(ent2->data),
(void (*)(void *)) zval_add_ref,
(void *) &tmp, sizeof(zval *), 0);
if (incomplete_class) {
php_store_class_name(obj, Z_STRVAL_P(ent1->data), Z_STRLEN_P(ent1->data));
}
/* Clean up old array entry */
zval_ptr_dtor(&ent2->data);
/* Set stack entry to point to the newly created object */
ent2->data = obj;
/* Clean up class name var entry */
zval_ptr_dtor(&ent1->data);
} else if (Z_TYPE_P(ent2->data) == IS_OBJECT) {
zend_class_entry *old_scope = EG(scope);
EG(scope) = Z_OBJCE_P(ent2->data);
Z_DELREF_P(ent1->data);
add_property_zval(ent2->data, ent1->varname, ent1->data);
EG(scope) = old_scope;
} else {
zend_symtable_update(target_hash, ent1->varname, strlen(ent1->varname)+1, &ent1->data, sizeof(zval *), NULL);
}
efree(ent1->varname);
} else {
zend_hash_next_index_insert(target_hash, &ent1->data, sizeof(zval *), NULL);
}
}
efree(ent1);
} else {
stack->done = 1;
}
} else if (!strcmp(name, EL_VAR) && stack->varname) {
efree(stack->varname);
stack->varname = NULL;
} else if (!strcmp(name, EL_FIELD)) {
st_entry *ent;
wddx_stack_top(stack, (void **)&ent);
efree(ent);
stack->top--;
} | {
"deleted": [
{
"line_no": 40,
"char_start": 966,
"char_end": 1003,
"line": "\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n"
},
{
"line_no": 41,
"char_start": 1003,
"char_end": 1040,
"line": "\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n"
}
],
"added": [
{
"line_no": 40,
"char_start": 966,
"char_end": 984,
"line": "\t\t\tif (new_str) {\n"
},
{
"line_no": 41,
"char_start": 984,
"char_end": 1022,
"line": "\t\t\t\tZ_STRVAL_P(ent1->data) = new_str;\n"
},
{
"line_no": 42,
"char_start": 1022,
"char_end": 1060,
"line": "\t\t\t\tZ_STRLEN_P(ent1->data) = new_len;\n"
},
{
"line_no": 43,
"char_start": 1060,
"char_end": 1072,
"line": "\t\t\t} else {\n"
},
{
"line_no": 44,
"char_start": 1072,
"char_end": 1107,
"line": "\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n"
},
{
"line_no": 45,
"char_start": 1107,
"char_end": 1112,
"line": "\t\t\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 969,
"char_end": 988,
"chars": "if (new_str) {\n\t\t\t\t"
},
{
"char_start": 1025,
"char_end": 1026,
"chars": "\t"
},
{
"char_start": 1059,
"char_end": 1111,
"chars": "\n\t\t\t} else {\n\t\t\t\tZVAL_EMPTY_STRING(ent1->data);\n\t\t\t}"
}
]
} | github.com/php/php-src/commit/698a691724c0a949295991e5df091ce16f899e02 | ext/wddx/wddx.c | cwe-476 |
prplcb_xfer_new_send_cb | static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
PurpleXfer *xfer = data;
struct im_connection *ic = purple_ic_by_pa(xfer->account);
struct prpl_xfer_data *px = xfer->ui_data;
PurpleBuddy *buddy;
const char *who;
buddy = purple_find_buddy(xfer->account, xfer->who);
who = buddy ? purple_buddy_get_name(buddy) : xfer->who;
/* TODO(wilmer): After spreading some more const goodness in BitlBee,
remove the evil cast below. */
px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);
px->ft->data = px;
px->ft->accept = prpl_xfer_accept;
px->ft->canceled = prpl_xfer_canceled;
px->ft->free = prpl_xfer_free;
px->ft->write_request = prpl_xfer_write_request;
return FALSE;
} | static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
PurpleXfer *xfer = data;
struct im_connection *ic = purple_ic_by_pa(xfer->account);
struct prpl_xfer_data *px = xfer->ui_data;
PurpleBuddy *buddy;
const char *who;
buddy = purple_find_buddy(xfer->account, xfer->who);
who = buddy ? purple_buddy_get_name(buddy) : xfer->who;
/* TODO(wilmer): After spreading some more const goodness in BitlBee,
remove the evil cast below. */
px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);
if (!px->ft) {
return FALSE;
}
px->ft->data = px;
px->ft->accept = prpl_xfer_accept;
px->ft->canceled = prpl_xfer_canceled;
px->ft->free = prpl_xfer_free;
px->ft->write_request = prpl_xfer_write_request;
return FALSE;
} | {
"deleted": [],
"added": [
{
"line_no": 15,
"char_start": 556,
"char_end": 557,
"line": "\n"
},
{
"line_no": 16,
"char_start": 557,
"char_end": 573,
"line": "\tif (!px->ft) {\n"
},
{
"line_no": 17,
"char_start": 573,
"char_end": 589,
"line": "\t\treturn FALSE;\n"
},
{
"line_no": 18,
"char_start": 589,
"char_end": 592,
"line": "\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 556,
"char_end": 592,
"chars": "\n\tif (!px->ft) {\n\t\treturn FALSE;\n\t}\n"
}
]
} | github.com/bitlbee/bitlbee/commit/30d598ce7cd3f136ee9d7097f39fa9818a272441 | protocols/purple/ft.c | cwe-476 |
changedline | static int changedline (const Proto *p, int oldpc, int newpc) {
while (oldpc++ < newpc) {
if (p->lineinfo[oldpc] != 0)
return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));
}
return 0; /* no line changes in the way */
} | static int changedline (const Proto *p, int oldpc, int newpc) {
if (p->lineinfo == NULL) /* no debug information? */
return 0;
while (oldpc++ < newpc) {
if (p->lineinfo[oldpc] != 0)
return (luaG_getfuncline(p, oldpc - 1) != luaG_getfuncline(p, newpc));
}
return 0; /* no line changes between positions */
} | {
"deleted": [
{
"line_no": 6,
"char_start": 206,
"char_end": 252,
"line": " return 0; /* no line changes in the way */\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 64,
"char_end": 120,
"line": " if (p->lineinfo == NULL) /* no debug information? */\n"
},
{
"line_no": 3,
"char_start": 120,
"char_end": 134,
"line": " return 0;\n"
},
{
"line_no": 8,
"char_start": 276,
"char_end": 329,
"line": " return 0; /* no line changes between positions */\n"
}
]
} | {
"deleted": [
{
"char_start": 238,
"char_end": 239,
"chars": "i"
},
{
"char_start": 242,
"char_end": 248,
"chars": "he way"
}
],
"added": [
{
"char_start": 66,
"char_end": 136,
"chars": "if (p->lineinfo == NULL) /* no debug information? */\n return 0;\n "
},
{
"char_start": 308,
"char_end": 310,
"chars": "be"
},
{
"char_start": 311,
"char_end": 312,
"chars": "w"
},
{
"char_start": 313,
"char_end": 315,
"chars": "en"
},
{
"char_start": 316,
"char_end": 325,
"chars": "positions"
}
]
} | github.com/lua/lua/commit/ae5b5ba529753c7a653901ffc29b5ea24c3fdf3a | ldebug.c | cwe-476 |
exprListAppendList | static ExprList *exprListAppendList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
ExprList *pAppend, /* List of values to append. Might be NULL */
int bIntToNull
){
if( pAppend ){
int i;
int nInit = pList ? pList->nExpr : 0;
for(i=0; i<pAppend->nExpr; i++){
Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
pDup->op = TK_NULL;
pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
}
pList = sqlite3ExprListAppend(pParse, pList, pDup);
if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
}
}
return pList;
} | static ExprList *exprListAppendList(
Parse *pParse, /* Parsing context */
ExprList *pList, /* List to which to append. Might be NULL */
ExprList *pAppend, /* List of values to append. Might be NULL */
int bIntToNull
){
if( pAppend ){
int i;
int nInit = pList ? pList->nExpr : 0;
for(i=0; i<pAppend->nExpr; i++){
Expr *pDup = sqlite3ExprDup(pParse->db, pAppend->a[i].pExpr, 0);
assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );
if( bIntToNull && pDup && pDup->op==TK_INTEGER ){
pDup->op = TK_NULL;
pDup->flags &= ~(EP_IntValue|EP_IsTrue|EP_IsFalse);
pDup->u.zToken = 0;
}
pList = sqlite3ExprListAppend(pParse, pList, pDup);
if( pList ) pList->a[nInit+i].sortFlags = pAppend->a[i].sortFlags;
}
}
return pList;
} | {
"deleted": [],
"added": [
{
"line_no": 12,
"char_start": 426,
"char_end": 490,
"line": " assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );\n"
},
{
"line_no": 16,
"char_start": 634,
"char_end": 662,
"line": " pDup->u.zToken = 0;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 432,
"char_end": 496,
"chars": "assert( pDup==0 || !ExprHasProperty(pDup, EP_MemToken) );\n "
},
{
"char_start": 632,
"char_end": 660,
"chars": ";\n pDup->u.zToken = 0"
}
]
} | github.com/sqlite/sqlite/commit/75e95e1fcd52d3ec8282edb75ac8cd0814095d54 | src/window.c | cwe-476 |
inet_rtm_getroute | static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(in_skb->sk);
struct rtmsg *rtm;
struct nlattr *tb[RTA_MAX+1];
struct fib_result res = {};
struct rtable *rt = NULL;
struct flowi4 fl4;
__be32 dst = 0;
__be32 src = 0;
u32 iif;
int err;
int mark;
struct sk_buff *skb;
u32 table_id = RT_TABLE_MAIN;
kuid_t uid;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy,
extack);
if (err < 0)
goto errout;
rtm = nlmsg_data(nlh);
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
err = -ENOBUFS;
goto errout;
}
/* Reserve room for dummy headers, this skb can pass
through good chunk of routing engine.
*/
skb_reset_mac_header(skb);
skb_reset_network_header(skb);
src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;
dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;
iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0;
mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0;
if (tb[RTA_UID])
uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID]));
else
uid = (iif ? INVALID_UID : current_uid());
/* Bugfix: need to give ip_route_input enough of an IP header to
* not gag.
*/
ip_hdr(skb)->protocol = IPPROTO_UDP;
ip_hdr(skb)->saddr = src;
ip_hdr(skb)->daddr = dst;
skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr));
memset(&fl4, 0, sizeof(fl4));
fl4.daddr = dst;
fl4.saddr = src;
fl4.flowi4_tos = rtm->rtm_tos;
fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0;
fl4.flowi4_mark = mark;
fl4.flowi4_uid = uid;
rcu_read_lock();
if (iif) {
struct net_device *dev;
dev = dev_get_by_index_rcu(net, iif);
if (!dev) {
err = -ENODEV;
goto errout_free;
}
skb->protocol = htons(ETH_P_IP);
skb->dev = dev;
skb->mark = mark;
err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos,
dev, &res);
rt = skb_rtable(skb);
if (err == 0 && rt->dst.error)
err = -rt->dst.error;
} else {
rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb);
err = 0;
if (IS_ERR(rt))
err = PTR_ERR(rt);
else
skb_dst_set(skb, &rt->dst);
}
if (err)
goto errout_free;
if (rtm->rtm_flags & RTM_F_NOTIFY)
rt->rt_flags |= RTCF_NOTIFY;
if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE)
table_id = rt->rt_table_id;
if (rtm->rtm_flags & RTM_F_FIB_MATCH)
err = fib_dump_info(skb, NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, RTM_NEWROUTE, table_id,
rt->rt_type, res.prefix, res.prefixlen,
fl4.flowi4_tos, res.fi, 0);
else
err = rt_fill_info(net, dst, src, table_id, &fl4, skb,
NETLINK_CB(in_skb).portid, nlh->nlmsg_seq);
if (err < 0)
goto errout_free;
rcu_read_unlock();
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
return err;
errout_free:
rcu_read_unlock();
kfree_skb(skb);
goto errout;
} | static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh,
struct netlink_ext_ack *extack)
{
struct net *net = sock_net(in_skb->sk);
struct rtmsg *rtm;
struct nlattr *tb[RTA_MAX+1];
struct fib_result res = {};
struct rtable *rt = NULL;
struct flowi4 fl4;
__be32 dst = 0;
__be32 src = 0;
u32 iif;
int err;
int mark;
struct sk_buff *skb;
u32 table_id = RT_TABLE_MAIN;
kuid_t uid;
err = nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy,
extack);
if (err < 0)
goto errout;
rtm = nlmsg_data(nlh);
skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
if (!skb) {
err = -ENOBUFS;
goto errout;
}
/* Reserve room for dummy headers, this skb can pass
through good chunk of routing engine.
*/
skb_reset_mac_header(skb);
skb_reset_network_header(skb);
src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0;
dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0;
iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0;
mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0;
if (tb[RTA_UID])
uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID]));
else
uid = (iif ? INVALID_UID : current_uid());
/* Bugfix: need to give ip_route_input enough of an IP header to
* not gag.
*/
ip_hdr(skb)->protocol = IPPROTO_UDP;
ip_hdr(skb)->saddr = src;
ip_hdr(skb)->daddr = dst;
skb_reserve(skb, MAX_HEADER + sizeof(struct iphdr));
memset(&fl4, 0, sizeof(fl4));
fl4.daddr = dst;
fl4.saddr = src;
fl4.flowi4_tos = rtm->rtm_tos;
fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0;
fl4.flowi4_mark = mark;
fl4.flowi4_uid = uid;
rcu_read_lock();
if (iif) {
struct net_device *dev;
dev = dev_get_by_index_rcu(net, iif);
if (!dev) {
err = -ENODEV;
goto errout_free;
}
skb->protocol = htons(ETH_P_IP);
skb->dev = dev;
skb->mark = mark;
err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos,
dev, &res);
rt = skb_rtable(skb);
if (err == 0 && rt->dst.error)
err = -rt->dst.error;
} else {
rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb);
err = 0;
if (IS_ERR(rt))
err = PTR_ERR(rt);
else
skb_dst_set(skb, &rt->dst);
}
if (err)
goto errout_free;
if (rtm->rtm_flags & RTM_F_NOTIFY)
rt->rt_flags |= RTCF_NOTIFY;
if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE)
table_id = rt->rt_table_id;
if (rtm->rtm_flags & RTM_F_FIB_MATCH) {
if (!res.fi) {
err = fib_props[res.type].error;
if (!err)
err = -EHOSTUNREACH;
goto errout_free;
}
err = fib_dump_info(skb, NETLINK_CB(in_skb).portid,
nlh->nlmsg_seq, RTM_NEWROUTE, table_id,
rt->rt_type, res.prefix, res.prefixlen,
fl4.flowi4_tos, res.fi, 0);
} else {
err = rt_fill_info(net, dst, src, table_id, &fl4, skb,
NETLINK_CB(in_skb).portid, nlh->nlmsg_seq);
}
if (err < 0)
goto errout_free;
rcu_read_unlock();
err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid);
errout:
return err;
errout_free:
rcu_read_unlock();
kfree_skb(skb);
goto errout;
} | {
"deleted": [
{
"line_no": 102,
"char_start": 2323,
"char_end": 2362,
"line": "\tif (rtm->rtm_flags & RTM_F_FIB_MATCH)\n"
},
{
"line_no": 107,
"char_start": 2548,
"char_end": 2554,
"line": "\telse\n"
}
],
"added": [
{
"line_no": 102,
"char_start": 2323,
"char_end": 2364,
"line": "\tif (rtm->rtm_flags & RTM_F_FIB_MATCH) {\n"
},
{
"line_no": 103,
"char_start": 2364,
"char_end": 2381,
"line": "\t\tif (!res.fi) {\n"
},
{
"line_no": 104,
"char_start": 2381,
"char_end": 2417,
"line": "\t\t\terr = fib_props[res.type].error;\n"
},
{
"line_no": 105,
"char_start": 2417,
"char_end": 2430,
"line": "\t\t\tif (!err)\n"
},
{
"line_no": 106,
"char_start": 2430,
"char_end": 2455,
"line": "\t\t\t\terr = -EHOSTUNREACH;\n"
},
{
"line_no": 107,
"char_start": 2455,
"char_end": 2476,
"line": "\t\t\tgoto errout_free;\n"
},
{
"line_no": 108,
"char_start": 2476,
"char_end": 2480,
"line": "\t\t}\n"
},
{
"line_no": 113,
"char_start": 2666,
"char_end": 2676,
"line": "\t} else {\n"
},
{
"line_no": 116,
"char_start": 2784,
"char_end": 2787,
"line": "\t}\n"
}
]
} | {
"deleted": [
{
"char_start": 2362,
"char_end": 2362,
"chars": ""
},
{
"char_start": 2611,
"char_end": 2611,
"chars": ""
}
],
"added": [
{
"char_start": 2361,
"char_end": 2479,
"chars": " {\n\t\tif (!res.fi) {\n\t\t\terr = fib_props[res.type].error;\n\t\t\tif (!err)\n\t\t\t\terr = -EHOSTUNREACH;\n\t\t\tgoto errout_free;\n\t\t}"
},
{
"char_start": 2667,
"char_end": 2669,
"chars": "} "
},
{
"char_start": 2673,
"char_end": 2675,
"chars": " {"
},
{
"char_start": 2783,
"char_end": 2786,
"chars": "\n\t}"
}
]
} | github.com/torvalds/linux/commit/bc3aae2bbac46dd894c89db5d5e98f7f0ef9e205 | net/ipv4/route.c | cwe-476 |
LookupModMask | LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, xkb_mod_mask_t *val_rtrn)
{
const char *str;
xkb_mod_index_t ndx;
const LookupModMaskPriv *arg = priv;
const struct xkb_mod_set *mods = arg->mods;
enum mod_type mod_type = arg->mod_type;
if (type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
if (istreq(str, "all")) {
*val_rtrn = MOD_REAL_MASK_ALL;
return true;
}
if (istreq(str, "none")) {
*val_rtrn = 0;
return true;
}
ndx = XkbModNameToIndex(mods, field, mod_type);
if (ndx == XKB_MOD_INVALID)
return false;
*val_rtrn = (1u << ndx);
return true;
} | LookupModMask(struct xkb_context *ctx, const void *priv, xkb_atom_t field,
enum expr_value_type type, xkb_mod_mask_t *val_rtrn)
{
const char *str;
xkb_mod_index_t ndx;
const LookupModMaskPriv *arg = priv;
const struct xkb_mod_set *mods = arg->mods;
enum mod_type mod_type = arg->mod_type;
if (type != EXPR_TYPE_INT)
return false;
str = xkb_atom_text(ctx, field);
if (!str)
return false;
if (istreq(str, "all")) {
*val_rtrn = MOD_REAL_MASK_ALL;
return true;
}
if (istreq(str, "none")) {
*val_rtrn = 0;
return true;
}
ndx = XkbModNameToIndex(mods, field, mod_type);
if (ndx == XKB_MOD_INVALID)
return false;
*val_rtrn = (1u << ndx);
return true;
} | {
"deleted": [],
"added": [
{
"line_no": 14,
"char_start": 415,
"char_end": 429,
"line": " if (!str)\n"
},
{
"line_no": 15,
"char_start": 429,
"char_end": 451,
"line": " return false;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 415,
"char_end": 451,
"chars": " if (!str)\n return false;\n"
}
]
} | github.com/xkbcommon/libxkbcommon/commit/4e2ee9c3f6050d773f8bbe05bc0edb17f1ff8371 | src/xkbcomp/expr.c | cwe-476 |
validate_as_request | validate_as_request(kdc_realm_t *kdc_active_realm,
register krb5_kdc_req *request, krb5_db_entry client,
krb5_db_entry server, krb5_timestamp kdc_time,
const char **status, krb5_pa_data ***e_data)
{
int errcode;
krb5_error_code ret;
/*
* If an option is set that is only allowed in TGS requests, complain.
*/
if (request->kdc_options & AS_INVALID_OPTIONS) {
*status = "INVALID AS OPTIONS";
return KDC_ERR_BADOPTION;
}
/* The client must not be expired */
if (client.expiration && client.expiration < kdc_time) {
*status = "CLIENT EXPIRED";
if (vague_errors)
return(KRB_ERR_GENERIC);
else
return(KDC_ERR_NAME_EXP);
}
/* The client's password must not be expired, unless the server is
a KRB5_KDC_PWCHANGE_SERVICE. */
if (client.pw_expiration && client.pw_expiration < kdc_time &&
!isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {
*status = "CLIENT KEY EXPIRED";
if (vague_errors)
return(KRB_ERR_GENERIC);
else
return(KDC_ERR_KEY_EXP);
}
/* The server must not be expired */
if (server.expiration && server.expiration < kdc_time) {
*status = "SERVICE EXPIRED";
return(KDC_ERR_SERVICE_EXP);
}
/*
* If the client requires password changing, then only allow the
* pwchange service.
*/
if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) &&
!isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {
*status = "REQUIRED PWCHANGE";
return(KDC_ERR_KEY_EXP);
}
/* Client and server must allow postdating tickets */
if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) ||
isflagset(request->kdc_options, KDC_OPT_POSTDATED)) &&
(isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) ||
isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) {
*status = "POSTDATE NOT ALLOWED";
return(KDC_ERR_CANNOT_POSTDATE);
}
/*
* A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of
* KDC_ERR_POLICY in the following case:
*
* - KDC_OPT_FORWARDABLE is set in KDCOptions but local
* policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the
* client, and;
* - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but
* preauthentication data is absent in the request.
*
* Hence, this check most be done after the check for preauth
* data, and is now performed by validate_forwardable() (the
* contents of which were previously below).
*/
/* Client and server must allow proxiable tickets */
if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) &&
(isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) ||
isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) {
*status = "PROXIABLE NOT ALLOWED";
return(KDC_ERR_POLICY);
}
/* Check to see if client is locked out */
if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {
*status = "CLIENT LOCKED OUT";
return(KDC_ERR_CLIENT_REVOKED);
}
/* Check to see if server is locked out */
if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {
*status = "SERVICE LOCKED OUT";
return(KDC_ERR_S_PRINCIPAL_UNKNOWN);
}
/* Check to see if server is allowed to be a service */
if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) {
*status = "SERVICE NOT ALLOWED";
return(KDC_ERR_MUST_USE_USER2USER);
}
if (check_anon(kdc_active_realm, request->client, request->server) != 0) {
*status = "ANONYMOUS NOT ALLOWED";
return(KDC_ERR_POLICY);
}
/* Perform KDB module policy checks. */
ret = krb5_db_check_policy_as(kdc_context, request, &client, &server,
kdc_time, status, e_data);
if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP)
return errcode_to_protocol(ret);
/* Check against local policy. */
errcode = against_local_policy_as(request, client, server,
kdc_time, status, e_data);
if (errcode)
return errcode;
return 0;
} | validate_as_request(kdc_realm_t *kdc_active_realm,
register krb5_kdc_req *request, krb5_db_entry client,
krb5_db_entry server, krb5_timestamp kdc_time,
const char **status, krb5_pa_data ***e_data)
{
int errcode;
krb5_error_code ret;
/*
* If an option is set that is only allowed in TGS requests, complain.
*/
if (request->kdc_options & AS_INVALID_OPTIONS) {
*status = "INVALID AS OPTIONS";
return KDC_ERR_BADOPTION;
}
/* The client must not be expired */
if (client.expiration && client.expiration < kdc_time) {
*status = "CLIENT EXPIRED";
if (vague_errors)
return(KRB_ERR_GENERIC);
else
return(KDC_ERR_NAME_EXP);
}
/* The client's password must not be expired, unless the server is
a KRB5_KDC_PWCHANGE_SERVICE. */
if (client.pw_expiration && client.pw_expiration < kdc_time &&
!isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {
*status = "CLIENT KEY EXPIRED";
if (vague_errors)
return(KRB_ERR_GENERIC);
else
return(KDC_ERR_KEY_EXP);
}
/* The server must not be expired */
if (server.expiration && server.expiration < kdc_time) {
*status = "SERVICE EXPIRED";
return(KDC_ERR_SERVICE_EXP);
}
/*
* If the client requires password changing, then only allow the
* pwchange service.
*/
if (isflagset(client.attributes, KRB5_KDB_REQUIRES_PWCHANGE) &&
!isflagset(server.attributes, KRB5_KDB_PWCHANGE_SERVICE)) {
*status = "REQUIRED PWCHANGE";
return(KDC_ERR_KEY_EXP);
}
/* Client and server must allow postdating tickets */
if ((isflagset(request->kdc_options, KDC_OPT_ALLOW_POSTDATE) ||
isflagset(request->kdc_options, KDC_OPT_POSTDATED)) &&
(isflagset(client.attributes, KRB5_KDB_DISALLOW_POSTDATED) ||
isflagset(server.attributes, KRB5_KDB_DISALLOW_POSTDATED))) {
*status = "POSTDATE NOT ALLOWED";
return(KDC_ERR_CANNOT_POSTDATE);
}
/*
* A Windows KDC will return KDC_ERR_PREAUTH_REQUIRED instead of
* KDC_ERR_POLICY in the following case:
*
* - KDC_OPT_FORWARDABLE is set in KDCOptions but local
* policy has KRB5_KDB_DISALLOW_FORWARDABLE set for the
* client, and;
* - KRB5_KDB_REQUIRES_PRE_AUTH is set for the client but
* preauthentication data is absent in the request.
*
* Hence, this check most be done after the check for preauth
* data, and is now performed by validate_forwardable() (the
* contents of which were previously below).
*/
/* Client and server must allow proxiable tickets */
if (isflagset(request->kdc_options, KDC_OPT_PROXIABLE) &&
(isflagset(client.attributes, KRB5_KDB_DISALLOW_PROXIABLE) ||
isflagset(server.attributes, KRB5_KDB_DISALLOW_PROXIABLE))) {
*status = "PROXIABLE NOT ALLOWED";
return(KDC_ERR_POLICY);
}
/* Check to see if client is locked out */
if (isflagset(client.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {
*status = "CLIENT LOCKED OUT";
return(KDC_ERR_CLIENT_REVOKED);
}
/* Check to see if server is locked out */
if (isflagset(server.attributes, KRB5_KDB_DISALLOW_ALL_TIX)) {
*status = "SERVICE LOCKED OUT";
return(KDC_ERR_S_PRINCIPAL_UNKNOWN);
}
/* Check to see if server is allowed to be a service */
if (isflagset(server.attributes, KRB5_KDB_DISALLOW_SVR)) {
*status = "SERVICE NOT ALLOWED";
return(KDC_ERR_MUST_USE_USER2USER);
}
if (check_anon(kdc_active_realm, client.princ, request->server) != 0) {
*status = "ANONYMOUS NOT ALLOWED";
return(KDC_ERR_POLICY);
}
/* Perform KDB module policy checks. */
ret = krb5_db_check_policy_as(kdc_context, request, &client, &server,
kdc_time, status, e_data);
if (ret && ret != KRB5_PLUGIN_OP_NOTSUPP)
return errcode_to_protocol(ret);
/* Check against local policy. */
errcode = against_local_policy_as(request, client, server,
kdc_time, status, e_data);
if (errcode)
return errcode;
return 0;
} | {
"deleted": [
{
"line_no": 103,
"char_start": 3679,
"char_end": 3758,
"line": " if (check_anon(kdc_active_realm, request->client, request->server) != 0) {\n"
}
],
"added": [
{
"line_no": 103,
"char_start": 3679,
"char_end": 3755,
"line": " if (check_anon(kdc_active_realm, client.princ, request->server) != 0) {\n"
}
]
} | {
"deleted": [
{
"char_start": 3716,
"char_end": 3725,
"chars": "request->"
}
],
"added": [
{
"char_start": 3722,
"char_end": 3728,
"chars": ".princ"
}
]
} | github.com/krb5/krb5/commit/93b4a6306a0026cf1cc31ac4bd8a49ba5d034ba7 | src/kdc/kdc_util.c | cwe-476 |
rfcomm_sock_bind | static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc *sa = (struct sockaddr_rc *) addr;
struct sock *sk = sock->sk;
int chan = sa->rc_channel;
int err = 0;
BT_DBG("sk %p %pMR", sk, &sa->rc_bdaddr);
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);
rfcomm_pi(sk)->channel = chan;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
} | static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
{
struct sockaddr_rc sa;
struct sock *sk = sock->sk;
int len, err = 0;
if (!addr || addr->sa_family != AF_BLUETOOTH)
return -EINVAL;
memset(&sa, 0, sizeof(sa));
len = min_t(unsigned int, sizeof(sa), addr_len);
memcpy(&sa, addr, len);
BT_DBG("sk %p %pMR", sk, &sa.rc_bdaddr);
lock_sock(sk);
if (sk->sk_state != BT_OPEN) {
err = -EBADFD;
goto done;
}
if (sk->sk_type != SOCK_STREAM) {
err = -EINVAL;
goto done;
}
write_lock(&rfcomm_sk_list.lock);
if (sa.rc_channel &&
__rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {
err = -EADDRINUSE;
} else {
/* Save source address */
bacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);
rfcomm_pi(sk)->channel = sa.rc_channel;
sk->sk_state = BT_BOUND;
}
write_unlock(&rfcomm_sk_list.lock);
done:
release_sock(sk);
return err;
} | {
"deleted": [
{
"line_no": 3,
"char_start": 88,
"char_end": 143,
"line": "\tstruct sockaddr_rc *sa = (struct sockaddr_rc *) addr;\n"
},
{
"line_no": 5,
"char_start": 172,
"char_end": 200,
"line": "\tint chan = sa->rc_channel;\n"
},
{
"line_no": 6,
"char_start": 200,
"char_end": 214,
"line": "\tint err = 0;\n"
},
{
"line_no": 7,
"char_start": 214,
"char_end": 215,
"line": "\n"
},
{
"line_no": 8,
"char_start": 215,
"char_end": 258,
"line": "\tBT_DBG(\"sk %p %pMR\", sk, &sa->rc_bdaddr);\n"
},
{
"line_no": 27,
"char_start": 513,
"char_end": 584,
"line": "\tif (chan && __rfcomm_get_listen_sock_by_addr(chan, &sa->rc_bdaddr)) {\n"
},
{
"line_no": 31,
"char_start": 643,
"char_end": 689,
"line": "\t\tbacpy(&rfcomm_pi(sk)->src, &sa->rc_bdaddr);\n"
},
{
"line_no": 32,
"char_start": 689,
"char_end": 722,
"line": "\t\trfcomm_pi(sk)->channel = chan;\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 88,
"char_end": 112,
"line": "\tstruct sockaddr_rc sa;\n"
},
{
"line_no": 5,
"char_start": 141,
"char_end": 160,
"line": "\tint len, err = 0;\n"
},
{
"line_no": 10,
"char_start": 227,
"char_end": 256,
"line": "\tmemset(&sa, 0, sizeof(sa));\n"
},
{
"line_no": 11,
"char_start": 256,
"char_end": 306,
"line": "\tlen = min_t(unsigned int, sizeof(sa), addr_len);\n"
},
{
"line_no": 12,
"char_start": 306,
"char_end": 331,
"line": "\tmemcpy(&sa, addr, len);\n"
},
{
"line_no": 13,
"char_start": 331,
"char_end": 332,
"line": "\n"
},
{
"line_no": 14,
"char_start": 332,
"char_end": 374,
"line": "\tBT_DBG(\"sk %p %pMR\", sk, &sa.rc_bdaddr);\n"
},
{
"line_no": 15,
"char_start": 374,
"char_end": 375,
"line": "\n"
},
{
"line_no": 30,
"char_start": 563,
"char_end": 585,
"line": "\tif (sa.rc_channel &&\n"
},
{
"line_no": 31,
"char_start": 585,
"char_end": 656,
"line": "\t __rfcomm_get_listen_sock_by_addr(sa.rc_channel, &sa.rc_bdaddr)) {\n"
},
{
"line_no": 35,
"char_start": 715,
"char_end": 760,
"line": "\t\tbacpy(&rfcomm_pi(sk)->src, &sa.rc_bdaddr);\n"
},
{
"line_no": 36,
"char_start": 760,
"char_end": 802,
"line": "\t\trfcomm_pi(sk)->channel = sa.rc_channel;\n"
}
]
} | {
"deleted": [
{
"char_start": 108,
"char_end": 109,
"chars": "*"
},
{
"char_start": 111,
"char_end": 141,
"chars": " = (struct sockaddr_rc *) addr"
},
{
"char_start": 177,
"char_end": 197,
"chars": "chan = sa->rc_channe"
},
{
"char_start": 198,
"char_end": 202,
"chars": ";\n\ti"
},
{
"char_start": 203,
"char_end": 204,
"chars": "t"
},
{
"char_start": 216,
"char_end": 260,
"chars": "BT_DBG(\"sk %p %pMR\", sk, &sa->rc_bdaddr);\n\n\t"
},
{
"char_start": 568,
"char_end": 570,
"chars": "->"
},
{
"char_start": 675,
"char_end": 677,
"chars": "->"
}
],
"added": [
{
"char_start": 146,
"char_end": 147,
"chars": "l"
},
{
"char_start": 149,
"char_end": 150,
"chars": ","
},
{
"char_start": 228,
"char_end": 376,
"chars": "memset(&sa, 0, sizeof(sa));\n\tlen = min_t(unsigned int, sizeof(sa), addr_len);\n\tmemcpy(&sa, addr, len);\n\n\tBT_DBG(\"sk %p %pMR\", sk, &sa.rc_bdaddr);\n\n\t"
},
{
"char_start": 568,
"char_end": 574,
"chars": "sa.rc_"
},
{
"char_start": 578,
"char_end": 581,
"chars": "nel"
},
{
"char_start": 584,
"char_end": 589,
"chars": "\n\t "
},
{
"char_start": 623,
"char_end": 629,
"chars": "sa.rc_"
},
{
"char_start": 633,
"char_end": 636,
"chars": "nel"
},
{
"char_start": 641,
"char_end": 642,
"chars": "."
},
{
"char_start": 747,
"char_end": 748,
"chars": "."
},
{
"char_start": 787,
"char_end": 793,
"chars": "sa.rc_"
},
{
"char_start": 797,
"char_end": 800,
"chars": "nel"
}
]
} | github.com/torvalds/linux/commit/951b6a0717db97ce420547222647bcc40bf1eacd | net/bluetooth/rfcomm/sock.c | cwe-476 |
AP4_HdlrAtom::AP4_HdlrAtom | AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)
{
AP4_UI32 predefined;
stream.ReadUI32(predefined);
stream.ReadUI32(m_HandlerType);
stream.ReadUI32(m_Reserved[0]);
stream.ReadUI32(m_Reserved[1]);
stream.ReadUI32(m_Reserved[2]);
// read the name unless it is empty
int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);
if (name_size == 0) return;
char* name = new char[name_size+1];
stream.Read(name, name_size);
name[name_size] = '\0'; // force a null termination
// handle a special case: the Quicktime files have a pascal
// string here, but ISO MP4 files have a C string.
// we try to detect a pascal encoding and correct it.
if (name[0] == name_size-1) {
m_HandlerName = name+1;
} else {
m_HandlerName = name;
}
delete[] name;
} | AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size,
AP4_UI08 version,
AP4_UI32 flags,
AP4_ByteStream& stream) :
AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags)
{
AP4_UI32 predefined;
stream.ReadUI32(predefined);
stream.ReadUI32(m_HandlerType);
stream.ReadUI32(m_Reserved[0]);
stream.ReadUI32(m_Reserved[1]);
stream.ReadUI32(m_Reserved[2]);
// read the name unless it is empty
if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;
AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);
char* name = new char[name_size+1];
if (name == NULL) return;
stream.Read(name, name_size);
name[name_size] = '\0'; // force a null termination
// handle a special case: the Quicktime files have a pascal
// string here, but ISO MP4 files have a C string.
// we try to detect a pascal encoding and correct it.
if (name[0] == name_size-1) {
m_HandlerName = name+1;
} else {
m_HandlerName = name;
}
delete[] name;
} | {
"deleted": [
{
"line_no": 15,
"char_start": 509,
"char_end": 566,
"line": " int name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n"
},
{
"line_no": 16,
"char_start": 566,
"char_end": 598,
"line": " if (name_size == 0) return;\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 509,
"char_end": 562,
"line": " if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return;\n"
},
{
"line_no": 16,
"char_start": 562,
"char_end": 624,
"line": " AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20);\n"
},
{
"line_no": 18,
"char_start": 664,
"char_end": 694,
"line": " if (name == NULL) return;\n"
}
]
} | {
"deleted": [
{
"char_start": 514,
"char_end": 516,
"chars": "nt"
},
{
"char_start": 517,
"char_end": 522,
"chars": "name_"
},
{
"char_start": 527,
"char_end": 528,
"chars": "="
},
{
"char_start": 529,
"char_end": 535,
"chars": "size-("
},
{
"char_start": 570,
"char_end": 572,
"chars": "if"
},
{
"char_start": 573,
"char_end": 574,
"chars": "("
},
{
"char_start": 585,
"char_end": 586,
"chars": "="
},
{
"char_start": 589,
"char_end": 596,
"chars": " return"
}
],
"added": [
{
"char_start": 514,
"char_end": 515,
"chars": "f"
},
{
"char_start": 516,
"char_end": 517,
"chars": "("
},
{
"char_start": 522,
"char_end": 523,
"chars": "<"
},
{
"char_start": 553,
"char_end": 560,
"chars": " return"
},
{
"char_start": 566,
"char_end": 574,
"chars": "AP4_UI32"
},
{
"char_start": 587,
"char_end": 620,
"chars": "size-(AP4_FULL_ATOM_HEADER_SIZE+2"
},
{
"char_start": 662,
"char_end": 692,
"chars": ";\n if (name == NULL) return"
}
]
} | github.com/axiomatic-systems/Bento4/commit/22192de5367fa0cee985917f092be4060b7c00b0 | Source/C++/Core/Ap4HdlrAtom.cpp | cwe-476 |
generatePreview | generatePreview (const char inFileName[],
float exposure,
int previewWidth,
int &previewHeight,
Array2D <PreviewRgba> &previewPixels)
{
//
// Read the input file
//
RgbaInputFile in (inFileName);
Box2i dw = in.dataWindow();
float a = in.pixelAspectRatio();
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
Array2D <Rgba> pixels (h, w);
in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);
in.readPixels (dw.min.y, dw.max.y);
//
// Make a preview image
//
previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);
previewPixels.resizeErase (previewHeight, previewWidth);
float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1;
float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1;
float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));
for (int y = 0; y < previewHeight; ++y)
{
for (int x = 0; x < previewWidth; ++x)
{
PreviewRgba &preview = previewPixels[y][x];
const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];
preview.r = gamma (pixel.r, m);
preview.g = gamma (pixel.g, m);
preview.b = gamma (pixel.b, m);
preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);
}
}
} | generatePreview (const char inFileName[],
float exposure,
int previewWidth,
int &previewHeight,
Array2D <PreviewRgba> &previewPixels)
{
//
// Read the input file
//
RgbaInputFile in (inFileName);
Box2i dw = in.dataWindow();
float a = in.pixelAspectRatio();
int w = dw.max.x - dw.min.x + 1;
int h = dw.max.y - dw.min.y + 1;
Array2D <Rgba> pixels (h, w);
in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w);
in.readPixels (dw.min.y, dw.max.y);
//
// Make a preview image
//
previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1);
previewPixels.resizeErase (previewHeight, previewWidth);
float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;
float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;
float m = Math<float>::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f));
for (int y = 0; y < previewHeight; ++y)
{
for (int x = 0; x < previewWidth; ++x)
{
PreviewRgba &preview = previewPixels[y][x];
const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)];
preview.r = gamma (pixel.r, m);
preview.g = gamma (pixel.g, m);
preview.b = gamma (pixel.b, m);
preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f);
}
}
} | {
"deleted": [
{
"line_no": 29,
"char_start": 689,
"char_end": 767,
"line": " float fx = (previewWidth > 0)? (float (w - 1) / (previewWidth - 1)): 1;\n"
},
{
"line_no": 30,
"char_start": 767,
"char_end": 845,
"line": " float fy = (previewHeight > 0)? (float (h - 1) / (previewHeight - 1)): 1;\n"
}
],
"added": [
{
"line_no": 29,
"char_start": 689,
"char_end": 767,
"line": " float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1;\n"
},
{
"line_no": 30,
"char_start": 767,
"char_end": 845,
"line": " float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1;\n"
}
]
} | {
"deleted": [
{
"char_start": 721,
"char_end": 722,
"chars": "0"
},
{
"char_start": 799,
"char_end": 800,
"chars": "0"
}
],
"added": [
{
"char_start": 721,
"char_end": 722,
"chars": "1"
},
{
"char_start": 799,
"char_end": 800,
"chars": "1"
}
]
} | github.com/AcademySoftwareFoundation/openexr/commit/74504503cff86e986bac441213c403b0ba28d58f | OpenEXR/exrmakepreview/makePreview.cpp | cwe-476 |
kvm_vm_ioctl_check_extension | int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
{
int r;
/* Assume we're using HV mode when the HV module is loaded */
int hv_enabled = kvmppc_hv_ops ? 1 : 0;
if (kvm) {
/*
* Hooray - we know which VM type we're running on. Depend on
* that rather than the guess above.
*/
hv_enabled = is_kvmppc_hv_enabled(kvm);
}
switch (ext) {
#ifdef CONFIG_BOOKE
case KVM_CAP_PPC_BOOKE_SREGS:
case KVM_CAP_PPC_BOOKE_WATCHDOG:
case KVM_CAP_PPC_EPR:
#else
case KVM_CAP_PPC_SEGSTATE:
case KVM_CAP_PPC_HIOR:
case KVM_CAP_PPC_PAPR:
#endif
case KVM_CAP_PPC_UNSET_IRQ:
case KVM_CAP_PPC_IRQ_LEVEL:
case KVM_CAP_ENABLE_CAP:
case KVM_CAP_ENABLE_CAP_VM:
case KVM_CAP_ONE_REG:
case KVM_CAP_IOEVENTFD:
case KVM_CAP_DEVICE_CTRL:
case KVM_CAP_IMMEDIATE_EXIT:
r = 1;
break;
case KVM_CAP_PPC_PAIRED_SINGLES:
case KVM_CAP_PPC_OSI:
case KVM_CAP_PPC_GET_PVINFO:
#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)
case KVM_CAP_SW_TLB:
#endif
/* We support this only for PR */
r = !hv_enabled;
break;
#ifdef CONFIG_KVM_MPIC
case KVM_CAP_IRQ_MPIC:
r = 1;
break;
#endif
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_SPAPR_TCE:
case KVM_CAP_SPAPR_TCE_64:
/* fallthrough */
case KVM_CAP_SPAPR_TCE_VFIO:
case KVM_CAP_PPC_RTAS:
case KVM_CAP_PPC_FIXUP_HCALL:
case KVM_CAP_PPC_ENABLE_HCALL:
#ifdef CONFIG_KVM_XICS
case KVM_CAP_IRQ_XICS:
#endif
r = 1;
break;
case KVM_CAP_PPC_ALLOC_HTAB:
r = hv_enabled;
break;
#endif /* CONFIG_PPC_BOOK3S_64 */
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_SMT:
r = 0;
if (kvm) {
if (kvm->arch.emul_smt_mode > 1)
r = kvm->arch.emul_smt_mode;
else
r = kvm->arch.smt_mode;
} else if (hv_enabled) {
if (cpu_has_feature(CPU_FTR_ARCH_300))
r = 1;
else
r = threads_per_subcore;
}
break;
case KVM_CAP_PPC_SMT_POSSIBLE:
r = 1;
if (hv_enabled) {
if (!cpu_has_feature(CPU_FTR_ARCH_300))
r = ((threads_per_subcore << 1) - 1);
else
/* P9 can emulate dbells, so allow any mode */
r = 8 | 4 | 2 | 1;
}
break;
case KVM_CAP_PPC_RMA:
r = 0;
break;
case KVM_CAP_PPC_HWRNG:
r = kvmppc_hwrng_present();
break;
case KVM_CAP_PPC_MMU_RADIX:
r = !!(hv_enabled && radix_enabled());
break;
case KVM_CAP_PPC_MMU_HASH_V3:
r = !!(hv_enabled && !radix_enabled() &&
cpu_has_feature(CPU_FTR_ARCH_300));
break;
#endif
case KVM_CAP_SYNC_MMU:
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
r = hv_enabled;
#elif defined(KVM_ARCH_WANT_MMU_NOTIFIER)
r = 1;
#else
r = 0;
#endif
break;
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_HTAB_FD:
r = hv_enabled;
break;
#endif
case KVM_CAP_NR_VCPUS:
/*
* Recommending a number of CPUs is somewhat arbitrary; we
* return the number of present CPUs for -HV (since a host
* will have secondary threads "offline"), and for other KVM
* implementations just count online CPUs.
*/
if (hv_enabled)
r = num_present_cpus();
else
r = num_online_cpus();
break;
case KVM_CAP_NR_MEMSLOTS:
r = KVM_USER_MEM_SLOTS;
break;
case KVM_CAP_MAX_VCPUS:
r = KVM_MAX_VCPUS;
break;
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_PPC_GET_SMMU_INFO:
r = 1;
break;
case KVM_CAP_SPAPR_MULTITCE:
r = 1;
break;
case KVM_CAP_SPAPR_RESIZE_HPT:
/* Disable this on POWER9 until code handles new HPTE format */
r = !!hv_enabled && !cpu_has_feature(CPU_FTR_ARCH_300);
break;
#endif
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_FWNMI:
r = hv_enabled;
break;
#endif
case KVM_CAP_PPC_HTM:
r = cpu_has_feature(CPU_FTR_TM_COMP) &&
is_kvmppc_hv_enabled(kvm);
break;
default:
r = 0;
break;
}
return r;
} | int kvm_vm_ioctl_check_extension(struct kvm *kvm, long ext)
{
int r;
/* Assume we're using HV mode when the HV module is loaded */
int hv_enabled = kvmppc_hv_ops ? 1 : 0;
if (kvm) {
/*
* Hooray - we know which VM type we're running on. Depend on
* that rather than the guess above.
*/
hv_enabled = is_kvmppc_hv_enabled(kvm);
}
switch (ext) {
#ifdef CONFIG_BOOKE
case KVM_CAP_PPC_BOOKE_SREGS:
case KVM_CAP_PPC_BOOKE_WATCHDOG:
case KVM_CAP_PPC_EPR:
#else
case KVM_CAP_PPC_SEGSTATE:
case KVM_CAP_PPC_HIOR:
case KVM_CAP_PPC_PAPR:
#endif
case KVM_CAP_PPC_UNSET_IRQ:
case KVM_CAP_PPC_IRQ_LEVEL:
case KVM_CAP_ENABLE_CAP:
case KVM_CAP_ENABLE_CAP_VM:
case KVM_CAP_ONE_REG:
case KVM_CAP_IOEVENTFD:
case KVM_CAP_DEVICE_CTRL:
case KVM_CAP_IMMEDIATE_EXIT:
r = 1;
break;
case KVM_CAP_PPC_PAIRED_SINGLES:
case KVM_CAP_PPC_OSI:
case KVM_CAP_PPC_GET_PVINFO:
#if defined(CONFIG_KVM_E500V2) || defined(CONFIG_KVM_E500MC)
case KVM_CAP_SW_TLB:
#endif
/* We support this only for PR */
r = !hv_enabled;
break;
#ifdef CONFIG_KVM_MPIC
case KVM_CAP_IRQ_MPIC:
r = 1;
break;
#endif
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_SPAPR_TCE:
case KVM_CAP_SPAPR_TCE_64:
/* fallthrough */
case KVM_CAP_SPAPR_TCE_VFIO:
case KVM_CAP_PPC_RTAS:
case KVM_CAP_PPC_FIXUP_HCALL:
case KVM_CAP_PPC_ENABLE_HCALL:
#ifdef CONFIG_KVM_XICS
case KVM_CAP_IRQ_XICS:
#endif
r = 1;
break;
case KVM_CAP_PPC_ALLOC_HTAB:
r = hv_enabled;
break;
#endif /* CONFIG_PPC_BOOK3S_64 */
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_SMT:
r = 0;
if (kvm) {
if (kvm->arch.emul_smt_mode > 1)
r = kvm->arch.emul_smt_mode;
else
r = kvm->arch.smt_mode;
} else if (hv_enabled) {
if (cpu_has_feature(CPU_FTR_ARCH_300))
r = 1;
else
r = threads_per_subcore;
}
break;
case KVM_CAP_PPC_SMT_POSSIBLE:
r = 1;
if (hv_enabled) {
if (!cpu_has_feature(CPU_FTR_ARCH_300))
r = ((threads_per_subcore << 1) - 1);
else
/* P9 can emulate dbells, so allow any mode */
r = 8 | 4 | 2 | 1;
}
break;
case KVM_CAP_PPC_RMA:
r = 0;
break;
case KVM_CAP_PPC_HWRNG:
r = kvmppc_hwrng_present();
break;
case KVM_CAP_PPC_MMU_RADIX:
r = !!(hv_enabled && radix_enabled());
break;
case KVM_CAP_PPC_MMU_HASH_V3:
r = !!(hv_enabled && !radix_enabled() &&
cpu_has_feature(CPU_FTR_ARCH_300));
break;
#endif
case KVM_CAP_SYNC_MMU:
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
r = hv_enabled;
#elif defined(KVM_ARCH_WANT_MMU_NOTIFIER)
r = 1;
#else
r = 0;
#endif
break;
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_HTAB_FD:
r = hv_enabled;
break;
#endif
case KVM_CAP_NR_VCPUS:
/*
* Recommending a number of CPUs is somewhat arbitrary; we
* return the number of present CPUs for -HV (since a host
* will have secondary threads "offline"), and for other KVM
* implementations just count online CPUs.
*/
if (hv_enabled)
r = num_present_cpus();
else
r = num_online_cpus();
break;
case KVM_CAP_NR_MEMSLOTS:
r = KVM_USER_MEM_SLOTS;
break;
case KVM_CAP_MAX_VCPUS:
r = KVM_MAX_VCPUS;
break;
#ifdef CONFIG_PPC_BOOK3S_64
case KVM_CAP_PPC_GET_SMMU_INFO:
r = 1;
break;
case KVM_CAP_SPAPR_MULTITCE:
r = 1;
break;
case KVM_CAP_SPAPR_RESIZE_HPT:
/* Disable this on POWER9 until code handles new HPTE format */
r = !!hv_enabled && !cpu_has_feature(CPU_FTR_ARCH_300);
break;
#endif
#ifdef CONFIG_KVM_BOOK3S_HV_POSSIBLE
case KVM_CAP_PPC_FWNMI:
r = hv_enabled;
break;
#endif
case KVM_CAP_PPC_HTM:
r = cpu_has_feature(CPU_FTR_TM_COMP) && hv_enabled;
break;
default:
r = 0;
break;
}
return r;
} | {
"deleted": [
{
"line_no": 157,
"char_start": 3515,
"char_end": 3557,
"line": "\t\tr = cpu_has_feature(CPU_FTR_TM_COMP) &&\n"
},
{
"line_no": 158,
"char_start": 3557,
"char_end": 3590,
"line": "\t\t is_kvmppc_hv_enabled(kvm);\n"
}
],
"added": [
{
"line_no": 157,
"char_start": 3515,
"char_end": 3569,
"line": "\t\tr = cpu_has_feature(CPU_FTR_TM_COMP) && hv_enabled;\n"
}
]
} | {
"deleted": [
{
"char_start": 3556,
"char_end": 3559,
"chars": "\n\t\t"
},
{
"char_start": 3560,
"char_end": 3573,
"chars": " is_kvmppc_"
},
{
"char_start": 3583,
"char_end": 3588,
"chars": "(kvm)"
}
],
"added": []
} | github.com/torvalds/linux/commit/ac64115a66c18c01745bbd3c47a36b124e5fd8c0 | arch/powerpc/kvm/powerpc.c | cwe-476 |
handle_client_startup | static bool handle_client_startup(PgSocket *client, PktHdr *pkt)
{
const char *passwd;
const uint8_t *key;
bool ok;
SBuf *sbuf = &client->sbuf;
/* don't tolerate partial packets */
if (incomplete_pkt(pkt)) {
disconnect_client(client, true, "client sent partial pkt in startup phase");
return false;
}
if (client->wait_for_welcome) {
if (finish_client_login(client)) {
/* the packet was already parsed */
sbuf_prepare_skip(sbuf, pkt->len);
return true;
} else
return false;
}
switch (pkt->type) {
case PKT_SSLREQ:
slog_noise(client, "C: req SSL");
slog_noise(client, "P: nak");
/* reject SSL attempt */
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak SSL");
return false;
}
break;
case PKT_STARTUP_V2:
disconnect_client(client, true, "Old V2 protocol not supported");
return false;
case PKT_STARTUP:
if (client->pool) {
disconnect_client(client, true, "client re-sent startup pkt");
return false;
}
if (!decide_startup_pool(client, pkt))
return false;
if (client->pool->db->admin) {
if (!admin_pre_login(client))
return false;
}
if (cf_auth_type <= AUTH_TRUST || client->own_user) {
if (!finish_client_login(client))
return false;
} else {
if (!send_client_authreq(client)) {
disconnect_client(client, false, "failed to send auth req");
return false;
}
}
break;
case 'p': /* PasswordMessage */
/* haven't requested it */
if (cf_auth_type <= AUTH_TRUST) {
disconnect_client(client, true, "unrequested passwd pkt");
return false;
}
ok = mbuf_get_string(&pkt->data, &passwd);
if (ok && check_client_passwd(client, passwd)) {
if (!finish_client_login(client))
return false;
} else {
disconnect_client(client, true, "Auth failed");
return false;
}
break;
case PKT_CANCEL:
if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN
&& mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key))
{
memcpy(client->cancel_key, key, BACKENDKEY_LEN);
accept_cancel_request(client);
} else
disconnect_client(client, false, "bad cancel request");
return false;
default:
disconnect_client(client, false, "bad packet");
return false;
}
sbuf_prepare_skip(sbuf, pkt->len);
client->request_time = get_cached_time();
return true;
} | static bool handle_client_startup(PgSocket *client, PktHdr *pkt)
{
const char *passwd;
const uint8_t *key;
bool ok;
SBuf *sbuf = &client->sbuf;
/* don't tolerate partial packets */
if (incomplete_pkt(pkt)) {
disconnect_client(client, true, "client sent partial pkt in startup phase");
return false;
}
if (client->wait_for_welcome) {
if (finish_client_login(client)) {
/* the packet was already parsed */
sbuf_prepare_skip(sbuf, pkt->len);
return true;
} else
return false;
}
switch (pkt->type) {
case PKT_SSLREQ:
slog_noise(client, "C: req SSL");
slog_noise(client, "P: nak");
/* reject SSL attempt */
if (!sbuf_answer(&client->sbuf, "N", 1)) {
disconnect_client(client, false, "failed to nak SSL");
return false;
}
break;
case PKT_STARTUP_V2:
disconnect_client(client, true, "Old V2 protocol not supported");
return false;
case PKT_STARTUP:
if (client->pool) {
disconnect_client(client, true, "client re-sent startup pkt");
return false;
}
if (!decide_startup_pool(client, pkt))
return false;
if (client->pool->db->admin) {
if (!admin_pre_login(client))
return false;
}
if (cf_auth_type <= AUTH_TRUST || client->own_user) {
if (!finish_client_login(client))
return false;
} else {
if (!send_client_authreq(client)) {
disconnect_client(client, false, "failed to send auth req");
return false;
}
}
break;
case 'p': /* PasswordMessage */
/* too early */
if (!client->auth_user) {
disconnect_client(client, true, "client password pkt before startup packet");
return false;
}
/* haven't requested it */
if (cf_auth_type <= AUTH_TRUST) {
disconnect_client(client, true, "unrequested passwd pkt");
return false;
}
ok = mbuf_get_string(&pkt->data, &passwd);
if (ok && check_client_passwd(client, passwd)) {
if (!finish_client_login(client))
return false;
} else {
disconnect_client(client, true, "Auth failed");
return false;
}
break;
case PKT_CANCEL:
if (mbuf_avail_for_read(&pkt->data) == BACKENDKEY_LEN
&& mbuf_get_bytes(&pkt->data, BACKENDKEY_LEN, &key))
{
memcpy(client->cancel_key, key, BACKENDKEY_LEN);
accept_cancel_request(client);
} else
disconnect_client(client, false, "bad cancel request");
return false;
default:
disconnect_client(client, false, "bad packet");
return false;
}
sbuf_prepare_skip(sbuf, pkt->len);
client->request_time = get_cached_time();
return true;
} | {
"deleted": [],
"added": [
{
"line_no": 63,
"char_start": 1457,
"char_end": 1475,
"line": "\t\t/* too early */\n"
},
{
"line_no": 64,
"char_start": 1475,
"char_end": 1503,
"line": "\t\tif (!client->auth_user) {\n"
},
{
"line_no": 65,
"char_start": 1503,
"char_end": 1584,
"line": "\t\t\tdisconnect_client(client, true, \"client password pkt before startup packet\");\n"
},
{
"line_no": 66,
"char_start": 1584,
"char_end": 1601,
"line": "\t\t\treturn false;\n"
},
{
"line_no": 67,
"char_start": 1601,
"char_end": 1605,
"line": "\t\t}\n"
},
{
"line_no": 68,
"char_start": 1605,
"char_end": 1606,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1462,
"char_end": 1611,
"chars": "too early */\n\t\tif (!client->auth_user) {\n\t\t\tdisconnect_client(client, true, \"client password pkt before startup packet\");\n\t\t\treturn false;\n\t\t}\n\n\t\t/* "
}
]
} | github.com/pgbouncer/pgbouncer/commit/74d6e5f7de5ec736f71204b7b422af7380c19ac5 | src/client.c | cwe-476 |
mrb_class_real | mrb_class_real(struct RClass* cl)
{
if (cl == 0)
return NULL;
while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {
cl = cl->super;
}
return cl;
} | mrb_class_real(struct RClass* cl)
{
if (cl == 0) return NULL;
while ((cl->tt == MRB_TT_SCLASS) || (cl->tt == MRB_TT_ICLASS)) {
cl = cl->super;
if (cl == 0) return NULL;
}
return cl;
} | {
"deleted": [
{
"line_no": 3,
"char_start": 36,
"char_end": 51,
"line": " if (cl == 0)\n"
},
{
"line_no": 4,
"char_start": 51,
"char_end": 68,
"line": " return NULL;\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 36,
"char_end": 64,
"line": " if (cl == 0) return NULL;\n"
},
{
"line_no": 6,
"char_start": 151,
"char_end": 181,
"line": " if (cl == 0) return NULL;\n"
}
]
} | {
"deleted": [
{
"char_start": 50,
"char_end": 54,
"chars": "\n "
}
],
"added": [
{
"char_start": 149,
"char_end": 179,
"chars": ";\n if (cl == 0) return NULL"
}
]
} | github.com/mruby/mruby/commit/faa4eaf6803bd11669bc324b4c34e7162286bfa3 | src/class.c | cwe-476 |
nsv_read_chunk | static int nsv_read_chunk(AVFormatContext *s, int fill_header)
{
NSVContext *nsv = s->priv_data;
AVIOContext *pb = s->pb;
AVStream *st[2] = {NULL, NULL};
NSVStream *nst;
AVPacket *pkt;
int i, err = 0;
uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */
uint32_t vsize;
uint16_t asize;
uint16_t auxsize;
if (nsv->ahead[0].data || nsv->ahead[1].data)
return 0; //-1; /* hey! eat what you've in your plate first! */
null_chunk_retry:
if (pb->eof_reached)
return -1;
for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
err = nsv_resync(s);
if (err < 0)
return err;
if (nsv->state == NSV_FOUND_NSVS)
err = nsv_parse_NSVs_header(s);
if (err < 0)
return err;
if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
return -1;
auxcount = avio_r8(pb);
vsize = avio_rl16(pb);
asize = avio_rl16(pb);
vsize = (vsize << 4) | (auxcount >> 4);
auxcount &= 0x0f;
av_log(s, AV_LOG_TRACE, "NSV CHUNK %"PRIu8" aux, %"PRIu32" bytes video, %"PRIu16" bytes audio\n",
auxcount, vsize, asize);
/* skip aux stuff */
for (i = 0; i < auxcount; i++) {
uint32_t av_unused auxtag;
auxsize = avio_rl16(pb);
auxtag = avio_rl32(pb);
avio_skip(pb, auxsize);
vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */
}
if (pb->eof_reached)
return -1;
if (!vsize && !asize) {
nsv->state = NSV_UNSYNC;
goto null_chunk_retry;
}
/* map back streams to v,a */
if (s->nb_streams > 0)
st[s->streams[0]->id] = s->streams[0];
if (s->nb_streams > 1)
st[s->streams[1]->id] = s->streams[1];
if (vsize && st[NSV_ST_VIDEO]) {
nst = st[NSV_ST_VIDEO]->priv_data;
pkt = &nsv->ahead[NSV_ST_VIDEO];
av_get_packet(pb, pkt, vsize);
pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
pkt->dts = nst->frame_offset;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
for (i = 0; i < FFMIN(8, vsize); i++)
av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02"PRIx8"\n",
i, pkt->data[i]);
}
if(st[NSV_ST_VIDEO])
((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
if (asize && st[NSV_ST_AUDIO]) {
nst = st[NSV_ST_AUDIO]->priv_data;
pkt = &nsv->ahead[NSV_ST_AUDIO];
/* read raw audio specific header on the first audio chunk... */
/* on ALL audio chunks ?? seems so! */
if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {
uint8_t bps;
uint8_t channels;
uint16_t samplerate;
bps = avio_r8(pb);
channels = avio_r8(pb);
samplerate = avio_rl16(pb);
if (!channels || !samplerate)
return AVERROR_INVALIDDATA;
asize-=4;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
if (fill_header) {
st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
if (bps != 16) {
av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%"PRIu8")!!!\n", bps);
}
bps /= channels; // ???
if (bps == 8)
st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
samplerate /= 4;/* UGH ??? XXX */
channels = 1;
st[NSV_ST_AUDIO]->codecpar->channels = channels;
st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
}
}
av_get_packet(pb, pkt, asize);
pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {
/* on a nsvs frame we have new information on a/v sync */
pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
pkt->dts *= (int64_t)1000 * nsv->framerate.den;
pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%"PRId16", dts:%"PRId64,
nsv->avsync, pkt->dts);
}
nst->frame_offset++;
}
nsv->state = NSV_UNSYNC;
return 0;
} | static int nsv_read_chunk(AVFormatContext *s, int fill_header)
{
NSVContext *nsv = s->priv_data;
AVIOContext *pb = s->pb;
AVStream *st[2] = {NULL, NULL};
NSVStream *nst;
AVPacket *pkt;
int i, err = 0;
uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */
uint32_t vsize;
uint16_t asize;
uint16_t auxsize;
int ret;
if (nsv->ahead[0].data || nsv->ahead[1].data)
return 0; //-1; /* hey! eat what you've in your plate first! */
null_chunk_retry:
if (pb->eof_reached)
return -1;
for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++)
err = nsv_resync(s);
if (err < 0)
return err;
if (nsv->state == NSV_FOUND_NSVS)
err = nsv_parse_NSVs_header(s);
if (err < 0)
return err;
if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF)
return -1;
auxcount = avio_r8(pb);
vsize = avio_rl16(pb);
asize = avio_rl16(pb);
vsize = (vsize << 4) | (auxcount >> 4);
auxcount &= 0x0f;
av_log(s, AV_LOG_TRACE, "NSV CHUNK %"PRIu8" aux, %"PRIu32" bytes video, %"PRIu16" bytes audio\n",
auxcount, vsize, asize);
/* skip aux stuff */
for (i = 0; i < auxcount; i++) {
uint32_t av_unused auxtag;
auxsize = avio_rl16(pb);
auxtag = avio_rl32(pb);
avio_skip(pb, auxsize);
vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */
}
if (pb->eof_reached)
return -1;
if (!vsize && !asize) {
nsv->state = NSV_UNSYNC;
goto null_chunk_retry;
}
/* map back streams to v,a */
if (s->nb_streams > 0)
st[s->streams[0]->id] = s->streams[0];
if (s->nb_streams > 1)
st[s->streams[1]->id] = s->streams[1];
if (vsize && st[NSV_ST_VIDEO]) {
nst = st[NSV_ST_VIDEO]->priv_data;
pkt = &nsv->ahead[NSV_ST_VIDEO];
if ((ret = av_get_packet(pb, pkt, vsize)) < 0)
return ret;
pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO;
pkt->dts = nst->frame_offset;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
for (i = 0; i < FFMIN(8, vsize); i++)
av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02"PRIx8"\n",
i, pkt->data[i]);
}
if(st[NSV_ST_VIDEO])
((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++;
if (asize && st[NSV_ST_AUDIO]) {
nst = st[NSV_ST_AUDIO]->priv_data;
pkt = &nsv->ahead[NSV_ST_AUDIO];
/* read raw audio specific header on the first audio chunk... */
/* on ALL audio chunks ?? seems so! */
if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) {
uint8_t bps;
uint8_t channels;
uint16_t samplerate;
bps = avio_r8(pb);
channels = avio_r8(pb);
samplerate = avio_rl16(pb);
if (!channels || !samplerate)
return AVERROR_INVALIDDATA;
asize-=4;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
if (fill_header) {
st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */
if (bps != 16) {
av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%"PRIu8")!!!\n", bps);
}
bps /= channels; // ???
if (bps == 8)
st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8;
samplerate /= 4;/* UGH ??? XXX */
channels = 1;
st[NSV_ST_AUDIO]->codecpar->channels = channels;
st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate;
av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %"PRIu8", nchan %"PRIu8", srate %"PRIu16"\n",
bps, channels, samplerate);
}
}
if ((ret = av_get_packet(pb, pkt, asize)) < 0)
return ret;
pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO;
pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */
if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) {
/* on a nsvs frame we have new information on a/v sync */
pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1);
pkt->dts *= (int64_t)1000 * nsv->framerate.den;
pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num;
av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%"PRId16", dts:%"PRId64,
nsv->avsync, pkt->dts);
}
nst->frame_offset++;
}
nsv->state = NSV_UNSYNC;
return 0;
} | {
"deleted": [
{
"line_no": 64,
"char_start": 1938,
"char_end": 1977,
"line": " av_get_packet(pb, pkt, vsize);\n"
},
{
"line_no": 108,
"char_start": 4074,
"char_end": 4113,
"line": " av_get_packet(pb, pkt, asize);\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 360,
"char_end": 373,
"line": " int ret;\n"
},
{
"line_no": 65,
"char_start": 1951,
"char_end": 2006,
"line": " if ((ret = av_get_packet(pb, pkt, vsize)) < 0)\n"
},
{
"line_no": 66,
"char_start": 2006,
"char_end": 2030,
"line": " return ret;\n"
},
{
"line_no": 110,
"char_start": 4127,
"char_end": 4182,
"line": " if ((ret = av_get_packet(pb, pkt, asize)) < 0)\n"
},
{
"line_no": 111,
"char_start": 4182,
"char_end": 4206,
"line": " return ret;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 360,
"char_end": 373,
"chars": " int ret;\n"
},
{
"char_start": 1959,
"char_end": 1970,
"chars": "if ((ret = "
},
{
"char_start": 1999,
"char_end": 2028,
"chars": ") < 0)\n return ret"
},
{
"char_start": 4135,
"char_end": 4146,
"chars": "if ((ret = "
},
{
"char_start": 4175,
"char_end": 4204,
"chars": ") < 0)\n return ret"
}
]
} | github.com/libav/libav/commit/fe6eea99efac66839052af547426518efd970b24 | libavformat/nsvdec.c | cwe-476 |
_kdc_as_rep | _kdc_as_rep(kdc_request_t r,
krb5_data *reply,
const char *from,
struct sockaddr *from_addr,
int datagram_reply)
{
krb5_context context = r->context;
krb5_kdc_configuration *config = r->config;
KDC_REQ *req = &r->req;
KDC_REQ_BODY *b = NULL;
AS_REP rep;
KDCOptions f;
krb5_enctype setype;
krb5_error_code ret = 0;
Key *skey;
int found_pa = 0;
int i, flags = HDB_F_FOR_AS_REQ;
METHOD_DATA error_method;
const PA_DATA *pa;
memset(&rep, 0, sizeof(rep));
error_method.len = 0;
error_method.val = NULL;
/*
* Look for FAST armor and unwrap
*/
ret = _kdc_fast_unwrap_request(r);
if (ret) {
_kdc_r_log(r, 0, "FAST unwrap request from %s failed: %d", from, ret);
goto out;
}
b = &req->req_body;
f = b->kdc_options;
if (f.canonicalize)
flags |= HDB_F_CANON;
if(b->sname == NULL){
ret = KRB5KRB_ERR_GENERIC;
_kdc_set_e_text(r, "No server in request");
} else{
ret = _krb5_principalname2krb5_principal (context,
&r->server_princ,
*(b->sname),
b->realm);
if (ret == 0)
ret = krb5_unparse_name(context, r->server_princ, &r->server_name);
}
if (ret) {
kdc_log(context, config, 0,
"AS-REQ malformed server name from %s", from);
goto out;
}
if(b->cname == NULL){
ret = KRB5KRB_ERR_GENERIC;
_kdc_set_e_text(r, "No client in request");
} else {
ret = _krb5_principalname2krb5_principal (context,
&r->client_princ,
*(b->cname),
b->realm);
if (ret)
goto out;
ret = krb5_unparse_name(context, r->client_princ, &r->client_name);
}
if (ret) {
kdc_log(context, config, 0,
"AS-REQ malformed client name from %s", from);
goto out;
}
kdc_log(context, config, 0, "AS-REQ %s from %s for %s",
r->client_name, from, r->server_name);
/*
*
*/
if (_kdc_is_anonymous(context, r->client_princ)) {
if (!_kdc_is_anon_request(b)) {
kdc_log(context, config, 0, "Anonymous ticket w/o anonymous flag");
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
goto out;
}
} else if (_kdc_is_anon_request(b)) {
kdc_log(context, config, 0,
"Request for a anonymous ticket with non "
"anonymous client name: %s", r->client_name);
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
goto out;
}
/*
*
*/
ret = _kdc_db_fetch(context, config, r->client_princ,
HDB_F_GET_CLIENT | flags, NULL,
&r->clientdb, &r->client);
if(ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "client %s does not have secrets at this KDC, need to proxy",
r->client_name);
goto out;
} else if (ret == HDB_ERR_WRONG_REALM) {
char *fixed_client_name = NULL;
ret = krb5_unparse_name(context, r->client->entry.principal,
&fixed_client_name);
if (ret) {
goto out;
}
kdc_log(context, config, 0, "WRONG_REALM - %s -> %s",
r->client_name, fixed_client_name);
free(fixed_client_name);
ret = _kdc_fast_mk_error(context, r,
&error_method,
r->armor_crypto,
&req->req_body,
KRB5_KDC_ERR_WRONG_REALM,
NULL,
r->server_princ,
NULL,
&r->client->entry.principal->realm,
NULL, NULL,
reply);
goto out;
} else if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "UNKNOWN -- %s: %s", r->client_name, msg);
krb5_free_error_message(context, msg);
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
goto out;
}
ret = _kdc_db_fetch(context, config, r->server_princ,
HDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags,
NULL, NULL, &r->server);
if(ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy",
r->server_name);
goto out;
} else if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "UNKNOWN -- %s: %s", r->server_name, msg);
krb5_free_error_message(context, msg);
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
goto out;
}
/*
* Select a session enctype from the list of the crypto system
* supported enctypes that is supported by the client and is one of
* the enctype of the enctype of the service (likely krbtgt).
*
* The latter is used as a hint of what enctypes all KDC support,
* to make sure a newer version of KDC won't generate a session
* enctype that an older version of a KDC in the same realm can't
* decrypt.
*/
ret = _kdc_find_etype(context,
krb5_principal_is_krbtgt(context, r->server_princ) ?
config->tgt_use_strongest_session_key :
config->svc_use_strongest_session_key, FALSE,
r->client, b->etype.val, b->etype.len, &r->sessionetype,
NULL);
if (ret) {
kdc_log(context, config, 0,
"Client (%s) from %s has no common enctypes with KDC "
"to use for the session key",
r->client_name, from);
goto out;
}
/*
* Pre-auth processing
*/
if(req->padata){
unsigned int n;
log_patypes(context, config, req->padata);
/* Check if preauth matching */
for (n = 0; !found_pa && n < sizeof(pat) / sizeof(pat[0]); n++) {
if (pat[n].validate == NULL)
continue;
if (r->armor_crypto == NULL && (pat[n].flags & PA_REQ_FAST))
continue;
kdc_log(context, config, 5,
"Looking for %s pa-data -- %s", pat[n].name, r->client_name);
i = 0;
pa = _kdc_find_padata(req, &i, pat[n].type);
if (pa) {
ret = pat[n].validate(r, pa);
if (ret != 0) {
goto out;
}
kdc_log(context, config, 0,
"%s pre-authentication succeeded -- %s",
pat[n].name, r->client_name);
found_pa = 1;
r->et.flags.pre_authent = 1;
}
}
}
if (found_pa == 0) {
Key *ckey = NULL;
size_t n;
for (n = 0; n < sizeof(pat) / sizeof(pat[0]); n++) {
if ((pat[n].flags & PA_ANNOUNCE) == 0)
continue;
ret = krb5_padata_add(context, &error_method,
pat[n].type, NULL, 0);
if (ret)
goto out;
}
/*
* If there is a client key, send ETYPE_INFO{,2}
*/
ret = _kdc_find_etype(context,
config->preauth_use_strongest_session_key, TRUE,
r->client, b->etype.val, b->etype.len, NULL, &ckey);
if (ret == 0) {
/*
* RFC4120 requires:
* - If the client only knows about old enctypes, then send
* both info replies (we send 'info' first in the list).
* - If the client is 'modern', because it knows about 'new'
* enctype types, then only send the 'info2' reply.
*
* Before we send the full list of etype-info data, we pick
* the client key we would have used anyway below, just pick
* that instead.
*/
if (older_enctype(ckey->key.keytype)) {
ret = get_pa_etype_info(context, config,
&error_method, ckey);
if (ret)
goto out;
}
ret = get_pa_etype_info2(context, config,
&error_method, ckey);
if (ret)
goto out;
}
/*
* send requre preauth is its required or anon is requested,
* anon is today only allowed via preauth mechanisms.
*/
if (require_preauth_p(r) || _kdc_is_anon_request(b)) {
ret = KRB5KDC_ERR_PREAUTH_REQUIRED;
_kdc_set_e_text(r, "Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ");
goto out;
}
if (ckey == NULL) {
ret = KRB5KDC_ERR_CLIENT_NOTYET;
_kdc_set_e_text(r, "Doesn't have a client key available");
goto out;
}
krb5_free_keyblock_contents(r->context, &r->reply_key);
ret = krb5_copy_keyblock_contents(r->context, &ckey->key, &r->reply_key);
if (ret)
goto out;
}
if (r->clientdb->hdb_auth_status) {
r->clientdb->hdb_auth_status(context, r->clientdb, r->client,
HDB_AUTH_SUCCESS);
}
/*
* Verify flags after the user been required to prove its identity
* with in a preauth mech.
*/
ret = _kdc_check_access(context, config, r->client, r->client_name,
r->server, r->server_name,
req, &error_method);
if(ret)
goto out;
/*
* Select the best encryption type for the KDC with out regard to
* the client since the client never needs to read that data.
*/
ret = _kdc_get_preferred_key(context, config,
r->server, r->server_name,
&setype, &skey);
if(ret)
goto out;
if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey
|| (_kdc_is_anon_request(b) && !config->allow_anonymous)) {
ret = KRB5KDC_ERR_BADOPTION;
_kdc_set_e_text(r, "Bad KDC options");
goto out;
}
/*
* Build reply
*/
rep.pvno = 5;
rep.msg_type = krb_as_rep;
if (_kdc_is_anonymous(context, r->client_princ)) {
Realm anon_realm=KRB5_ANON_REALM;
ret = copy_Realm(&anon_realm, &rep.crealm);
} else
ret = copy_Realm(&r->client->entry.principal->realm, &rep.crealm);
if (ret)
goto out;
ret = _krb5_principal2principalname(&rep.cname, r->client->entry.principal);
if (ret)
goto out;
rep.ticket.tkt_vno = 5;
ret = copy_Realm(&r->server->entry.principal->realm, &rep.ticket.realm);
if (ret)
goto out;
_krb5_principal2principalname(&rep.ticket.sname,
r->server->entry.principal);
/* java 1.6 expects the name to be the same type, lets allow that
* uncomplicated name-types. */
#define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t)
if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST))
rep.ticket.sname.name_type = b->sname->name_type;
#undef CNT
r->et.flags.initial = 1;
if(r->client->entry.flags.forwardable && r->server->entry.flags.forwardable)
r->et.flags.forwardable = f.forwardable;
else if (f.forwardable) {
_kdc_set_e_text(r, "Ticket may not be forwardable");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
if(r->client->entry.flags.proxiable && r->server->entry.flags.proxiable)
r->et.flags.proxiable = f.proxiable;
else if (f.proxiable) {
_kdc_set_e_text(r, "Ticket may not be proxiable");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
if(r->client->entry.flags.postdate && r->server->entry.flags.postdate)
r->et.flags.may_postdate = f.allow_postdate;
else if (f.allow_postdate){
_kdc_set_e_text(r, "Ticket may not be postdate");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
/* check for valid set of addresses */
if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {
_kdc_set_e_text(r, "Bad address list in requested");
ret = KRB5KRB_AP_ERR_BADADDR;
goto out;
}
ret = copy_PrincipalName(&rep.cname, &r->et.cname);
if (ret)
goto out;
ret = copy_Realm(&rep.crealm, &r->et.crealm);
if (ret)
goto out;
{
time_t start;
time_t t;
start = r->et.authtime = kdc_time;
if(f.postdated && req->req_body.from){
ALLOC(r->et.starttime);
start = *r->et.starttime = *req->req_body.from;
r->et.flags.invalid = 1;
r->et.flags.postdated = 1; /* XXX ??? */
}
_kdc_fix_time(&b->till);
t = *b->till;
/* be careful not overflowing */
if(r->client->entry.max_life)
t = start + min(t - start, *r->client->entry.max_life);
if(r->server->entry.max_life)
t = start + min(t - start, *r->server->entry.max_life);
#if 0
t = min(t, start + realm->max_life);
#endif
r->et.endtime = t;
if(f.renewable_ok && r->et.endtime < *b->till){
f.renewable = 1;
if(b->rtime == NULL){
ALLOC(b->rtime);
*b->rtime = 0;
}
if(*b->rtime < *b->till)
*b->rtime = *b->till;
}
if(f.renewable && b->rtime){
t = *b->rtime;
if(t == 0)
t = MAX_TIME;
if(r->client->entry.max_renew)
t = start + min(t - start, *r->client->entry.max_renew);
if(r->server->entry.max_renew)
t = start + min(t - start, *r->server->entry.max_renew);
#if 0
t = min(t, start + realm->max_renew);
#endif
ALLOC(r->et.renew_till);
*r->et.renew_till = t;
r->et.flags.renewable = 1;
}
}
if (_kdc_is_anon_request(b))
r->et.flags.anonymous = 1;
if(b->addresses){
ALLOC(r->et.caddr);
copy_HostAddresses(b->addresses, r->et.caddr);
}
r->et.transited.tr_type = DOMAIN_X500_COMPRESS;
krb5_data_zero(&r->et.transited.contents);
/* The MIT ASN.1 library (obviously) doesn't tell lengths encoded
* as 0 and as 0x80 (meaning indefinite length) apart, and is thus
* incapable of correctly decoding SEQUENCE OF's of zero length.
*
* To fix this, always send at least one no-op last_req
*
* If there's a pw_end or valid_end we will use that,
* otherwise just a dummy lr.
*/
r->ek.last_req.val = malloc(2 * sizeof(*r->ek.last_req.val));
if (r->ek.last_req.val == NULL) {
ret = ENOMEM;
goto out;
}
r->ek.last_req.len = 0;
if (r->client->entry.pw_end
&& (config->kdc_warn_pwexpire == 0
|| kdc_time + config->kdc_warn_pwexpire >= *r->client->entry.pw_end)) {
r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_PW_EXPTIME;
r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.pw_end;
++r->ek.last_req.len;
}
if (r->client->entry.valid_end) {
r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_ACCT_EXPTIME;
r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.valid_end;
++r->ek.last_req.len;
}
if (r->ek.last_req.len == 0) {
r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_NONE;
r->ek.last_req.val[r->ek.last_req.len].lr_value = 0;
++r->ek.last_req.len;
}
r->ek.nonce = b->nonce;
if (r->client->entry.valid_end || r->client->entry.pw_end) {
ALLOC(r->ek.key_expiration);
if (r->client->entry.valid_end) {
if (r->client->entry.pw_end)
*r->ek.key_expiration = min(*r->client->entry.valid_end,
*r->client->entry.pw_end);
else
*r->ek.key_expiration = *r->client->entry.valid_end;
} else
*r->ek.key_expiration = *r->client->entry.pw_end;
} else
r->ek.key_expiration = NULL;
r->ek.flags = r->et.flags;
r->ek.authtime = r->et.authtime;
if (r->et.starttime) {
ALLOC(r->ek.starttime);
*r->ek.starttime = *r->et.starttime;
}
r->ek.endtime = r->et.endtime;
if (r->et.renew_till) {
ALLOC(r->ek.renew_till);
*r->ek.renew_till = *r->et.renew_till;
}
ret = copy_Realm(&rep.ticket.realm, &r->ek.srealm);
if (ret)
goto out;
ret = copy_PrincipalName(&rep.ticket.sname, &r->ek.sname);
if (ret)
goto out;
if(r->et.caddr){
ALLOC(r->ek.caddr);
copy_HostAddresses(r->et.caddr, r->ek.caddr);
}
/*
* Check and session and reply keys
*/
if (r->session_key.keytype == ETYPE_NULL) {
ret = krb5_generate_random_keyblock(context, r->sessionetype, &r->session_key);
if (ret)
goto out;
}
if (r->reply_key.keytype == ETYPE_NULL) {
_kdc_set_e_text(r, "Client have no reply key");
ret = KRB5KDC_ERR_CLIENT_NOTYET;
goto out;
}
ret = copy_EncryptionKey(&r->session_key, &r->et.key);
if (ret)
goto out;
ret = copy_EncryptionKey(&r->session_key, &r->ek.key);
if (ret)
goto out;
if (r->outpadata.len) {
ALLOC(rep.padata);
if (rep.padata == NULL) {
ret = ENOMEM;
goto out;
}
ret = copy_METHOD_DATA(&r->outpadata, rep.padata);
if (ret)
goto out;
}
/* Add the PAC */
if (send_pac_p(context, req)) {
generate_pac(r, skey);
}
_kdc_log_timestamp(context, config, "AS-REQ", r->et.authtime, r->et.starttime,
r->et.endtime, r->et.renew_till);
/* do this as the last thing since this signs the EncTicketPart */
ret = _kdc_add_KRB5SignedPath(context,
config,
r->server,
setype,
r->client->entry.principal,
NULL,
NULL,
&r->et);
if (ret)
goto out;
log_as_req(context, config, r->reply_key.keytype, setype, b);
/*
* We always say we support FAST/enc-pa-rep
*/
r->et.flags.enc_pa_rep = r->ek.flags.enc_pa_rep = 1;
/*
* Add REQ_ENC_PA_REP if client supports it
*/
i = 0;
pa = _kdc_find_padata(req, &i, KRB5_PADATA_REQ_ENC_PA_REP);
if (pa) {
ret = add_enc_pa_rep(r);
if (ret) {
const char *msg = krb5_get_error_message(r->context, ret);
_kdc_r_log(r, 0, "add_enc_pa_rep failed: %s: %d", msg, ret);
krb5_free_error_message(r->context, msg);
goto out;
}
}
/*
*
*/
ret = _kdc_encode_reply(context, config,
r->armor_crypto, req->req_body.nonce,
&rep, &r->et, &r->ek, setype, r->server->entry.kvno,
&skey->key, r->client->entry.kvno,
&r->reply_key, 0, &r->e_text, reply);
if (ret)
goto out;
/*
* Check if message too large
*/
if (datagram_reply && reply->length > config->max_datagram_reply_length) {
krb5_data_free(reply);
ret = KRB5KRB_ERR_RESPONSE_TOO_BIG;
_kdc_set_e_text(r, "Reply packet too large");
}
out:
free_AS_REP(&rep);
/*
* In case of a non proxy error, build an error message.
*/
if(ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {
ret = _kdc_fast_mk_error(context, r,
&error_method,
r->armor_crypto,
&req->req_body,
ret, r->e_text,
r->server_princ,
&r->client_princ->name,
&r->client_princ->realm,
NULL, NULL,
reply);
if (ret)
goto out2;
}
out2:
free_EncTicketPart(&r->et);
free_EncKDCRepPart(&r->ek);
free_KDCFastState(&r->fast);
if (error_method.len)
free_METHOD_DATA(&error_method);
if (r->outpadata.len)
free_METHOD_DATA(&r->outpadata);
if (r->client_princ) {
krb5_free_principal(context, r->client_princ);
r->client_princ = NULL;
}
if (r->client_name) {
free(r->client_name);
r->client_name = NULL;
}
if (r->server_princ){
krb5_free_principal(context, r->server_princ);
r->server_princ = NULL;
}
if (r->server_name) {
free(r->server_name);
r->server_name = NULL;
}
if (r->client)
_kdc_free_ent(context, r->client);
if (r->server)
_kdc_free_ent(context, r->server);
if (r->armor_crypto) {
krb5_crypto_destroy(r->context, r->armor_crypto);
r->armor_crypto = NULL;
}
krb5_free_keyblock_contents(r->context, &r->reply_key);
krb5_free_keyblock_contents(r->context, &r->session_key);
return ret;
} | _kdc_as_rep(kdc_request_t r,
krb5_data *reply,
const char *from,
struct sockaddr *from_addr,
int datagram_reply)
{
krb5_context context = r->context;
krb5_kdc_configuration *config = r->config;
KDC_REQ *req = &r->req;
KDC_REQ_BODY *b = NULL;
AS_REP rep;
KDCOptions f;
krb5_enctype setype;
krb5_error_code ret = 0;
Key *skey;
int found_pa = 0;
int i, flags = HDB_F_FOR_AS_REQ;
METHOD_DATA error_method;
const PA_DATA *pa;
memset(&rep, 0, sizeof(rep));
error_method.len = 0;
error_method.val = NULL;
/*
* Look for FAST armor and unwrap
*/
ret = _kdc_fast_unwrap_request(r);
if (ret) {
_kdc_r_log(r, 0, "FAST unwrap request from %s failed: %d", from, ret);
goto out;
}
b = &req->req_body;
f = b->kdc_options;
if (f.canonicalize)
flags |= HDB_F_CANON;
if(b->sname == NULL){
ret = KRB5KRB_ERR_GENERIC;
_kdc_set_e_text(r, "No server in request");
} else{
ret = _krb5_principalname2krb5_principal (context,
&r->server_princ,
*(b->sname),
b->realm);
if (ret == 0)
ret = krb5_unparse_name(context, r->server_princ, &r->server_name);
}
if (ret) {
kdc_log(context, config, 0,
"AS-REQ malformed server name from %s", from);
goto out;
}
if(b->cname == NULL){
ret = KRB5KRB_ERR_GENERIC;
_kdc_set_e_text(r, "No client in request");
} else {
ret = _krb5_principalname2krb5_principal (context,
&r->client_princ,
*(b->cname),
b->realm);
if (ret)
goto out;
ret = krb5_unparse_name(context, r->client_princ, &r->client_name);
}
if (ret) {
kdc_log(context, config, 0,
"AS-REQ malformed client name from %s", from);
goto out;
}
kdc_log(context, config, 0, "AS-REQ %s from %s for %s",
r->client_name, from, r->server_name);
/*
*
*/
if (_kdc_is_anonymous(context, r->client_princ)) {
if (!_kdc_is_anon_request(b)) {
kdc_log(context, config, 0, "Anonymous ticket w/o anonymous flag");
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
goto out;
}
} else if (_kdc_is_anon_request(b)) {
kdc_log(context, config, 0,
"Request for a anonymous ticket with non "
"anonymous client name: %s", r->client_name);
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
goto out;
}
/*
*
*/
ret = _kdc_db_fetch(context, config, r->client_princ,
HDB_F_GET_CLIENT | flags, NULL,
&r->clientdb, &r->client);
if(ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "client %s does not have secrets at this KDC, need to proxy",
r->client_name);
goto out;
} else if (ret == HDB_ERR_WRONG_REALM) {
char *fixed_client_name = NULL;
ret = krb5_unparse_name(context, r->client->entry.principal,
&fixed_client_name);
if (ret) {
goto out;
}
kdc_log(context, config, 0, "WRONG_REALM - %s -> %s",
r->client_name, fixed_client_name);
free(fixed_client_name);
ret = _kdc_fast_mk_error(context, r,
&error_method,
r->armor_crypto,
&req->req_body,
KRB5_KDC_ERR_WRONG_REALM,
NULL,
r->server_princ,
NULL,
&r->client->entry.principal->realm,
NULL, NULL,
reply);
goto out;
} else if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "UNKNOWN -- %s: %s", r->client_name, msg);
krb5_free_error_message(context, msg);
ret = KRB5KDC_ERR_C_PRINCIPAL_UNKNOWN;
goto out;
}
ret = _kdc_db_fetch(context, config, r->server_princ,
HDB_F_GET_SERVER|HDB_F_GET_KRBTGT | flags,
NULL, NULL, &r->server);
if(ret == HDB_ERR_NOT_FOUND_HERE) {
kdc_log(context, config, 5, "target %s does not have secrets at this KDC, need to proxy",
r->server_name);
goto out;
} else if(ret){
const char *msg = krb5_get_error_message(context, ret);
kdc_log(context, config, 0, "UNKNOWN -- %s: %s", r->server_name, msg);
krb5_free_error_message(context, msg);
ret = KRB5KDC_ERR_S_PRINCIPAL_UNKNOWN;
goto out;
}
/*
* Select a session enctype from the list of the crypto system
* supported enctypes that is supported by the client and is one of
* the enctype of the enctype of the service (likely krbtgt).
*
* The latter is used as a hint of what enctypes all KDC support,
* to make sure a newer version of KDC won't generate a session
* enctype that an older version of a KDC in the same realm can't
* decrypt.
*/
ret = _kdc_find_etype(context,
krb5_principal_is_krbtgt(context, r->server_princ) ?
config->tgt_use_strongest_session_key :
config->svc_use_strongest_session_key, FALSE,
r->client, b->etype.val, b->etype.len, &r->sessionetype,
NULL);
if (ret) {
kdc_log(context, config, 0,
"Client (%s) from %s has no common enctypes with KDC "
"to use for the session key",
r->client_name, from);
goto out;
}
/*
* Pre-auth processing
*/
if(req->padata){
unsigned int n;
log_patypes(context, config, req->padata);
/* Check if preauth matching */
for (n = 0; !found_pa && n < sizeof(pat) / sizeof(pat[0]); n++) {
if (pat[n].validate == NULL)
continue;
if (r->armor_crypto == NULL && (pat[n].flags & PA_REQ_FAST))
continue;
kdc_log(context, config, 5,
"Looking for %s pa-data -- %s", pat[n].name, r->client_name);
i = 0;
pa = _kdc_find_padata(req, &i, pat[n].type);
if (pa) {
ret = pat[n].validate(r, pa);
if (ret != 0) {
goto out;
}
kdc_log(context, config, 0,
"%s pre-authentication succeeded -- %s",
pat[n].name, r->client_name);
found_pa = 1;
r->et.flags.pre_authent = 1;
}
}
}
if (found_pa == 0) {
Key *ckey = NULL;
size_t n;
for (n = 0; n < sizeof(pat) / sizeof(pat[0]); n++) {
if ((pat[n].flags & PA_ANNOUNCE) == 0)
continue;
ret = krb5_padata_add(context, &error_method,
pat[n].type, NULL, 0);
if (ret)
goto out;
}
/*
* If there is a client key, send ETYPE_INFO{,2}
*/
ret = _kdc_find_etype(context,
config->preauth_use_strongest_session_key, TRUE,
r->client, b->etype.val, b->etype.len, NULL, &ckey);
if (ret == 0) {
/*
* RFC4120 requires:
* - If the client only knows about old enctypes, then send
* both info replies (we send 'info' first in the list).
* - If the client is 'modern', because it knows about 'new'
* enctype types, then only send the 'info2' reply.
*
* Before we send the full list of etype-info data, we pick
* the client key we would have used anyway below, just pick
* that instead.
*/
if (older_enctype(ckey->key.keytype)) {
ret = get_pa_etype_info(context, config,
&error_method, ckey);
if (ret)
goto out;
}
ret = get_pa_etype_info2(context, config,
&error_method, ckey);
if (ret)
goto out;
}
/*
* send requre preauth is its required or anon is requested,
* anon is today only allowed via preauth mechanisms.
*/
if (require_preauth_p(r) || _kdc_is_anon_request(b)) {
ret = KRB5KDC_ERR_PREAUTH_REQUIRED;
_kdc_set_e_text(r, "Need to use PA-ENC-TIMESTAMP/PA-PK-AS-REQ");
goto out;
}
if (ckey == NULL) {
ret = KRB5KDC_ERR_CLIENT_NOTYET;
_kdc_set_e_text(r, "Doesn't have a client key available");
goto out;
}
krb5_free_keyblock_contents(r->context, &r->reply_key);
ret = krb5_copy_keyblock_contents(r->context, &ckey->key, &r->reply_key);
if (ret)
goto out;
}
if (r->clientdb->hdb_auth_status) {
r->clientdb->hdb_auth_status(context, r->clientdb, r->client,
HDB_AUTH_SUCCESS);
}
/*
* Verify flags after the user been required to prove its identity
* with in a preauth mech.
*/
ret = _kdc_check_access(context, config, r->client, r->client_name,
r->server, r->server_name,
req, &error_method);
if(ret)
goto out;
/*
* Select the best encryption type for the KDC with out regard to
* the client since the client never needs to read that data.
*/
ret = _kdc_get_preferred_key(context, config,
r->server, r->server_name,
&setype, &skey);
if(ret)
goto out;
if(f.renew || f.validate || f.proxy || f.forwarded || f.enc_tkt_in_skey
|| (_kdc_is_anon_request(b) && !config->allow_anonymous)) {
ret = KRB5KDC_ERR_BADOPTION;
_kdc_set_e_text(r, "Bad KDC options");
goto out;
}
/*
* Build reply
*/
rep.pvno = 5;
rep.msg_type = krb_as_rep;
if (_kdc_is_anonymous(context, r->client_princ)) {
Realm anon_realm=KRB5_ANON_REALM;
ret = copy_Realm(&anon_realm, &rep.crealm);
} else
ret = copy_Realm(&r->client->entry.principal->realm, &rep.crealm);
if (ret)
goto out;
ret = _krb5_principal2principalname(&rep.cname, r->client->entry.principal);
if (ret)
goto out;
rep.ticket.tkt_vno = 5;
ret = copy_Realm(&r->server->entry.principal->realm, &rep.ticket.realm);
if (ret)
goto out;
_krb5_principal2principalname(&rep.ticket.sname,
r->server->entry.principal);
/* java 1.6 expects the name to be the same type, lets allow that
* uncomplicated name-types. */
#define CNT(sp,t) (((sp)->sname->name_type) == KRB5_NT_##t)
if (CNT(b, UNKNOWN) || CNT(b, PRINCIPAL) || CNT(b, SRV_INST) || CNT(b, SRV_HST) || CNT(b, SRV_XHST))
rep.ticket.sname.name_type = b->sname->name_type;
#undef CNT
r->et.flags.initial = 1;
if(r->client->entry.flags.forwardable && r->server->entry.flags.forwardable)
r->et.flags.forwardable = f.forwardable;
else if (f.forwardable) {
_kdc_set_e_text(r, "Ticket may not be forwardable");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
if(r->client->entry.flags.proxiable && r->server->entry.flags.proxiable)
r->et.flags.proxiable = f.proxiable;
else if (f.proxiable) {
_kdc_set_e_text(r, "Ticket may not be proxiable");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
if(r->client->entry.flags.postdate && r->server->entry.flags.postdate)
r->et.flags.may_postdate = f.allow_postdate;
else if (f.allow_postdate){
_kdc_set_e_text(r, "Ticket may not be postdate");
ret = KRB5KDC_ERR_POLICY;
goto out;
}
/* check for valid set of addresses */
if(!_kdc_check_addresses(context, config, b->addresses, from_addr)) {
_kdc_set_e_text(r, "Bad address list in requested");
ret = KRB5KRB_AP_ERR_BADADDR;
goto out;
}
ret = copy_PrincipalName(&rep.cname, &r->et.cname);
if (ret)
goto out;
ret = copy_Realm(&rep.crealm, &r->et.crealm);
if (ret)
goto out;
{
time_t start;
time_t t;
start = r->et.authtime = kdc_time;
if(f.postdated && req->req_body.from){
ALLOC(r->et.starttime);
start = *r->et.starttime = *req->req_body.from;
r->et.flags.invalid = 1;
r->et.flags.postdated = 1; /* XXX ??? */
}
_kdc_fix_time(&b->till);
t = *b->till;
/* be careful not overflowing */
if(r->client->entry.max_life)
t = start + min(t - start, *r->client->entry.max_life);
if(r->server->entry.max_life)
t = start + min(t - start, *r->server->entry.max_life);
#if 0
t = min(t, start + realm->max_life);
#endif
r->et.endtime = t;
if(f.renewable_ok && r->et.endtime < *b->till){
f.renewable = 1;
if(b->rtime == NULL){
ALLOC(b->rtime);
*b->rtime = 0;
}
if(*b->rtime < *b->till)
*b->rtime = *b->till;
}
if(f.renewable && b->rtime){
t = *b->rtime;
if(t == 0)
t = MAX_TIME;
if(r->client->entry.max_renew)
t = start + min(t - start, *r->client->entry.max_renew);
if(r->server->entry.max_renew)
t = start + min(t - start, *r->server->entry.max_renew);
#if 0
t = min(t, start + realm->max_renew);
#endif
ALLOC(r->et.renew_till);
*r->et.renew_till = t;
r->et.flags.renewable = 1;
}
}
if (_kdc_is_anon_request(b))
r->et.flags.anonymous = 1;
if(b->addresses){
ALLOC(r->et.caddr);
copy_HostAddresses(b->addresses, r->et.caddr);
}
r->et.transited.tr_type = DOMAIN_X500_COMPRESS;
krb5_data_zero(&r->et.transited.contents);
/* The MIT ASN.1 library (obviously) doesn't tell lengths encoded
* as 0 and as 0x80 (meaning indefinite length) apart, and is thus
* incapable of correctly decoding SEQUENCE OF's of zero length.
*
* To fix this, always send at least one no-op last_req
*
* If there's a pw_end or valid_end we will use that,
* otherwise just a dummy lr.
*/
r->ek.last_req.val = malloc(2 * sizeof(*r->ek.last_req.val));
if (r->ek.last_req.val == NULL) {
ret = ENOMEM;
goto out;
}
r->ek.last_req.len = 0;
if (r->client->entry.pw_end
&& (config->kdc_warn_pwexpire == 0
|| kdc_time + config->kdc_warn_pwexpire >= *r->client->entry.pw_end)) {
r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_PW_EXPTIME;
r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.pw_end;
++r->ek.last_req.len;
}
if (r->client->entry.valid_end) {
r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_ACCT_EXPTIME;
r->ek.last_req.val[r->ek.last_req.len].lr_value = *r->client->entry.valid_end;
++r->ek.last_req.len;
}
if (r->ek.last_req.len == 0) {
r->ek.last_req.val[r->ek.last_req.len].lr_type = LR_NONE;
r->ek.last_req.val[r->ek.last_req.len].lr_value = 0;
++r->ek.last_req.len;
}
r->ek.nonce = b->nonce;
if (r->client->entry.valid_end || r->client->entry.pw_end) {
ALLOC(r->ek.key_expiration);
if (r->client->entry.valid_end) {
if (r->client->entry.pw_end)
*r->ek.key_expiration = min(*r->client->entry.valid_end,
*r->client->entry.pw_end);
else
*r->ek.key_expiration = *r->client->entry.valid_end;
} else
*r->ek.key_expiration = *r->client->entry.pw_end;
} else
r->ek.key_expiration = NULL;
r->ek.flags = r->et.flags;
r->ek.authtime = r->et.authtime;
if (r->et.starttime) {
ALLOC(r->ek.starttime);
*r->ek.starttime = *r->et.starttime;
}
r->ek.endtime = r->et.endtime;
if (r->et.renew_till) {
ALLOC(r->ek.renew_till);
*r->ek.renew_till = *r->et.renew_till;
}
ret = copy_Realm(&rep.ticket.realm, &r->ek.srealm);
if (ret)
goto out;
ret = copy_PrincipalName(&rep.ticket.sname, &r->ek.sname);
if (ret)
goto out;
if(r->et.caddr){
ALLOC(r->ek.caddr);
copy_HostAddresses(r->et.caddr, r->ek.caddr);
}
/*
* Check and session and reply keys
*/
if (r->session_key.keytype == ETYPE_NULL) {
ret = krb5_generate_random_keyblock(context, r->sessionetype, &r->session_key);
if (ret)
goto out;
}
if (r->reply_key.keytype == ETYPE_NULL) {
_kdc_set_e_text(r, "Client have no reply key");
ret = KRB5KDC_ERR_CLIENT_NOTYET;
goto out;
}
ret = copy_EncryptionKey(&r->session_key, &r->et.key);
if (ret)
goto out;
ret = copy_EncryptionKey(&r->session_key, &r->ek.key);
if (ret)
goto out;
if (r->outpadata.len) {
ALLOC(rep.padata);
if (rep.padata == NULL) {
ret = ENOMEM;
goto out;
}
ret = copy_METHOD_DATA(&r->outpadata, rep.padata);
if (ret)
goto out;
}
/* Add the PAC */
if (send_pac_p(context, req)) {
generate_pac(r, skey);
}
_kdc_log_timestamp(context, config, "AS-REQ", r->et.authtime, r->et.starttime,
r->et.endtime, r->et.renew_till);
/* do this as the last thing since this signs the EncTicketPart */
ret = _kdc_add_KRB5SignedPath(context,
config,
r->server,
setype,
r->client->entry.principal,
NULL,
NULL,
&r->et);
if (ret)
goto out;
log_as_req(context, config, r->reply_key.keytype, setype, b);
/*
* We always say we support FAST/enc-pa-rep
*/
r->et.flags.enc_pa_rep = r->ek.flags.enc_pa_rep = 1;
/*
* Add REQ_ENC_PA_REP if client supports it
*/
i = 0;
pa = _kdc_find_padata(req, &i, KRB5_PADATA_REQ_ENC_PA_REP);
if (pa) {
ret = add_enc_pa_rep(r);
if (ret) {
const char *msg = krb5_get_error_message(r->context, ret);
_kdc_r_log(r, 0, "add_enc_pa_rep failed: %s: %d", msg, ret);
krb5_free_error_message(r->context, msg);
goto out;
}
}
/*
*
*/
ret = _kdc_encode_reply(context, config,
r->armor_crypto, req->req_body.nonce,
&rep, &r->et, &r->ek, setype, r->server->entry.kvno,
&skey->key, r->client->entry.kvno,
&r->reply_key, 0, &r->e_text, reply);
if (ret)
goto out;
/*
* Check if message too large
*/
if (datagram_reply && reply->length > config->max_datagram_reply_length) {
krb5_data_free(reply);
ret = KRB5KRB_ERR_RESPONSE_TOO_BIG;
_kdc_set_e_text(r, "Reply packet too large");
}
out:
free_AS_REP(&rep);
/*
* In case of a non proxy error, build an error message.
*/
if (ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {
ret = _kdc_fast_mk_error(context, r,
&error_method,
r->armor_crypto,
&req->req_body,
ret, r->e_text,
r->server_princ,
r->client_princ ?
&r->client_princ->name : NULL,
r->client_princ ?
&r->client_princ->realm : NULL,
NULL, NULL,
reply);
if (ret)
goto out2;
}
out2:
free_EncTicketPart(&r->et);
free_EncKDCRepPart(&r->ek);
free_KDCFastState(&r->fast);
if (error_method.len)
free_METHOD_DATA(&error_method);
if (r->outpadata.len)
free_METHOD_DATA(&r->outpadata);
if (r->client_princ) {
krb5_free_principal(context, r->client_princ);
r->client_princ = NULL;
}
if (r->client_name) {
free(r->client_name);
r->client_name = NULL;
}
if (r->server_princ){
krb5_free_principal(context, r->server_princ);
r->server_princ = NULL;
}
if (r->server_name) {
free(r->server_name);
r->server_name = NULL;
}
if (r->client)
_kdc_free_ent(context, r->client);
if (r->server)
_kdc_free_ent(context, r->server);
if (r->armor_crypto) {
krb5_crypto_destroy(r->context, r->armor_crypto);
r->armor_crypto = NULL;
}
krb5_free_keyblock_contents(r->context, &r->reply_key);
krb5_free_keyblock_contents(r->context, &r->session_key);
return ret;
} | {
"deleted": [
{
"line_no": 619,
"char_start": 16727,
"char_end": 16801,
"line": " if(ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {\n"
},
{
"line_no": 626,
"char_start": 16945,
"char_end": 16974,
"line": "\t\t\t\t &r->client_princ->name,\n"
},
{
"line_no": 627,
"char_start": 16974,
"char_end": 17004,
"line": "\t\t\t\t &r->client_princ->realm,\n"
}
],
"added": [
{
"line_no": 619,
"char_start": 16727,
"char_end": 16802,
"line": " if (ret != 0 && ret != HDB_ERR_NOT_FOUND_HERE && reply->length == 0) {\n"
},
{
"line_no": 626,
"char_start": 16946,
"char_end": 16969,
"line": "\t\t\t\t r->client_princ ?\n"
},
{
"line_no": 627,
"char_start": 16969,
"char_end": 17037,
"line": " &r->client_princ->name : NULL,\n"
},
{
"line_no": 628,
"char_start": 17037,
"char_end": 17060,
"line": "\t\t\t\t r->client_princ ?\n"
},
{
"line_no": 629,
"char_start": 17060,
"char_end": 17129,
"line": " &r->client_princ->realm : NULL,\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 16733,
"char_end": 16734,
"chars": " "
},
{
"char_start": 16951,
"char_end": 17006,
"chars": "r->client_princ ?\n "
},
{
"char_start": 17028,
"char_end": 17035,
"chars": " : NULL"
},
{
"char_start": 17042,
"char_end": 17097,
"chars": "r->client_princ ?\n "
},
{
"char_start": 17120,
"char_end": 17127,
"chars": " : NULL"
}
]
} | github.com/heimdal/heimdal/commit/1a6a6e462dc2ac6111f9e02c6852ddec4849b887 | kdc/kerberos5.c | cwe-476 |
formUpdateBuffer | formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
} | formUpdateBuffer(Anchor *a, Buffer *buf, FormItemList *form)
{
Buffer save;
char *p;
int spos, epos, rows, c_rows, pos, col = 0;
Line *l;
copyBuffer(&save, buf);
gotoLine(buf, a->start.line);
switch (form->type) {
case FORM_TEXTAREA:
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
#ifdef MENU_SELECT
case FORM_SELECT:
#endif /* MENU_SELECT */
spos = a->start.pos;
epos = a->end.pos;
break;
default:
spos = a->start.pos + 1;
epos = a->end.pos - 1;
}
switch (form->type) {
case FORM_INPUT_CHECKBOX:
case FORM_INPUT_RADIO:
if (buf->currentLine == NULL ||
spos >= buf->currentLine->len || spos < 0)
break;
if (form->checked)
buf->currentLine->lineBuf[spos] = '*';
else
buf->currentLine->lineBuf[spos] = ' ';
break;
case FORM_INPUT_TEXT:
case FORM_INPUT_FILE:
case FORM_INPUT_PASSWORD:
case FORM_TEXTAREA:
#ifdef MENU_SELECT
case FORM_SELECT:
if (form->type == FORM_SELECT) {
p = form->label->ptr;
updateSelectOption(form, form->select_option);
}
else
#endif /* MENU_SELECT */
{
if (!form->value)
break;
p = form->value->ptr;
}
l = buf->currentLine;
if (!l)
break;
if (form->type == FORM_TEXTAREA) {
int n = a->y - buf->currentLine->linenumber;
if (n > 0)
for (; l && n; l = l->prev, n--) ;
else if (n < 0)
for (; l && n; l = l->prev, n++) ;
if (!l)
break;
}
rows = form->rows ? form->rows : 1;
col = COLPOS(l, a->start.pos);
for (c_rows = 0; c_rows < rows; c_rows++, l = l->next) {
if (l == NULL)
break;
if (rows > 1) {
pos = columnPos(l, col);
a = retrieveAnchor(buf->formitem, l->linenumber, pos);
if (a == NULL)
break;
spos = a->start.pos;
epos = a->end.pos;
}
if (a->start.line != a->end.line || spos > epos || epos >= l->len ||
spos < 0 || epos < 0 || COLPOS(l, epos) < col)
break;
pos = form_update_line(l, &p, spos, epos, COLPOS(l, epos) - col,
rows > 1,
form->type == FORM_INPUT_PASSWORD);
if (pos != epos) {
shiftAnchorPosition(buf->href, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->name, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->img, buf->hmarklist,
a->start.line, spos, pos - epos);
shiftAnchorPosition(buf->formitem, buf->hmarklist,
a->start.line, spos, pos - epos);
}
}
break;
}
copyBuffer(buf, &save);
arrangeLine(buf);
} | {
"deleted": [],
"added": [
{
"line_no": 70,
"char_start": 1647,
"char_end": 1667,
"line": "\t if (l == NULL)\n"
},
{
"line_no": 71,
"char_start": 1667,
"char_end": 1676,
"line": "\t\tbreak;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1656,
"char_end": 1685,
"chars": "l == NULL)\n\t\tbreak;\n\t if ("
}
]
} | github.com/tats/w3m/commit/7fdc83b0364005a0b5ed869230dd81752ba022e8 | form.c | cwe-476 |
lexer_process_char_literal | lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */ | lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
if (length == 0)
{
has_escape = false;
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */ | {
"deleted": [],
"added": [
{
"line_no": 41,
"char_start": 1556,
"char_end": 1575,
"line": " if (length == 0)\n"
},
{
"line_no": 42,
"char_start": 1575,
"char_end": 1579,
"line": " {\n"
},
{
"line_no": 43,
"char_start": 1579,
"char_end": 1603,
"line": " has_escape = false;\n"
},
{
"line_no": 44,
"char_start": 1603,
"char_end": 1607,
"line": " }\n"
},
{
"line_no": 45,
"char_start": 1607,
"char_end": 1608,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1558,
"char_end": 1610,
"chars": "if (length == 0)\n {\n has_escape = false;\n }\n\n "
}
]
} | github.com/zherczeg/jerryscript/commit/03a8c630f015f63268639d3ed3bf82cff6fa77d8 | jerry-core/parser/js/js-lexer.c | cwe-476 |
unimac_mdio_probe | static int unimac_mdio_probe(struct platform_device *pdev)
{
struct unimac_mdio_pdata *pdata = pdev->dev.platform_data;
struct unimac_mdio_priv *priv;
struct device_node *np;
struct mii_bus *bus;
struct resource *r;
int ret;
np = pdev->dev.of_node;
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
/* Just ioremap, as this MDIO block is usually integrated into an
* Ethernet MAC controller register range
*/
priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!priv->base) {
dev_err(&pdev->dev, "failed to remap register\n");
return -ENOMEM;
}
priv->mii_bus = mdiobus_alloc();
if (!priv->mii_bus)
return -ENOMEM;
bus = priv->mii_bus;
bus->priv = priv;
if (pdata) {
bus->name = pdata->bus_name;
priv->wait_func = pdata->wait_func;
priv->wait_func_data = pdata->wait_func_data;
bus->phy_mask = ~pdata->phy_mask;
} else {
bus->name = "unimac MII bus";
priv->wait_func_data = priv;
priv->wait_func = unimac_mdio_poll;
}
bus->parent = &pdev->dev;
bus->read = unimac_mdio_read;
bus->write = unimac_mdio_write;
bus->reset = unimac_mdio_reset;
snprintf(bus->id, MII_BUS_ID_SIZE, "%s-%d", pdev->name, pdev->id);
ret = of_mdiobus_register(bus, np);
if (ret) {
dev_err(&pdev->dev, "MDIO bus registration failed\n");
goto out_mdio_free;
}
platform_set_drvdata(pdev, priv);
dev_info(&pdev->dev, "Broadcom UniMAC MDIO bus at 0x%p\n", priv->base);
return 0;
out_mdio_free:
mdiobus_free(bus);
return ret;
} | static int unimac_mdio_probe(struct platform_device *pdev)
{
struct unimac_mdio_pdata *pdata = pdev->dev.platform_data;
struct unimac_mdio_priv *priv;
struct device_node *np;
struct mii_bus *bus;
struct resource *r;
int ret;
np = pdev->dev.of_node;
priv = devm_kzalloc(&pdev->dev, sizeof(*priv), GFP_KERNEL);
if (!priv)
return -ENOMEM;
r = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!r)
return -EINVAL;
/* Just ioremap, as this MDIO block is usually integrated into an
* Ethernet MAC controller register range
*/
priv->base = devm_ioremap(&pdev->dev, r->start, resource_size(r));
if (!priv->base) {
dev_err(&pdev->dev, "failed to remap register\n");
return -ENOMEM;
}
priv->mii_bus = mdiobus_alloc();
if (!priv->mii_bus)
return -ENOMEM;
bus = priv->mii_bus;
bus->priv = priv;
if (pdata) {
bus->name = pdata->bus_name;
priv->wait_func = pdata->wait_func;
priv->wait_func_data = pdata->wait_func_data;
bus->phy_mask = ~pdata->phy_mask;
} else {
bus->name = "unimac MII bus";
priv->wait_func_data = priv;
priv->wait_func = unimac_mdio_poll;
}
bus->parent = &pdev->dev;
bus->read = unimac_mdio_read;
bus->write = unimac_mdio_write;
bus->reset = unimac_mdio_reset;
snprintf(bus->id, MII_BUS_ID_SIZE, "%s-%d", pdev->name, pdev->id);
ret = of_mdiobus_register(bus, np);
if (ret) {
dev_err(&pdev->dev, "MDIO bus registration failed\n");
goto out_mdio_free;
}
platform_set_drvdata(pdev, priv);
dev_info(&pdev->dev, "Broadcom UniMAC MDIO bus at 0x%p\n", priv->base);
return 0;
out_mdio_free:
mdiobus_free(bus);
return ret;
} | {
"deleted": [],
"added": [
{
"line_no": 17,
"char_start": 403,
"char_end": 412,
"line": "\tif (!r)\n"
},
{
"line_no": 18,
"char_start": 412,
"char_end": 430,
"line": "\t\treturn -EINVAL;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 403,
"char_end": 430,
"chars": "\tif (!r)\n\t\treturn -EINVAL;\n"
}
]
} | github.com/torvalds/linux/commit/297a6961ffb8ff4dc66c9fbf53b924bd1dda05d5 | drivers/net/phy/mdio-bcm-unimac.c | cwe-476 |
hi3660_stub_clk_probe | static int hi3660_stub_clk_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
unsigned int i;
int ret;
/* Use mailbox client without blocking */
stub_clk_chan.cl.dev = dev;
stub_clk_chan.cl.tx_done = NULL;
stub_clk_chan.cl.tx_block = false;
stub_clk_chan.cl.knows_txdone = false;
/* Allocate mailbox channel */
stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);
if (IS_ERR(stub_clk_chan.mbox))
return PTR_ERR(stub_clk_chan.mbox);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
freq_reg = devm_ioremap(dev, res->start, resource_size(res));
if (!freq_reg)
return -ENOMEM;
freq_reg += HI3660_STUB_CLOCK_DATA;
for (i = 0; i < HI3660_CLK_STUB_NUM; i++) {
ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);
if (ret)
return ret;
}
return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,
hi3660_stub_clks);
} | static int hi3660_stub_clk_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct resource *res;
unsigned int i;
int ret;
/* Use mailbox client without blocking */
stub_clk_chan.cl.dev = dev;
stub_clk_chan.cl.tx_done = NULL;
stub_clk_chan.cl.tx_block = false;
stub_clk_chan.cl.knows_txdone = false;
/* Allocate mailbox channel */
stub_clk_chan.mbox = mbox_request_channel(&stub_clk_chan.cl, 0);
if (IS_ERR(stub_clk_chan.mbox))
return PTR_ERR(stub_clk_chan.mbox);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res)
return -EINVAL;
freq_reg = devm_ioremap(dev, res->start, resource_size(res));
if (!freq_reg)
return -ENOMEM;
freq_reg += HI3660_STUB_CLOCK_DATA;
for (i = 0; i < HI3660_CLK_STUB_NUM; i++) {
ret = devm_clk_hw_register(&pdev->dev, &hi3660_stub_clks[i].hw);
if (ret)
return ret;
}
return devm_of_clk_add_hw_provider(&pdev->dev, hi3660_stub_clk_hw_get,
hi3660_stub_clks);
} | {
"deleted": [],
"added": [
{
"line_no": 20,
"char_start": 558,
"char_end": 569,
"line": "\tif (!res)\n"
},
{
"line_no": 21,
"char_start": 569,
"char_end": 587,
"line": "\t\treturn -EINVAL;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 559,
"char_end": 588,
"chars": "if (!res)\n\t\treturn -EINVAL;\n\t"
}
]
} | github.com/torvalds/linux/commit/9903e41ae1f5d50c93f268ca3304d4d7c64b9311 | drivers/clk/hisilicon/clk-hi3660-stub.c | cwe-476 |
assoc_array_insert_into_terminal_node | static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
const struct assoc_array_ops *ops,
const void *index_key,
struct assoc_array_walk_result *result)
{
struct assoc_array_shortcut *shortcut, *new_s0;
struct assoc_array_node *node, *new_n0, *new_n1, *side;
struct assoc_array_ptr *ptr;
unsigned long dissimilarity, base_seg, blank;
size_t keylen;
bool have_meta;
int level, diff;
int slot, next_slot, free_slot, i, j;
node = result->terminal_node.node;
level = result->terminal_node.level;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
pr_devel("-->%s()\n", __func__);
/* We arrived at a node which doesn't have an onward node or shortcut
* pointer that we have to follow. This means that (a) the leaf we
* want must go here (either by insertion or replacement) or (b) we
* need to split this node and insert in one of the fragments.
*/
free_slot = -1;
/* Firstly, we have to check the leaves in this node to see if there's
* a matching one we should replace in place.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (!ptr) {
free_slot = i;
continue;
}
if (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) {
pr_devel("replace in slot %d\n", i);
edit->leaf_p = &node->slots[i];
edit->dead_leaf = node->slots[i];
pr_devel("<--%s() = ok [replace]\n", __func__);
return true;
}
}
/* If there is a free slot in this node then we can just insert the
* leaf here.
*/
if (free_slot >= 0) {
pr_devel("insert in free slot %d\n", free_slot);
edit->leaf_p = &node->slots[free_slot];
edit->adjust_count_on = node;
pr_devel("<--%s() = ok [insert]\n", __func__);
return true;
}
/* The node has no spare slots - so we're either going to have to split
* it or insert another node before it.
*
* Whatever, we're going to need at least two new nodes - so allocate
* those now. We may also need a new shortcut, but we deal with that
* when we need it.
*/
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
return false;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n1)
return false;
edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
/* We need to find out how similar the leaves are. */
pr_devel("no spare slots\n");
have_meta = false;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (assoc_array_ptr_is_meta(ptr)) {
edit->segment_cache[i] = 0xff;
have_meta = true;
continue;
}
base_seg = ops->get_object_key_chunk(
assoc_array_ptr_to_leaf(ptr), level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
if (have_meta) {
pr_devel("have meta\n");
goto split_node;
}
/* The node contains only leaves */
dissimilarity = 0;
base_seg = edit->segment_cache[0];
for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
dissimilarity |= edit->segment_cache[i] ^ base_seg;
pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
/* The old leaves all cluster in the same slot. We will need
* to insert a shortcut if the new node wants to cluster with them.
*/
if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
goto all_leaves_cluster_together;
/* Otherwise we can just insert a new node ahead of the old
* one.
*/
goto present_leaves_cluster_but_not_new_leaf;
}
split_node:
pr_devel("split node\n");
/* We need to split the current node; we know that the node doesn't
* simply contain a full set of leaves that cluster together (it
* contains meta pointers and/or non-clustering leaves).
*
* We need to expel at least two leaves out of a set consisting of the
* leaves in the node and the new leaf.
*
* We need a new node (n0) to replace the current one and a new node to
* take the expelled nodes (n1).
*/
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
do_split_node:
pr_devel("do_split_node\n");
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->nr_leaves_on_branch = 0;
/* Begin by finding two matching leaves. There have to be at least two
* that match - even if there are meta pointers - because any leaf that
* would match a slot with a meta pointer in it must be somewhere
* behind that meta pointer and cannot be here. Further, given N
* remaining leaf slots, we now have N+1 leaves to go in them.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
slot = edit->segment_cache[i];
if (slot != 0xff)
for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
if (edit->segment_cache[j] == slot)
goto found_slot_for_multiple_occupancy;
}
found_slot_for_multiple_occupancy:
pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
new_n1->parent_slot = slot;
/* Metadata pointers cannot change slot */
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
if (assoc_array_ptr_is_meta(node->slots[i]))
new_n0->slots[i] = node->slots[i];
else
new_n0->slots[i] = NULL;
BUG_ON(new_n0->slots[slot] != NULL);
new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
/* Filter the leaf pointers between the new nodes */
free_slot = -1;
next_slot = 0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (assoc_array_ptr_is_meta(node->slots[i]))
continue;
if (edit->segment_cache[i] == slot) {
new_n1->slots[next_slot++] = node->slots[i];
new_n1->nr_leaves_on_branch++;
} else {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
new_n0->slots[free_slot] = node->slots[i];
}
}
pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
edit->leaf_p = &new_n0->slots[free_slot];
edit->adjust_count_on = new_n0;
} else {
edit->leaf_p = &new_n1->slots[next_slot++];
edit->adjust_count_on = new_n1;
}
BUG_ON(next_slot <= 1);
edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (edit->segment_cache[i] == 0xff) {
ptr = node->slots[i];
BUG_ON(assoc_array_ptr_is_leaf(ptr));
if (assoc_array_ptr_is_node(ptr)) {
side = assoc_array_ptr_to_node(ptr);
edit->set_backpointers[i] = &side->back_pointer;
} else {
shortcut = assoc_array_ptr_to_shortcut(ptr);
edit->set_backpointers[i] = &shortcut->back_pointer;
}
}
}
ptr = node->back_pointer;
if (!ptr)
edit->set[0].ptr = &edit->array->root;
else if (assoc_array_ptr_is_node(ptr))
edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
else
edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [split node]\n", __func__);
return true;
present_leaves_cluster_but_not_new_leaf:
/* All the old leaves cluster in the same slot, but the new leaf wants
* to go into a different slot, so we create a new node to hold the new
* leaf and a pointer to a new node holding all the old leaves.
*/
pr_devel("present leaves cluster but not new leaf\n");
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = edit->segment_cache[0];
new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch;
edit->adjust_count_on = new_n0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
new_n1->slots[i] = node->slots[i];
new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0);
edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]];
edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot];
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [insert node before]\n", __func__);
return true;
all_leaves_cluster_together:
/* All the leaves, new and old, want to cluster together in this node
* in the same slot, so we have to replace this node with a shortcut to
* skip over the identical parts of the key and then place a pair of
* nodes, one inside the other, at the end of the shortcut and
* distribute the keys between them.
*
* Firstly we need to work out where the leaves start diverging as a
* bit position into their keys so that we know how big the shortcut
* needs to be.
*
* We only need to make a single pass of N of the N+1 leaves because if
* any keys differ between themselves at bit X then at least one of
* them must also differ with the base key at bit X or before.
*/
pr_devel("all leaves cluster together\n");
diff = INT_MAX;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
index_key);
if (x < diff) {
BUG_ON(x < 0);
diff = x;
}
}
BUG_ON(diff == INT_MAX);
BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s0)
return false;
edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
new_s0->back_pointer = node->back_pointer;
new_s0->parent_slot = node->parent_slot;
new_s0->next_node = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
new_n0->parent_slot = 0;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
BUG_ON(level <= 0);
for (i = 0; i < keylen; i++)
new_s0->index_key[i] =
ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
new_s0->index_key[keylen - 1] &= ~blank;
/* This now reduces to a node splitting exercise for which we'll need
* to regenerate the disparity table.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
base_seg = ops->get_key_chunk(index_key, level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
goto do_split_node;
} | static bool assoc_array_insert_into_terminal_node(struct assoc_array_edit *edit,
const struct assoc_array_ops *ops,
const void *index_key,
struct assoc_array_walk_result *result)
{
struct assoc_array_shortcut *shortcut, *new_s0;
struct assoc_array_node *node, *new_n0, *new_n1, *side;
struct assoc_array_ptr *ptr;
unsigned long dissimilarity, base_seg, blank;
size_t keylen;
bool have_meta;
int level, diff;
int slot, next_slot, free_slot, i, j;
node = result->terminal_node.node;
level = result->terminal_node.level;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = result->terminal_node.slot;
pr_devel("-->%s()\n", __func__);
/* We arrived at a node which doesn't have an onward node or shortcut
* pointer that we have to follow. This means that (a) the leaf we
* want must go here (either by insertion or replacement) or (b) we
* need to split this node and insert in one of the fragments.
*/
free_slot = -1;
/* Firstly, we have to check the leaves in this node to see if there's
* a matching one we should replace in place.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (!ptr) {
free_slot = i;
continue;
}
if (assoc_array_ptr_is_leaf(ptr) &&
ops->compare_object(assoc_array_ptr_to_leaf(ptr),
index_key)) {
pr_devel("replace in slot %d\n", i);
edit->leaf_p = &node->slots[i];
edit->dead_leaf = node->slots[i];
pr_devel("<--%s() = ok [replace]\n", __func__);
return true;
}
}
/* If there is a free slot in this node then we can just insert the
* leaf here.
*/
if (free_slot >= 0) {
pr_devel("insert in free slot %d\n", free_slot);
edit->leaf_p = &node->slots[free_slot];
edit->adjust_count_on = node;
pr_devel("<--%s() = ok [insert]\n", __func__);
return true;
}
/* The node has no spare slots - so we're either going to have to split
* it or insert another node before it.
*
* Whatever, we're going to need at least two new nodes - so allocate
* those now. We may also need a new shortcut, but we deal with that
* when we need it.
*/
new_n0 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n0)
return false;
edit->new_meta[0] = assoc_array_node_to_ptr(new_n0);
new_n1 = kzalloc(sizeof(struct assoc_array_node), GFP_KERNEL);
if (!new_n1)
return false;
edit->new_meta[1] = assoc_array_node_to_ptr(new_n1);
/* We need to find out how similar the leaves are. */
pr_devel("no spare slots\n");
have_meta = false;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
if (assoc_array_ptr_is_meta(ptr)) {
edit->segment_cache[i] = 0xff;
have_meta = true;
continue;
}
base_seg = ops->get_object_key_chunk(
assoc_array_ptr_to_leaf(ptr), level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
if (have_meta) {
pr_devel("have meta\n");
goto split_node;
}
/* The node contains only leaves */
dissimilarity = 0;
base_seg = edit->segment_cache[0];
for (i = 1; i < ASSOC_ARRAY_FAN_OUT; i++)
dissimilarity |= edit->segment_cache[i] ^ base_seg;
pr_devel("only leaves; dissimilarity=%lx\n", dissimilarity);
if ((dissimilarity & ASSOC_ARRAY_FAN_MASK) == 0) {
/* The old leaves all cluster in the same slot. We will need
* to insert a shortcut if the new node wants to cluster with them.
*/
if ((edit->segment_cache[ASSOC_ARRAY_FAN_OUT] ^ base_seg) == 0)
goto all_leaves_cluster_together;
/* Otherwise we can just insert a new node ahead of the old
* one.
*/
goto present_leaves_cluster_but_not_new_leaf;
}
split_node:
pr_devel("split node\n");
/* We need to split the current node; we know that the node doesn't
* simply contain a full set of leaves that cluster together (it
* contains meta pointers and/or non-clustering leaves).
*
* We need to expel at least two leaves out of a set consisting of the
* leaves in the node and the new leaf.
*
* We need a new node (n0) to replace the current one and a new node to
* take the expelled nodes (n1).
*/
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
do_split_node:
pr_devel("do_split_node\n");
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->nr_leaves_on_branch = 0;
/* Begin by finding two matching leaves. There have to be at least two
* that match - even if there are meta pointers - because any leaf that
* would match a slot with a meta pointer in it must be somewhere
* behind that meta pointer and cannot be here. Further, given N
* remaining leaf slots, we now have N+1 leaves to go in them.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
slot = edit->segment_cache[i];
if (slot != 0xff)
for (j = i + 1; j < ASSOC_ARRAY_FAN_OUT + 1; j++)
if (edit->segment_cache[j] == slot)
goto found_slot_for_multiple_occupancy;
}
found_slot_for_multiple_occupancy:
pr_devel("same slot: %x %x [%02x]\n", i, j, slot);
BUG_ON(i >= ASSOC_ARRAY_FAN_OUT);
BUG_ON(j >= ASSOC_ARRAY_FAN_OUT + 1);
BUG_ON(slot >= ASSOC_ARRAY_FAN_OUT);
new_n1->parent_slot = slot;
/* Metadata pointers cannot change slot */
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
if (assoc_array_ptr_is_meta(node->slots[i]))
new_n0->slots[i] = node->slots[i];
else
new_n0->slots[i] = NULL;
BUG_ON(new_n0->slots[slot] != NULL);
new_n0->slots[slot] = assoc_array_node_to_ptr(new_n1);
/* Filter the leaf pointers between the new nodes */
free_slot = -1;
next_slot = 0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (assoc_array_ptr_is_meta(node->slots[i]))
continue;
if (edit->segment_cache[i] == slot) {
new_n1->slots[next_slot++] = node->slots[i];
new_n1->nr_leaves_on_branch++;
} else {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
new_n0->slots[free_slot] = node->slots[i];
}
}
pr_devel("filtered: f=%x n=%x\n", free_slot, next_slot);
if (edit->segment_cache[ASSOC_ARRAY_FAN_OUT] != slot) {
do {
free_slot++;
} while (new_n0->slots[free_slot] != NULL);
edit->leaf_p = &new_n0->slots[free_slot];
edit->adjust_count_on = new_n0;
} else {
edit->leaf_p = &new_n1->slots[next_slot++];
edit->adjust_count_on = new_n1;
}
BUG_ON(next_slot <= 1);
edit->set_backpointers_to = assoc_array_node_to_ptr(new_n0);
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
if (edit->segment_cache[i] == 0xff) {
ptr = node->slots[i];
BUG_ON(assoc_array_ptr_is_leaf(ptr));
if (assoc_array_ptr_is_node(ptr)) {
side = assoc_array_ptr_to_node(ptr);
edit->set_backpointers[i] = &side->back_pointer;
} else {
shortcut = assoc_array_ptr_to_shortcut(ptr);
edit->set_backpointers[i] = &shortcut->back_pointer;
}
}
}
ptr = node->back_pointer;
if (!ptr)
edit->set[0].ptr = &edit->array->root;
else if (assoc_array_ptr_is_node(ptr))
edit->set[0].ptr = &assoc_array_ptr_to_node(ptr)->slots[node->parent_slot];
else
edit->set[0].ptr = &assoc_array_ptr_to_shortcut(ptr)->next_node;
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [split node]\n", __func__);
return true;
present_leaves_cluster_but_not_new_leaf:
/* All the old leaves cluster in the same slot, but the new leaf wants
* to go into a different slot, so we create a new node to hold the new
* leaf and a pointer to a new node holding all the old leaves.
*/
pr_devel("present leaves cluster but not new leaf\n");
new_n0->back_pointer = node->back_pointer;
new_n0->parent_slot = node->parent_slot;
new_n0->nr_leaves_on_branch = node->nr_leaves_on_branch;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = edit->segment_cache[0];
new_n1->nr_leaves_on_branch = node->nr_leaves_on_branch;
edit->adjust_count_on = new_n0;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++)
new_n1->slots[i] = node->slots[i];
new_n0->slots[edit->segment_cache[0]] = assoc_array_node_to_ptr(new_n0);
edit->leaf_p = &new_n0->slots[edit->segment_cache[ASSOC_ARRAY_FAN_OUT]];
edit->set[0].ptr = &assoc_array_ptr_to_node(node->back_pointer)->slots[node->parent_slot];
edit->set[0].to = assoc_array_node_to_ptr(new_n0);
edit->excised_meta[0] = assoc_array_node_to_ptr(node);
pr_devel("<--%s() = ok [insert node before]\n", __func__);
return true;
all_leaves_cluster_together:
/* All the leaves, new and old, want to cluster together in this node
* in the same slot, so we have to replace this node with a shortcut to
* skip over the identical parts of the key and then place a pair of
* nodes, one inside the other, at the end of the shortcut and
* distribute the keys between them.
*
* Firstly we need to work out where the leaves start diverging as a
* bit position into their keys so that we know how big the shortcut
* needs to be.
*
* We only need to make a single pass of N of the N+1 leaves because if
* any keys differ between themselves at bit X then at least one of
* them must also differ with the base key at bit X or before.
*/
pr_devel("all leaves cluster together\n");
diff = INT_MAX;
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
int x = ops->diff_objects(assoc_array_ptr_to_leaf(node->slots[i]),
index_key);
if (x < diff) {
BUG_ON(x < 0);
diff = x;
}
}
BUG_ON(diff == INT_MAX);
BUG_ON(diff < level + ASSOC_ARRAY_LEVEL_STEP);
keylen = round_up(diff, ASSOC_ARRAY_KEY_CHUNK_SIZE);
keylen >>= ASSOC_ARRAY_KEY_CHUNK_SHIFT;
new_s0 = kzalloc(sizeof(struct assoc_array_shortcut) +
keylen * sizeof(unsigned long), GFP_KERNEL);
if (!new_s0)
return false;
edit->new_meta[2] = assoc_array_shortcut_to_ptr(new_s0);
edit->set[0].to = assoc_array_shortcut_to_ptr(new_s0);
new_s0->back_pointer = node->back_pointer;
new_s0->parent_slot = node->parent_slot;
new_s0->next_node = assoc_array_node_to_ptr(new_n0);
new_n0->back_pointer = assoc_array_shortcut_to_ptr(new_s0);
new_n0->parent_slot = 0;
new_n1->back_pointer = assoc_array_node_to_ptr(new_n0);
new_n1->parent_slot = -1; /* Need to calculate this */
new_s0->skip_to_level = level = diff & ~ASSOC_ARRAY_LEVEL_STEP_MASK;
pr_devel("skip_to_level = %d [diff %d]\n", level, diff);
BUG_ON(level <= 0);
for (i = 0; i < keylen; i++)
new_s0->index_key[i] =
ops->get_key_chunk(index_key, i * ASSOC_ARRAY_KEY_CHUNK_SIZE);
blank = ULONG_MAX << (level & ASSOC_ARRAY_KEY_CHUNK_MASK);
pr_devel("blank off [%zu] %d: %lx\n", keylen - 1, level, blank);
new_s0->index_key[keylen - 1] &= ~blank;
/* This now reduces to a node splitting exercise for which we'll need
* to regenerate the disparity table.
*/
for (i = 0; i < ASSOC_ARRAY_FAN_OUT; i++) {
ptr = node->slots[i];
base_seg = ops->get_object_key_chunk(assoc_array_ptr_to_leaf(ptr),
level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[i] = base_seg & ASSOC_ARRAY_FAN_MASK;
}
base_seg = ops->get_key_chunk(index_key, level);
base_seg >>= level & ASSOC_ARRAY_KEY_CHUNK_MASK;
edit->segment_cache[ASSOC_ARRAY_FAN_OUT] = base_seg & ASSOC_ARRAY_FAN_MASK;
goto do_split_node;
} | {
"deleted": [
{
"line_no": 37,
"char_start": 1199,
"char_end": 1269,
"line": "\t\tif (ops->compare_object(assoc_array_ptr_to_leaf(ptr), index_key)) {\n"
}
],
"added": [
{
"line_no": 37,
"char_start": 1199,
"char_end": 1237,
"line": "\t\tif (assoc_array_ptr_is_leaf(ptr) &&\n"
},
{
"line_no": 38,
"char_start": 1237,
"char_end": 1293,
"line": "\t\t ops->compare_object(assoc_array_ptr_to_leaf(ptr),\n"
},
{
"line_no": 39,
"char_start": 1293,
"char_end": 1312,
"line": "\t\t\t\t\tindex_key)) {\n"
}
]
} | {
"deleted": [
{
"char_start": 1254,
"char_end": 1255,
"chars": " "
}
],
"added": [
{
"char_start": 1205,
"char_end": 1243,
"chars": "assoc_array_ptr_is_leaf(ptr) &&\n\t\t "
},
{
"char_start": 1292,
"char_end": 1298,
"chars": "\n\t\t\t\t\t"
}
]
} | github.com/torvalds/linux/commit/8d4a2ec1e0b41b0cf9a0c5cd4511da7f8e4f3de2 | lib/assoc_array.c | cwe-476 |
ipv4_pktinfo_prepare | void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
skb_dst_drop(skb);
} | void ipv4_pktinfo_prepare(const struct sock *sk, struct sk_buff *skb)
{
struct in_pktinfo *pktinfo = PKTINFO_SKB_CB(skb);
bool prepare = (inet_sk(sk)->cmsg_flags & IP_CMSG_PKTINFO) ||
ipv6_sk_rxinfo(sk);
if (prepare && skb_rtable(skb)) {
/* skb->cb is overloaded: prior to this point it is IP{6}CB
* which has interface index (iif) as the first member of the
* underlying inet{6}_skb_parm struct. This code then overlays
* PKTINFO_SKB_CB and in_pktinfo also has iif as the first
* element so the iif is picked up from the prior IPCB. If iif
* is the loopback interface, then return the sending interface
* (e.g., process binds socket to eth0 for Tx which is
* redirected to loopback in the rtable/dst).
*/
if (pktinfo->ipi_ifindex == LOOPBACK_IFINDEX)
pktinfo->ipi_ifindex = inet_iif(skb);
pktinfo->ipi_spec_dst.s_addr = fib_compute_spec_dst(skb);
} else {
pktinfo->ipi_ifindex = 0;
pktinfo->ipi_spec_dst.s_addr = 0;
}
/* We need to keep the dst for __ip_options_echo()
* We could restrict the test to opt.ts_needtime || opt.srr,
* but the following is good enough as IP options are not often used.
*/
if (unlikely(IPCB(skb)->opt.optlen))
skb_dst_force(skb);
else
skb_dst_drop(skb);
} | {
"deleted": [
{
"line_no": 25,
"char_start": 972,
"char_end": 992,
"line": "\tskb_dst_drop(skb);\n"
}
],
"added": [
{
"line_no": 25,
"char_start": 972,
"char_end": 1024,
"line": "\t/* We need to keep the dst for __ip_options_echo()\n"
},
{
"line_no": 26,
"char_start": 1024,
"char_end": 1086,
"line": "\t * We could restrict the test to opt.ts_needtime || opt.srr,\n"
},
{
"line_no": 27,
"char_start": 1086,
"char_end": 1157,
"line": "\t * but the following is good enough as IP options are not often used.\n"
},
{
"line_no": 28,
"char_start": 1157,
"char_end": 1162,
"line": "\t */\n"
},
{
"line_no": 29,
"char_start": 1162,
"char_end": 1200,
"line": "\tif (unlikely(IPCB(skb)->opt.optlen))\n"
},
{
"line_no": 30,
"char_start": 1200,
"char_end": 1222,
"line": "\t\tskb_dst_force(skb);\n"
},
{
"line_no": 31,
"char_start": 1222,
"char_end": 1228,
"line": "\telse\n"
},
{
"line_no": 32,
"char_start": 1228,
"char_end": 1249,
"line": "\t\tskb_dst_drop(skb);\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 973,
"char_end": 1230,
"chars": "/* We need to keep the dst for __ip_options_echo()\n\t * We could restrict the test to opt.ts_needtime || opt.srr,\n\t * but the following is good enough as IP options are not often used.\n\t */\n\tif (unlikely(IPCB(skb)->opt.optlen))\n\t\tskb_dst_force(skb);\n\telse\n\t\t"
}
]
} | github.com/torvalds/linux/commit/34b2cef20f19c87999fff3da4071e66937db9644 | net/ipv4/ip_sockglue.c | cwe-476 |
dex_parse_debug_item | static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg > regsz) {
return; // this return breaks tests
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
// TODO: check when we should use source_file
// The state machine consists of five registers
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
//eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx);
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
} | static void dex_parse_debug_item(RBinFile *binfile, RBinDexObj *bin,
RBinDexClass *c, int MI, int MA, int paddr, int ins_size,
int insns_size, char *class_name, int regsz,
int debug_info_off) {
struct r_bin_t *rbin = binfile->rbin;
const ut8 *p4 = r_buf_get_at (binfile->buf, debug_info_off, NULL);
const ut8 *p4_end = p4 + binfile->buf->length - debug_info_off;
ut64 line_start;
ut64 parameters_size;
ut64 param_type_idx;
ut16 argReg = regsz - ins_size;
ut64 source_file_idx = c->source_file;
RList *params, *debug_positions, *emitted_debug_locals = NULL;
bool keep = true;
if (argReg > regsz) {
return; // this return breaks tests
}
p4 = r_uleb128 (p4, p4_end - p4, &line_start);
p4 = r_uleb128 (p4, p4_end - p4, ¶meters_size);
// TODO: check when we should use source_file
// The state machine consists of five registers
ut32 address = 0;
ut32 line = line_start;
if (!(debug_positions = r_list_newf ((RListFree)free))) {
return;
}
if (!(emitted_debug_locals = r_list_newf ((RListFree)free))) {
r_list_free (debug_positions);
return;
}
struct dex_debug_local_t debug_locals[regsz];
memset (debug_locals, 0, sizeof (struct dex_debug_local_t) * regsz);
if (!(MA & 0x0008)) {
debug_locals[argReg].name = "this";
debug_locals[argReg].descriptor = r_str_newf("%s;", class_name);
debug_locals[argReg].startAddress = 0;
debug_locals[argReg].signature = NULL;
debug_locals[argReg].live = true;
argReg++;
}
if (!(params = dex_method_signature2 (bin, MI))) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
return;
}
RListIter *iter = r_list_iterator (params);
char *name;
char *type;
int reg;
r_list_foreach (params, iter, type) {
if ((argReg >= regsz) || !type || parameters_size <= 0) {
r_list_free (debug_positions);
r_list_free (params);
r_list_free (emitted_debug_locals);
return;
}
p4 = r_uleb128 (p4, p4_end - p4, ¶m_type_idx); // read uleb128p1
param_type_idx -= 1;
name = getstr (bin, param_type_idx);
reg = argReg;
switch (type[0]) {
case 'D':
case 'J':
argReg += 2;
break;
default:
argReg += 1;
break;
}
if (name) {
debug_locals[reg].name = name;
debug_locals[reg].descriptor = type;
debug_locals[reg].signature = NULL;
debug_locals[reg].startAddress = address;
debug_locals[reg].live = true;
}
--parameters_size;
}
if (p4 <= 0) {
return;
}
ut8 opcode = *(p4++) & 0xff;
while (keep) {
switch (opcode) {
case 0x0: // DBG_END_SEQUENCE
keep = false;
break;
case 0x1: // DBG_ADVANCE_PC
{
ut64 addr_diff;
p4 = r_uleb128 (p4, p4_end - p4, &addr_diff);
address += addr_diff;
}
break;
case 0x2: // DBG_ADVANCE_LINE
{
st64 line_diff = r_sleb128 (&p4, p4_end);
line += line_diff;
}
break;
case 0x3: // DBG_START_LOCAL
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = NULL;
debug_locals[register_num].live = true;
//eprintf("DBG_START_LOCAL %x %x %x\n", register_num, name_idx, type_idx);
}
break;
case 0x4: //DBG_START_LOCAL_EXTENDED
{
ut64 register_num;
ut64 name_idx;
ut64 type_idx;
ut64 sig_idx;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
p4 = r_uleb128 (p4, p4_end - p4, &name_idx);
name_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &type_idx);
type_idx -= 1;
p4 = r_uleb128 (p4, p4_end - p4, &sig_idx);
sig_idx -= 1;
if (register_num >= regsz) {
r_list_free (debug_positions);
r_list_free (params);
return;
}
// Emit what was previously there, if anything
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].name = getstr (bin, name_idx);
debug_locals[register_num].descriptor = dex_type_descriptor (bin, type_idx);
debug_locals[register_num].startAddress = address;
debug_locals[register_num].signature = getstr (bin, sig_idx);
debug_locals[register_num].live = true;
}
break;
case 0x5: // DBG_END_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
// emitLocalCbIfLive
if (debug_locals[register_num].live) {
struct dex_debug_local_t *local = malloc (
sizeof (struct dex_debug_local_t));
if (!local) {
keep = false;
break;
}
local->name = debug_locals[register_num].name;
local->descriptor = debug_locals[register_num].descriptor;
local->startAddress = debug_locals[register_num].startAddress;
local->signature = debug_locals[register_num].signature;
local->live = true;
local->reg = register_num;
local->endAddress = address;
r_list_append (emitted_debug_locals, local);
}
debug_locals[register_num].live = false;
}
break;
case 0x6: // DBG_RESTART_LOCAL
{
ut64 register_num;
p4 = r_uleb128 (p4, p4_end - p4, ®ister_num);
if (!debug_locals[register_num].live) {
debug_locals[register_num].startAddress = address;
debug_locals[register_num].live = true;
}
}
break;
case 0x7: //DBG_SET_PROLOGUE_END
break;
case 0x8: //DBG_SET_PROLOGUE_BEGIN
break;
case 0x9:
{
p4 = r_uleb128 (p4, p4_end - p4, &source_file_idx);
source_file_idx--;
}
break;
default:
{
int adjusted_opcode = opcode - 0x0a;
address += (adjusted_opcode / 15);
line += -4 + (adjusted_opcode % 15);
struct dex_debug_position_t *position =
malloc (sizeof (struct dex_debug_position_t));
if (!position) {
keep = false;
break;
}
position->source_file_idx = source_file_idx;
position->address = address;
position->line = line;
r_list_append (debug_positions, position);
}
break;
}
opcode = *(p4++) & 0xff;
}
if (!binfile->sdb_addrinfo) {
binfile->sdb_addrinfo = sdb_new0 ();
}
char *fileline;
char offset[64];
char *offset_ptr;
RListIter *iter1;
struct dex_debug_position_t *pos;
r_list_foreach (debug_positions, iter1, pos) {
fileline = r_str_newf ("%s|%"PFMT64d, getstr (bin, pos->source_file_idx), pos->line);
offset_ptr = sdb_itoa (pos->address + paddr, offset, 16);
sdb_set (binfile->sdb_addrinfo, offset_ptr, fileline, 0);
sdb_set (binfile->sdb_addrinfo, fileline, offset_ptr, 0);
}
if (!dexdump) {
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
return;
}
RListIter *iter2;
struct dex_debug_position_t *position;
rbin->cb_printf (" positions :\n");
r_list_foreach (debug_positions, iter2, position) {
rbin->cb_printf (" 0x%04llx line=%llu\n",
position->address, position->line);
}
rbin->cb_printf (" locals :\n");
RListIter *iter3;
struct dex_debug_local_t *local;
r_list_foreach (emitted_debug_locals, iter3, local) {
if (local->signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor,
local->signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s\n",
local->startAddress, local->endAddress,
local->reg, local->name, local->descriptor);
}
}
for (reg = 0; reg < regsz; reg++) {
if (debug_locals[reg].live) {
if (debug_locals[reg].signature) {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s "
"%s\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor,
debug_locals[reg].signature);
} else {
rbin->cb_printf (
" 0x%04x - 0x%04x reg=%d %s %s"
"\n",
debug_locals[reg].startAddress,
insns_size, reg, debug_locals[reg].name,
debug_locals[reg].descriptor);
}
}
}
r_list_free (debug_positions);
r_list_free (emitted_debug_locals);
r_list_free (params);
} | {
"deleted": [],
"added": [
{
"line_no": 83,
"char_start": 2398,
"char_end": 2414,
"line": "\tif (p4 <= 0) {\n"
},
{
"line_no": 84,
"char_start": 2414,
"char_end": 2424,
"line": "\t\treturn;\n"
},
{
"line_no": 85,
"char_start": 2424,
"char_end": 2427,
"line": "\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2399,
"char_end": 2428,
"chars": "if (p4 <= 0) {\n\t\treturn;\n\t}\n\t"
}
]
} | github.com/radare/radare2/commit/252afb1cff9676f3ae1f341a28448bf2c8b6e308 | libr/bin/p/bin_dex.c | cwe-476 |
rds_cmsg_atomic | int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,
struct cmsghdr *cmsg)
{
struct page *page = NULL;
struct rds_atomic_args *args;
int ret = 0;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))
|| rm->atomic.op_active)
return -EINVAL;
args = CMSG_DATA(cmsg);
/* Nonmasked & masked cmsg ops converted to masked hw ops */
switch (cmsg->cmsg_type) {
case RDS_CMSG_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = 0;
break;
case RDS_CMSG_MASKED_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->m_fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;
break;
case RDS_CMSG_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->cswp.compare;
rm->atomic.op_m_cswp.swap = args->cswp.swap;
rm->atomic.op_m_cswp.compare_mask = ~0;
rm->atomic.op_m_cswp.swap_mask = ~0;
break;
case RDS_CMSG_MASKED_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->m_cswp.compare;
rm->atomic.op_m_cswp.swap = args->m_cswp.swap;
rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;
rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;
break;
default:
BUG(); /* should never happen */
}
rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);
rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);
rm->atomic.op_active = 1;
rm->atomic.op_recverr = rs->rs_recverr;
rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);
if (!rm->atomic.op_sg) {
ret = -ENOMEM;
goto err;
}
/* verify 8 byte-aligned */
if (args->local_addr & 0x7) {
ret = -EFAULT;
goto err;
}
ret = rds_pin_pages(args->local_addr, 1, &page, 1);
if (ret != 1)
goto err;
ret = 0;
sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
if (rm->atomic.op_notify || rm->atomic.op_recverr) {
/* We allocate an uninitialized notifier here, because
* we don't want to do that in the completion handler. We
* would have to use GFP_ATOMIC there, and don't want to deal
* with failed allocations.
*/
rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);
if (!rm->atomic.op_notifier) {
ret = -ENOMEM;
goto err;
}
rm->atomic.op_notifier->n_user_token = args->user_token;
rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;
}
rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);
rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);
return ret;
err:
if (page)
put_page(page);
kfree(rm->atomic.op_notifier);
return ret;
} | int rds_cmsg_atomic(struct rds_sock *rs, struct rds_message *rm,
struct cmsghdr *cmsg)
{
struct page *page = NULL;
struct rds_atomic_args *args;
int ret = 0;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct rds_atomic_args))
|| rm->atomic.op_active)
return -EINVAL;
args = CMSG_DATA(cmsg);
/* Nonmasked & masked cmsg ops converted to masked hw ops */
switch (cmsg->cmsg_type) {
case RDS_CMSG_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = 0;
break;
case RDS_CMSG_MASKED_ATOMIC_FADD:
rm->atomic.op_type = RDS_ATOMIC_TYPE_FADD;
rm->atomic.op_m_fadd.add = args->m_fadd.add;
rm->atomic.op_m_fadd.nocarry_mask = args->m_fadd.nocarry_mask;
break;
case RDS_CMSG_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->cswp.compare;
rm->atomic.op_m_cswp.swap = args->cswp.swap;
rm->atomic.op_m_cswp.compare_mask = ~0;
rm->atomic.op_m_cswp.swap_mask = ~0;
break;
case RDS_CMSG_MASKED_ATOMIC_CSWP:
rm->atomic.op_type = RDS_ATOMIC_TYPE_CSWP;
rm->atomic.op_m_cswp.compare = args->m_cswp.compare;
rm->atomic.op_m_cswp.swap = args->m_cswp.swap;
rm->atomic.op_m_cswp.compare_mask = args->m_cswp.compare_mask;
rm->atomic.op_m_cswp.swap_mask = args->m_cswp.swap_mask;
break;
default:
BUG(); /* should never happen */
}
rm->atomic.op_notify = !!(args->flags & RDS_RDMA_NOTIFY_ME);
rm->atomic.op_silent = !!(args->flags & RDS_RDMA_SILENT);
rm->atomic.op_active = 1;
rm->atomic.op_recverr = rs->rs_recverr;
rm->atomic.op_sg = rds_message_alloc_sgs(rm, 1);
if (!rm->atomic.op_sg) {
ret = -ENOMEM;
goto err;
}
/* verify 8 byte-aligned */
if (args->local_addr & 0x7) {
ret = -EFAULT;
goto err;
}
ret = rds_pin_pages(args->local_addr, 1, &page, 1);
if (ret != 1)
goto err;
ret = 0;
sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
if (rm->atomic.op_notify || rm->atomic.op_recverr) {
/* We allocate an uninitialized notifier here, because
* we don't want to do that in the completion handler. We
* would have to use GFP_ATOMIC there, and don't want to deal
* with failed allocations.
*/
rm->atomic.op_notifier = kmalloc(sizeof(*rm->atomic.op_notifier), GFP_KERNEL);
if (!rm->atomic.op_notifier) {
ret = -ENOMEM;
goto err;
}
rm->atomic.op_notifier->n_user_token = args->user_token;
rm->atomic.op_notifier->n_status = RDS_RDMA_SUCCESS;
}
rm->atomic.op_rkey = rds_rdma_cookie_key(args->cookie);
rm->atomic.op_remote_addr = args->remote_addr + rds_rdma_cookie_offset(args->cookie);
return ret;
err:
if (page)
put_page(page);
rm->atomic.op_active = 0;
kfree(rm->atomic.op_notifier);
return ret;
} | {
"deleted": [],
"added": [
{
"line_no": 90,
"char_start": 2680,
"char_end": 2707,
"line": "\trm->atomic.op_active = 0;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2681,
"char_end": 2708,
"chars": "rm->atomic.op_active = 0;\n\t"
}
]
} | github.com/torvalds/linux/commit/7d11f77f84b27cef452cee332f4e469503084737 | net/rds/rdma.c | cwe-476 |
AP4_AtomFactory::CreateAtomFromStream | AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_UI32 type,
AP4_UI32 size_32,
AP4_UI64 size_64,
AP4_Atom*& atom)
{
bool atom_is_large = (size_32 == 1);
bool force_64 = (size_32==1 && ((size_64>>32) == 0));
// create the atom
if (GetContext() == AP4_ATOM_TYPE_STSD) {
// sample entry
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
switch (type) {
case AP4_ATOM_TYPE_MP4A:
atom = new AP4_Mp4aSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4V:
atom = new AP4_Mp4vSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4S:
atom = new AP4_Mp4sSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCA:
atom = new AP4_EncaSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCV:
atom = new AP4_EncvSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMS:
atom = new AP4_DrmsSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMI:
atom = new AP4_DrmiSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_AVC1:
case AP4_ATOM_TYPE_AVC2:
case AP4_ATOM_TYPE_AVC3:
case AP4_ATOM_TYPE_AVC4:
case AP4_ATOM_TYPE_DVAV:
case AP4_ATOM_TYPE_DVA1:
atom = new AP4_AvcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_HEV1:
case AP4_ATOM_TYPE_HVC1:
case AP4_ATOM_TYPE_DVHE:
case AP4_ATOM_TYPE_DVH1:
atom = new AP4_HevcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ALAC:
case AP4_ATOM_TYPE_AC_3:
case AP4_ATOM_TYPE_EC_3:
case AP4_ATOM_TYPE_DTSC:
case AP4_ATOM_TYPE_DTSH:
case AP4_ATOM_TYPE_DTSL:
case AP4_ATOM_TYPE_DTSE:
atom = new AP4_AudioSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
atom = new AP4_RtpHintSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STPP:
atom = new AP4_SubtitleSampleEntry(type, size_32, stream, *this);
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
// no custom handler, create a generic entry
if (atom == NULL) {
atom = new AP4_UnknownSampleEntry(type, (AP4_UI32)size_64, stream);
}
break;
}
}
} else {
// regular atom
switch (type) {
case AP4_ATOM_TYPE_MOOV:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MoovAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MVHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MvhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MEHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MehdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRAK:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrakAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_TREX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrexAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HDLR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HdlrAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TKHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TkhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRUN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrunAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFRA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfraAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfroAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MDHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MdhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StsdAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STSC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StscAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STCO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StcoAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CO64:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Co64Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StszAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STZ2:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Stz2Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CTTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_CttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StssAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IODS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IodsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ESDS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_EsdsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
atom->SetType(AP4_ATOM_TYPE_HVCE);
break;
case AP4_ATOM_TYPE_AVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
atom->SetType(AP4_ATOM_TYPE_AVCE);
break;
#if !defined(AP4_CONFIG_MINI_BUILD)
case AP4_ATOM_TYPE_UUID: {
AP4_UI08 uuid[16];
AP4_Result result = stream.Read(uuid, 16);
if (AP4_FAILED(result)) return result;
if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffTrackEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffSampleEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else {
atom = new AP4_UnknownUuidAtom(size_64, uuid, stream);
}
break;
}
case AP4_ATOM_TYPE_8ID_:
atom = new AP4_NullTerminatedStringAtom(type, size_64, stream);
break;
case AP4_ATOM_TYPE_8BDL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_8bdlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DREF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DrefAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_URL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_UrlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ELST:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ElstAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_VMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_VmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_NMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_NmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SthdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_FRMA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FrmaAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SCHM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SchmAtom::Create(size_32, &m_ContextStack, stream);
break;
case AP4_ATOM_TYPE_FTYP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FtypAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TIMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TimsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SDP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SdpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IKMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IkmsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISFM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsfmAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISLT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsltAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ODHE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdheAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_OHDR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OhdrAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ODDA:
atom = AP4_OddaAtom::Create(size_64, stream);
break;
case AP4_ATOM_TYPE_ODAF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdafAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_GRPI:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_GrpiAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IPRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IproAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_RtpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFDT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfdtAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaizAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaioAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PDIN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PdinAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_BLOC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_BlocAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AINF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AinfAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PSSH:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PsshAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SIDX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SidxAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SBGP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SbgpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SGPD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SgpdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MKID:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_MARL) {
atom = AP4_MkidAtom::Create(size_32, stream);
}
break;
case AP4_ATOM_TYPE_DEC3:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_EC_3 || GetContext() == AP4_ATOM_TYPE_ENCA) {
atom = AP4_Dec3Atom::Create(size_32, stream);
}
break;
// track ref types
case AP4_ATOM_TYPE_HINT:
case AP4_ATOM_TYPE_CDSC:
case AP4_ATOM_TYPE_SYNC:
case AP4_ATOM_TYPE_MPOD:
case AP4_ATOM_TYPE_DPND:
case AP4_ATOM_TYPE_IPIR:
case AP4_ATOM_TYPE_ALIS:
case AP4_ATOM_TYPE_CHAP:
if (GetContext() == AP4_ATOM_TYPE_TREF) {
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrefTypeAtom::Create(type, size_32, stream);
}
break;
#endif // AP4_CONFIG_MINI_BUILD
// container atoms
case AP4_ATOM_TYPE_MOOF:
case AP4_ATOM_TYPE_MVEX:
case AP4_ATOM_TYPE_TRAF:
case AP4_ATOM_TYPE_TREF:
case AP4_ATOM_TYPE_MFRA:
case AP4_ATOM_TYPE_HNTI:
case AP4_ATOM_TYPE_STBL:
case AP4_ATOM_TYPE_MDIA:
case AP4_ATOM_TYPE_DINF:
case AP4_ATOM_TYPE_MINF:
case AP4_ATOM_TYPE_SCHI:
case AP4_ATOM_TYPE_SINF:
case AP4_ATOM_TYPE_UDTA:
case AP4_ATOM_TYPE_ILST:
case AP4_ATOM_TYPE_EDTS:
case AP4_ATOM_TYPE_MDRI:
case AP4_ATOM_TYPE_WAVE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
break;
// containers, only at the top
case AP4_ATOM_TYPE_MARL:
if (GetContext() == 0) {
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
}
break;
// full container atoms
case AP4_ATOM_TYPE_META:
case AP4_ATOM_TYPE_ODRM:
case AP4_ATOM_TYPE_ODKM:
atom = AP4_ContainerAtom::Create(type, size_64, true, force_64, stream, *this);
break;
case AP4_ATOM_TYPE_FREE:
case AP4_ATOM_TYPE_WIDE:
case AP4_ATOM_TYPE_MDAT:
// generic atoms
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
break;
}
}
}
return AP4_SUCCESS;
} | AP4_AtomFactory::CreateAtomFromStream(AP4_ByteStream& stream,
AP4_UI32 type,
AP4_UI32 size_32,
AP4_UI64 size_64,
AP4_Atom*& atom)
{
bool atom_is_large = (size_32 == 1);
bool force_64 = (size_32==1 && ((size_64>>32) == 0));
// create the atom
if (GetContext() == AP4_ATOM_TYPE_STSD) {
// sample entry
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
switch (type) {
case AP4_ATOM_TYPE_MP4A:
atom = new AP4_Mp4aSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4V:
atom = new AP4_Mp4vSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MP4S:
atom = new AP4_Mp4sSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCA:
atom = new AP4_EncaSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ENCV:
atom = new AP4_EncvSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMS:
atom = new AP4_DrmsSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_DRMI:
atom = new AP4_DrmiSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_AVC1:
case AP4_ATOM_TYPE_AVC2:
case AP4_ATOM_TYPE_AVC3:
case AP4_ATOM_TYPE_AVC4:
case AP4_ATOM_TYPE_DVAV:
case AP4_ATOM_TYPE_DVA1:
atom = new AP4_AvcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_HEV1:
case AP4_ATOM_TYPE_HVC1:
case AP4_ATOM_TYPE_DVHE:
case AP4_ATOM_TYPE_DVH1:
atom = new AP4_HevcSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ALAC:
case AP4_ATOM_TYPE_AC_3:
case AP4_ATOM_TYPE_EC_3:
case AP4_ATOM_TYPE_DTSC:
case AP4_ATOM_TYPE_DTSH:
case AP4_ATOM_TYPE_DTSL:
case AP4_ATOM_TYPE_DTSE:
atom = new AP4_AudioSampleEntry(type, size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
atom = new AP4_RtpHintSampleEntry(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STPP:
atom = new AP4_SubtitleSampleEntry(type, size_32, stream, *this);
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
// no custom handler, create a generic entry
if (atom == NULL) {
atom = new AP4_UnknownSampleEntry(type, (AP4_UI32)size_64, stream);
}
break;
}
}
} else {
// regular atom
switch (type) {
case AP4_ATOM_TYPE_MOOV:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MoovAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_MVHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MvhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MEHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MehdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRAK:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrakAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_TREX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrexAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HDLR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HdlrAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TKHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TkhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TRUN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrunAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFRA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfraAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MFRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MfroAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MDHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_MdhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StsdAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_STSC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StscAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STCO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StcoAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CO64:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Co64Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StszAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STZ2:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_Stz2Atom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_CTTS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_CttsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STSS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_StssAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IODS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IodsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ESDS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_EsdsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DVCC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DvccAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HvccAtom::Create(size_32, stream);
if (atom) {
atom->SetType(AP4_ATOM_TYPE_HVCE);
}
break;
case AP4_ATOM_TYPE_AVCE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AvccAtom::Create(size_32, stream);
if (atom) {
atom->SetType(AP4_ATOM_TYPE_AVCE);
}
break;
#if !defined(AP4_CONFIG_MINI_BUILD)
case AP4_ATOM_TYPE_UUID: {
AP4_UI08 uuid[16];
AP4_Result result = stream.Read(uuid, 16);
if (AP4_FAILED(result)) return result;
if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_TRACK_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffTrackEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else if (AP4_CompareMemory(uuid, AP4_UUID_PIFF_SAMPLE_ENCRYPTION_ATOM, 16) == 0) {
atom = AP4_PiffSampleEncryptionAtom::Create((AP4_UI32)size_64, stream);
} else {
atom = new AP4_UnknownUuidAtom(size_64, uuid, stream);
}
break;
}
case AP4_ATOM_TYPE_8ID_:
atom = new AP4_NullTerminatedStringAtom(type, size_64, stream);
break;
case AP4_ATOM_TYPE_8BDL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_8bdlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_DREF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_DrefAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_URL:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_UrlAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ELST:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ElstAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_VMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_VmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_NMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_NmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_STHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SthdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_HMHD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_HmhdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_FRMA:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FrmaAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SCHM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SchmAtom::Create(size_32, &m_ContextStack, stream);
break;
case AP4_ATOM_TYPE_FTYP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_FtypAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TIMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TimsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SDP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SdpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IKMS:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IkmsAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISFM:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsfmAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ISLT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IsltAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_ODHE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdheAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_OHDR:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OhdrAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_ODDA:
atom = AP4_OddaAtom::Create(size_64, stream);
break;
case AP4_ATOM_TYPE_ODAF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_OdafAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_GRPI:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_GrpiAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_IPRO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_IproAtom::Create(size_32, stream, *this);
break;
case AP4_ATOM_TYPE_RTP_:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_RtpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TFDT:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TfdtAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_TENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SENC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SencAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIZ:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaizAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SAIO:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SaioAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PDIN:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PdinAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_BLOC:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_BlocAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_AINF:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_AinfAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_PSSH:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_PsshAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SIDX:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SidxAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SBGP:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SbgpAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_SGPD:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_SgpdAtom::Create(size_32, stream);
break;
case AP4_ATOM_TYPE_MKID:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_MARL) {
atom = AP4_MkidAtom::Create(size_32, stream);
}
break;
case AP4_ATOM_TYPE_DEC3:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
if (GetContext() == AP4_ATOM_TYPE_EC_3 || GetContext() == AP4_ATOM_TYPE_ENCA) {
atom = AP4_Dec3Atom::Create(size_32, stream);
}
break;
// track ref types
case AP4_ATOM_TYPE_HINT:
case AP4_ATOM_TYPE_CDSC:
case AP4_ATOM_TYPE_SYNC:
case AP4_ATOM_TYPE_MPOD:
case AP4_ATOM_TYPE_DPND:
case AP4_ATOM_TYPE_IPIR:
case AP4_ATOM_TYPE_ALIS:
case AP4_ATOM_TYPE_CHAP:
if (GetContext() == AP4_ATOM_TYPE_TREF) {
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_TrefTypeAtom::Create(type, size_32, stream);
}
break;
#endif // AP4_CONFIG_MINI_BUILD
// container atoms
case AP4_ATOM_TYPE_MOOF:
case AP4_ATOM_TYPE_MVEX:
case AP4_ATOM_TYPE_TRAF:
case AP4_ATOM_TYPE_TREF:
case AP4_ATOM_TYPE_MFRA:
case AP4_ATOM_TYPE_HNTI:
case AP4_ATOM_TYPE_STBL:
case AP4_ATOM_TYPE_MDIA:
case AP4_ATOM_TYPE_DINF:
case AP4_ATOM_TYPE_MINF:
case AP4_ATOM_TYPE_SCHI:
case AP4_ATOM_TYPE_SINF:
case AP4_ATOM_TYPE_UDTA:
case AP4_ATOM_TYPE_ILST:
case AP4_ATOM_TYPE_EDTS:
case AP4_ATOM_TYPE_MDRI:
case AP4_ATOM_TYPE_WAVE:
if (atom_is_large) return AP4_ERROR_INVALID_FORMAT;
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
break;
// containers, only at the top
case AP4_ATOM_TYPE_MARL:
if (GetContext() == 0) {
atom = AP4_ContainerAtom::Create(type, size_64, false, force_64, stream, *this);
}
break;
// full container atoms
case AP4_ATOM_TYPE_META:
case AP4_ATOM_TYPE_ODRM:
case AP4_ATOM_TYPE_ODKM:
atom = AP4_ContainerAtom::Create(type, size_64, true, force_64, stream, *this);
break;
case AP4_ATOM_TYPE_FREE:
case AP4_ATOM_TYPE_WIDE:
case AP4_ATOM_TYPE_MDAT:
// generic atoms
break;
default: {
// try all the external type handlers
AP4_List<TypeHandler>::Item* handler_item = m_TypeHandlers.FirstItem();
while (handler_item) {
TypeHandler* handler = handler_item->GetData();
if (AP4_SUCCEEDED(handler->CreateAtom(type, size_32, stream, GetContext(), atom))) {
break;
}
handler_item = handler_item->GetNext();
}
break;
}
}
}
return AP4_SUCCESS;
} | {
"deleted": [
{
"line_no": 237,
"char_start": 8331,
"char_end": 8378,
"line": " atom->SetType(AP4_ATOM_TYPE_HVCE);\n"
},
{
"line_no": 243,
"char_start": 8555,
"char_end": 8602,
"line": " atom->SetType(AP4_ATOM_TYPE_AVCE);\n"
}
],
"added": [
{
"line_no": 237,
"char_start": 8331,
"char_end": 8355,
"line": " if (atom) {\n"
},
{
"line_no": 238,
"char_start": 8355,
"char_end": 8406,
"line": " atom->SetType(AP4_ATOM_TYPE_HVCE);\n"
},
{
"line_no": 239,
"char_start": 8406,
"char_end": 8420,
"line": " }\n"
},
{
"line_no": 245,
"char_start": 8597,
"char_end": 8621,
"line": " if (atom) {\n"
},
{
"line_no": 246,
"char_start": 8621,
"char_end": 8672,
"line": " atom->SetType(AP4_ATOM_TYPE_AVCE);\n"
},
{
"line_no": 247,
"char_start": 8672,
"char_end": 8686,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 8343,
"char_end": 8371,
"chars": "if (atom) {\n "
},
{
"char_start": 8405,
"char_end": 8419,
"chars": "\n }"
},
{
"char_start": 8609,
"char_end": 8637,
"chars": "if (atom) {\n "
},
{
"char_start": 8671,
"char_end": 8685,
"chars": "\n }"
}
]
} | github.com/axiomatic-systems/Bento4/commit/be7185faf7f52674028977dcf501c6039ff03aa5 | Source/C++/Core/Ap4AtomFactory.cpp | cwe-476 |
imcb_file_send_start | file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)
{
bee_t *bee = ic->bee;
bee_user_t *bu = bee_user_by_handle(bee, ic, handle);
if (bee->ui->ft_in_start) {
return bee->ui->ft_in_start(bee, bu, file_name, file_size);
} else {
return NULL;
}
} | file_transfer_t *imcb_file_send_start(struct im_connection *ic, char *handle, char *file_name, size_t file_size)
{
bee_t *bee = ic->bee;
bee_user_t *bu = bee_user_by_handle(bee, ic, handle);
if (bee->ui->ft_in_start && bu) {
return bee->ui->ft_in_start(bee, bu, file_name, file_size);
} else {
return NULL;
}
} | {
"deleted": [
{
"line_no": 6,
"char_start": 194,
"char_end": 223,
"line": "\tif (bee->ui->ft_in_start) {\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 194,
"char_end": 229,
"line": "\tif (bee->ui->ft_in_start && bu) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 219,
"char_end": 225,
"chars": " && bu"
}
]
} | github.com/bitlbee/bitlbee/commit/701ab8129ba9ea64f569daedca9a8603abad740f | protocols/bee_ft.c | cwe-476 |
mpeg4video_probe | static int mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if ((temp_buffer & 0xffffff00) != 0x100)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer < 0x120)
VO++;
else if (temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
} | static int mpeg4video_probe(AVProbeData *probe_packet)
{
uint32_t temp_buffer = -1;
int VO = 0, VOL = 0, VOP = 0, VISO = 0, res = 0;
int i;
for (i = 0; i < probe_packet->buf_size; i++) {
temp_buffer = (temp_buffer << 8) + probe_packet->buf[i];
if (temp_buffer & 0xfffffe00)
continue;
if (temp_buffer < 2)
continue;
if (temp_buffer == VOP_START_CODE)
VOP++;
else if (temp_buffer == VISUAL_OBJECT_START_CODE)
VISO++;
else if (temp_buffer >= 0x100 && temp_buffer < 0x120)
VO++;
else if (temp_buffer >= 0x120 && temp_buffer < 0x130)
VOL++;
else if (!(0x1AF < temp_buffer && temp_buffer < 0x1B7) &&
!(0x1B9 < temp_buffer && temp_buffer < 0x1C4))
res++;
}
if (VOP >= VISO && VOP >= VOL && VO >= VOL && VOL > 0 && res == 0)
return AVPROBE_SCORE_EXTENSION;
return 0;
} | {
"deleted": [
{
"line_no": 9,
"char_start": 269,
"char_end": 318,
"line": " if ((temp_buffer & 0xffffff00) != 0x100)\n"
},
{
"line_no": 16,
"char_start": 481,
"char_end": 519,
"line": " else if (temp_buffer < 0x120)\n"
},
{
"line_no": 18,
"char_start": 537,
"char_end": 575,
"line": " else if (temp_buffer < 0x130)\n"
}
],
"added": [
{
"line_no": 9,
"char_start": 269,
"char_end": 307,
"line": " if (temp_buffer & 0xfffffe00)\n"
},
{
"line_no": 10,
"char_start": 307,
"char_end": 329,
"line": " continue;\n"
},
{
"line_no": 11,
"char_start": 329,
"char_end": 358,
"line": " if (temp_buffer < 2)\n"
},
{
"line_no": 18,
"char_start": 521,
"char_end": 583,
"line": " else if (temp_buffer >= 0x100 && temp_buffer < 0x120)\n"
},
{
"line_no": 20,
"char_start": 601,
"char_end": 663,
"line": " else if (temp_buffer >= 0x120 && temp_buffer < 0x130)\n"
}
]
} | {
"deleted": [
{
"char_start": 281,
"char_end": 282,
"chars": "("
},
{
"char_start": 303,
"char_end": 304,
"chars": "f"
},
{
"char_start": 308,
"char_end": 310,
"chars": "!="
},
{
"char_start": 311,
"char_end": 316,
"chars": "0x100"
}
],
"added": [
{
"char_start": 302,
"char_end": 303,
"chars": "e"
},
{
"char_start": 306,
"char_end": 332,
"chars": "\n continue;\n "
},
{
"char_start": 333,
"char_end": 334,
"chars": " "
},
{
"char_start": 335,
"char_end": 356,
"chars": " if (temp_buffer < 2"
},
{
"char_start": 550,
"char_end": 574,
"chars": ">= 0x100 && temp_buffer "
},
{
"char_start": 618,
"char_end": 642,
"chars": "temp_buffer >= 0x120 && "
}
]
} | github.com/libav/libav/commit/e5b019725f53b79159931d3a7317107cbbfd0860 | libavformat/m4vdec.c | cwe-476 |
megasas_alloc_cmds | int megasas_alloc_cmds(struct megasas_instance *instance)
{
int i;
int j;
u16 max_cmd;
struct megasas_cmd *cmd;
max_cmd = instance->max_mfi_cmds;
/*
* instance->cmd_list is an array of struct megasas_cmd pointers.
* Allocate the dynamic array first and then allocate individual
* commands.
*/
instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
if (!instance->cmd_list) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
return -ENOMEM;
}
memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
for (i = 0; i < max_cmd; i++) {
instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
GFP_KERNEL);
if (!instance->cmd_list[i]) {
for (j = 0; j < i; j++)
kfree(instance->cmd_list[j]);
kfree(instance->cmd_list);
instance->cmd_list = NULL;
return -ENOMEM;
}
}
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
memset(cmd, 0, sizeof(struct megasas_cmd));
cmd->index = i;
cmd->scmd = NULL;
cmd->instance = instance;
list_add_tail(&cmd->list, &instance->cmd_pool);
}
/*
* Create a frame pool and assign one frame to each cmd
*/
if (megasas_create_frame_pool(instance)) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
megasas_free_cmds(instance);
}
return 0;
} | int megasas_alloc_cmds(struct megasas_instance *instance)
{
int i;
int j;
u16 max_cmd;
struct megasas_cmd *cmd;
max_cmd = instance->max_mfi_cmds;
/*
* instance->cmd_list is an array of struct megasas_cmd pointers.
* Allocate the dynamic array first and then allocate individual
* commands.
*/
instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
if (!instance->cmd_list) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "out of memory\n");
return -ENOMEM;
}
memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
for (i = 0; i < max_cmd; i++) {
instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
GFP_KERNEL);
if (!instance->cmd_list[i]) {
for (j = 0; j < i; j++)
kfree(instance->cmd_list[j]);
kfree(instance->cmd_list);
instance->cmd_list = NULL;
return -ENOMEM;
}
}
for (i = 0; i < max_cmd; i++) {
cmd = instance->cmd_list[i];
memset(cmd, 0, sizeof(struct megasas_cmd));
cmd->index = i;
cmd->scmd = NULL;
cmd->instance = instance;
list_add_tail(&cmd->list, &instance->cmd_pool);
}
/*
* Create a frame pool and assign one frame to each cmd
*/
if (megasas_create_frame_pool(instance)) {
dev_printk(KERN_DEBUG, &instance->pdev->dev, "Error creating frame DMA pool\n");
megasas_free_cmds(instance);
return -ENOMEM;
}
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 56,
"char_start": 1333,
"char_end": 1351,
"line": "\t\treturn -ENOMEM;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1334,
"char_end": 1352,
"chars": "\treturn -ENOMEM;\n\t"
}
]
} | github.com/torvalds/linux/commit/bcf3b67d16a4c8ffae0aa79de5853435e683945c | drivers/scsi/megaraid/megaraid_sas_base.c | cwe-476 |
IRC_PROTOCOL_CALLBACK | IRC_PROTOCOL_CALLBACK(352)
{
char *pos_attr, *pos_hopcount, *pos_realname, *str_host;
int arg_start, length;
struct t_irc_channel *ptr_channel;
struct t_irc_nick *ptr_nick;
IRC_PROTOCOL_MIN_ARGS(5);
/* silently ignore malformed 352 message (missing infos) */
if (argc < 8)
return WEECHAT_RC_OK;
pos_attr = NULL;
pos_hopcount = NULL;
pos_realname = NULL;
if (argc > 8)
{
arg_start = (strcmp (argv[8], "*") == 0) ? 9 : 8;
if (argv[arg_start][0] == ':')
{
pos_attr = NULL;
pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL;
pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL;
}
else
{
pos_attr = argv[arg_start];
pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL;
pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL;
}
}
ptr_channel = irc_channel_search (server, argv[3]);
ptr_nick = (ptr_channel) ?
irc_nick_search (server, ptr_channel, argv[7]) : NULL;
/* update host in nick */
if (ptr_nick)
{
length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1;
str_host = malloc (length);
if (str_host)
{
snprintf (str_host, length, "%s@%s", argv[4], argv[5]);
irc_nick_set_host (ptr_nick, str_host);
free (str_host);
}
}
/* update away flag in nick */
if (ptr_channel && ptr_nick && pos_attr)
{
irc_nick_set_away (server, ptr_channel, ptr_nick,
(pos_attr[0] == 'G') ? 1 : 0);
}
/* update realname in nick */
if (ptr_channel && ptr_nick && pos_realname)
{
if (ptr_nick->realname)
free (ptr_nick->realname);
if (pos_realname &&
weechat_hashtable_has_key (server->cap_list, "extended-join"))
{
ptr_nick->realname = strdup (pos_realname);
}
else
{
ptr_nick->realname = NULL;
}
}
/* display output of who (manual who from user) */
if (!ptr_channel || (ptr_channel->checking_whox <= 0))
{
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, NULL, command, "who", NULL),
date,
irc_protocol_tags (command, "irc_numeric", NULL, NULL),
"%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)",
weechat_prefix ("network"),
IRC_COLOR_CHAT_DELIMITERS,
IRC_COLOR_CHAT_CHANNEL,
argv[3],
IRC_COLOR_CHAT_DELIMITERS,
irc_nick_color_for_msg (server, 1, NULL, argv[7]),
argv[7],
IRC_COLOR_CHAT_DELIMITERS,
IRC_COLOR_CHAT_HOST,
argv[4],
argv[5],
IRC_COLOR_CHAT_DELIMITERS,
IRC_COLOR_RESET,
(pos_attr) ? pos_attr : "",
(pos_attr) ? " " : "",
(pos_hopcount) ? pos_hopcount : "",
(pos_hopcount) ? " " : "",
(pos_realname) ? pos_realname : "");
}
return WEECHAT_RC_OK;
} | IRC_PROTOCOL_CALLBACK(352)
{
char *pos_attr, *pos_hopcount, *pos_realname, *str_host;
int arg_start, length;
struct t_irc_channel *ptr_channel;
struct t_irc_nick *ptr_nick;
IRC_PROTOCOL_MIN_ARGS(5);
/* silently ignore malformed 352 message (missing infos) */
if (argc < 8)
return WEECHAT_RC_OK;
pos_attr = NULL;
pos_hopcount = NULL;
pos_realname = NULL;
if (argc > 8)
{
arg_start = ((argc > 9) && (strcmp (argv[8], "*") == 0)) ? 9 : 8;
if (argv[arg_start][0] == ':')
{
pos_attr = NULL;
pos_hopcount = (argc > arg_start) ? argv[arg_start] + 1 : NULL;
pos_realname = (argc > arg_start + 1) ? argv_eol[arg_start + 1] : NULL;
}
else
{
pos_attr = argv[arg_start];
pos_hopcount = (argc > arg_start + 1) ? argv[arg_start + 1] + 1 : NULL;
pos_realname = (argc > arg_start + 2) ? argv_eol[arg_start + 2] : NULL;
}
}
ptr_channel = irc_channel_search (server, argv[3]);
ptr_nick = (ptr_channel) ?
irc_nick_search (server, ptr_channel, argv[7]) : NULL;
/* update host in nick */
if (ptr_nick)
{
length = strlen (argv[4]) + 1 + strlen (argv[5]) + 1;
str_host = malloc (length);
if (str_host)
{
snprintf (str_host, length, "%s@%s", argv[4], argv[5]);
irc_nick_set_host (ptr_nick, str_host);
free (str_host);
}
}
/* update away flag in nick */
if (ptr_channel && ptr_nick && pos_attr)
{
irc_nick_set_away (server, ptr_channel, ptr_nick,
(pos_attr[0] == 'G') ? 1 : 0);
}
/* update realname in nick */
if (ptr_channel && ptr_nick && pos_realname)
{
if (ptr_nick->realname)
free (ptr_nick->realname);
if (pos_realname &&
weechat_hashtable_has_key (server->cap_list, "extended-join"))
{
ptr_nick->realname = strdup (pos_realname);
}
else
{
ptr_nick->realname = NULL;
}
}
/* display output of who (manual who from user) */
if (!ptr_channel || (ptr_channel->checking_whox <= 0))
{
weechat_printf_date_tags (
irc_msgbuffer_get_target_buffer (
server, NULL, command, "who", NULL),
date,
irc_protocol_tags (command, "irc_numeric", NULL, NULL),
"%s%s[%s%s%s] %s%s %s(%s%s@%s%s)%s %s%s%s%s(%s)",
weechat_prefix ("network"),
IRC_COLOR_CHAT_DELIMITERS,
IRC_COLOR_CHAT_CHANNEL,
argv[3],
IRC_COLOR_CHAT_DELIMITERS,
irc_nick_color_for_msg (server, 1, NULL, argv[7]),
argv[7],
IRC_COLOR_CHAT_DELIMITERS,
IRC_COLOR_CHAT_HOST,
argv[4],
argv[5],
IRC_COLOR_CHAT_DELIMITERS,
IRC_COLOR_RESET,
(pos_attr) ? pos_attr : "",
(pos_attr) ? " " : "",
(pos_hopcount) ? pos_hopcount : "",
(pos_hopcount) ? " " : "",
(pos_realname) ? pos_realname : "");
}
return WEECHAT_RC_OK;
} | {
"deleted": [
{
"line_no": 20,
"char_start": 430,
"char_end": 488,
"line": " arg_start = (strcmp (argv[8], \"*\") == 0) ? 9 : 8;\n"
}
],
"added": [
{
"line_no": 20,
"char_start": 430,
"char_end": 504,
"line": " arg_start = ((argc > 9) && (strcmp (argv[8], \"*\") == 0)) ? 9 : 8;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 451,
"char_end": 466,
"chars": "(argc > 9) && ("
},
{
"char_start": 492,
"char_end": 493,
"chars": ")"
}
]
} | github.com/weechat/weechat/commit/9904cb6d2eb40f679d8ff6557c22d53a3e3dc75a | src/plugins/irc/irc-protocol.c | cwe-476 |
xfs_attr_shortform_to_leaf | xfs_attr_shortform_to_leaf(
struct xfs_da_args *args,
struct xfs_buf **leaf_bp)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == -EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
error = xfs_da_shrink_inode(args, 0, bp);
bp = NULL;
if (error)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.geo = args->geo;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == -ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != -ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
*leaf_bp = bp;
out:
kmem_free(tmpbuffer);
return error;
} | xfs_attr_shortform_to_leaf(
struct xfs_da_args *args,
struct xfs_buf **leaf_bp)
{
xfs_inode_t *dp;
xfs_attr_shortform_t *sf;
xfs_attr_sf_entry_t *sfe;
xfs_da_args_t nargs;
char *tmpbuffer;
int error, i, size;
xfs_dablk_t blkno;
struct xfs_buf *bp;
xfs_ifork_t *ifp;
trace_xfs_attr_sf_to_leaf(args);
dp = args->dp;
ifp = dp->i_afp;
sf = (xfs_attr_shortform_t *)ifp->if_u1.if_data;
size = be16_to_cpu(sf->hdr.totsize);
tmpbuffer = kmem_alloc(size, KM_SLEEP);
ASSERT(tmpbuffer != NULL);
memcpy(tmpbuffer, ifp->if_u1.if_data, size);
sf = (xfs_attr_shortform_t *)tmpbuffer;
xfs_idata_realloc(dp, -size, XFS_ATTR_FORK);
xfs_bmap_local_to_extents_empty(dp, XFS_ATTR_FORK);
bp = NULL;
error = xfs_da_grow_inode(args, &blkno);
if (error) {
/*
* If we hit an IO error middle of the transaction inside
* grow_inode(), we may have inconsistent data. Bail out.
*/
if (error == -EIO)
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
ASSERT(blkno == 0);
error = xfs_attr3_leaf_create(args, blkno, &bp);
if (error) {
/* xfs_attr3_leaf_create may not have instantiated a block */
if (bp && (xfs_da_shrink_inode(args, 0, bp) != 0))
goto out;
xfs_idata_realloc(dp, size, XFS_ATTR_FORK); /* try to put */
memcpy(ifp->if_u1.if_data, tmpbuffer, size); /* it back */
goto out;
}
memset((char *)&nargs, 0, sizeof(nargs));
nargs.dp = dp;
nargs.geo = args->geo;
nargs.firstblock = args->firstblock;
nargs.dfops = args->dfops;
nargs.total = args->total;
nargs.whichfork = XFS_ATTR_FORK;
nargs.trans = args->trans;
nargs.op_flags = XFS_DA_OP_OKNOENT;
sfe = &sf->list[0];
for (i = 0; i < sf->hdr.count; i++) {
nargs.name = sfe->nameval;
nargs.namelen = sfe->namelen;
nargs.value = &sfe->nameval[nargs.namelen];
nargs.valuelen = sfe->valuelen;
nargs.hashval = xfs_da_hashname(sfe->nameval,
sfe->namelen);
nargs.flags = XFS_ATTR_NSP_ONDISK_TO_ARGS(sfe->flags);
error = xfs_attr3_leaf_lookup_int(bp, &nargs); /* set a->index */
ASSERT(error == -ENOATTR);
error = xfs_attr3_leaf_add(bp, &nargs);
ASSERT(error != -ENOSPC);
if (error)
goto out;
sfe = XFS_ATTR_SF_NEXTENTRY(sfe);
}
error = 0;
*leaf_bp = bp;
out:
kmem_free(tmpbuffer);
return error;
} | {
"deleted": [
{
"line_no": 46,
"char_start": 1151,
"char_end": 1195,
"line": "\t\terror = xfs_da_shrink_inode(args, 0, bp);\n"
},
{
"line_no": 47,
"char_start": 1195,
"char_end": 1208,
"line": "\t\tbp = NULL;\n"
},
{
"line_no": 48,
"char_start": 1208,
"char_end": 1221,
"line": "\t\tif (error)\n"
}
],
"added": [
{
"line_no": 46,
"char_start": 1151,
"char_end": 1215,
"line": "\t\t/* xfs_attr3_leaf_create may not have instantiated a block */\n"
},
{
"line_no": 47,
"char_start": 1215,
"char_end": 1268,
"line": "\t\tif (bp && (xfs_da_shrink_inode(args, 0, bp) != 0))\n"
}
]
} | {
"deleted": [
{
"char_start": 1155,
"char_end": 1156,
"chars": "r"
},
{
"char_start": 1157,
"char_end": 1158,
"chars": "r"
},
{
"char_start": 1159,
"char_end": 1160,
"chars": "="
},
{
"char_start": 1193,
"char_end": 1199,
"chars": ";\n\t\tbp"
},
{
"char_start": 1202,
"char_end": 1219,
"chars": "NULL;\n\t\tif (error"
}
],
"added": [
{
"char_start": 1153,
"char_end": 1167,
"chars": "/* xfs_attr3_l"
},
{
"char_start": 1168,
"char_end": 1172,
"chars": "af_c"
},
{
"char_start": 1173,
"char_end": 1183,
"chars": "eate may n"
},
{
"char_start": 1184,
"char_end": 1185,
"chars": "t"
},
{
"char_start": 1186,
"char_end": 1190,
"chars": "have"
},
{
"char_start": 1191,
"char_end": 1228,
"chars": "instantiated a block */\n\t\tif (bp && ("
},
{
"char_start": 1261,
"char_end": 1262,
"chars": "!"
},
{
"char_start": 1264,
"char_end": 1266,
"chars": "0)"
}
]
} | github.com/torvalds/linux/commit/bb3d48dcf86a97dc25fe9fc2c11938e19cb4399a | fs/xfs/libxfs/xfs_attr_leaf.c | cwe-476 |
lys_restr_dup | lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)
{
struct lys_restr *result;
int i;
if (!size) {
return NULL;
}
result = calloc(size, sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);
for (i = 0; i < size; i++) {
result[i].ext_size = old[i].ext_size;
lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);
result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);
result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);
result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);
result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);
result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);
}
return result;
} | lys_restr_dup(struct lys_module *mod, struct lys_restr *old, int size, int shallow, struct unres_schema *unres)
{
struct lys_restr *result;
int i;
if (!size) {
return NULL;
}
result = calloc(size, sizeof *result);
LY_CHECK_ERR_RETURN(!result, LOGMEM(mod->ctx), NULL);
for (i = 0; i < size; i++) {
/* copying unresolved extensions is not supported */
if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) {
result[i].ext_size = old[i].ext_size;
lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);
}
result[i].expr = lydict_insert(mod->ctx, old[i].expr, 0);
result[i].dsc = lydict_insert(mod->ctx, old[i].dsc, 0);
result[i].ref = lydict_insert(mod->ctx, old[i].ref, 0);
result[i].eapptag = lydict_insert(mod->ctx, old[i].eapptag, 0);
result[i].emsg = lydict_insert(mod->ctx, old[i].emsg, 0);
}
return result;
} | {
"deleted": [
{
"line_no": 14,
"char_start": 336,
"char_end": 382,
"line": " result[i].ext_size = old[i].ext_size;\n"
},
{
"line_no": 15,
"char_start": 382,
"char_end": 508,
"line": " lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n"
}
],
"added": [
{
"line_no": 14,
"char_start": 336,
"char_end": 397,
"line": " /* copying unresolved extensions is not supported */\n"
},
{
"line_no": 15,
"char_start": 397,
"char_end": 479,
"line": " if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) {\n"
},
{
"line_no": 16,
"char_start": 479,
"char_end": 529,
"line": " result[i].ext_size = old[i].ext_size;\n"
},
{
"line_no": 17,
"char_start": 529,
"char_end": 659,
"line": " lys_ext_dup(mod->ctx, mod, old[i].ext, old[i].ext_size, &result[i], LYEXT_PAR_RESTR, &result[i].ext, shallow, unres);\n"
},
{
"line_no": 18,
"char_start": 659,
"char_end": 669,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 344,
"char_end": 491,
"chars": "/* copying unresolved extensions is not supported */\n if (unres_schema_find(unres, -1, (void *)&old[i].ext, UNRES_EXT) == -1) {\n "
},
{
"char_start": 529,
"char_end": 533,
"chars": " "
},
{
"char_start": 658,
"char_end": 668,
"chars": "\n }"
}
]
} | github.com/CESNET/libyang/commit/7852b272ef77f8098c35deea6c6f09cb78176f08 | src/tree_schema.c | cwe-476 |
nfc_genl_deactivate_target | static int nfc_genl_deactivate_target(struct sk_buff *skb,
struct genl_info *info)
{
struct nfc_dev *dev;
u32 device_idx, target_idx;
int rc;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX])
return -EINVAL;
device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(device_idx);
if (!dev)
return -ENODEV;
target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);
rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);
nfc_put_device(dev);
return rc;
} | static int nfc_genl_deactivate_target(struct sk_buff *skb,
struct genl_info *info)
{
struct nfc_dev *dev;
u32 device_idx, target_idx;
int rc;
if (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||
!info->attrs[NFC_ATTR_TARGET_INDEX])
return -EINVAL;
device_idx = nla_get_u32(info->attrs[NFC_ATTR_DEVICE_INDEX]);
dev = nfc_get_device(device_idx);
if (!dev)
return -ENODEV;
target_idx = nla_get_u32(info->attrs[NFC_ATTR_TARGET_INDEX]);
rc = nfc_deactivate_target(dev, target_idx, NFC_TARGET_MODE_SLEEP);
nfc_put_device(dev);
return rc;
} | {
"deleted": [
{
"line_no": 8,
"char_start": 156,
"char_end": 198,
"line": "\tif (!info->attrs[NFC_ATTR_DEVICE_INDEX])\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 156,
"char_end": 200,
"line": "\tif (!info->attrs[NFC_ATTR_DEVICE_INDEX] ||\n"
},
{
"line_no": 9,
"char_start": 200,
"char_end": 242,
"line": "\t !info->attrs[NFC_ATTR_TARGET_INDEX])\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 196,
"char_end": 240,
"chars": " ||\n\t !info->attrs[NFC_ATTR_TARGET_INDEX]"
}
]
} | github.com/torvalds/linux/commit/385097a3675749cbc9e97c085c0e5dfe4269ca51 | net/nfc/netlink.c | cwe-476 |
dnxhd_find_frame_end | static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
if (cid <= 0)
continue;
dctx->remaining = avpriv_dnxhd_get_frame_size(cid);
if (dctx->remaining <= 0) {
dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (dctx->remaining <= 0)
return dctx->remaining;
}
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
} | static int dnxhd_find_frame_end(DNXHDParserContext *dctx,
const uint8_t *buf, int buf_size)
{
ParseContext *pc = &dctx->pc;
uint64_t state = pc->state64;
int pic_found = pc->frame_start_found;
int i = 0;
if (!pic_found) {
for (i = 0; i < buf_size; i++) {
state = (state << 8) | buf[i];
if (ff_dnxhd_check_header_prefix(state & 0xffffffffff00LL) != 0) {
i++;
pic_found = 1;
dctx->cur_byte = 0;
dctx->remaining = 0;
break;
}
}
}
if (pic_found && !dctx->remaining) {
if (!buf_size) /* EOF considered as end of frame */
return 0;
for (; i < buf_size; i++) {
dctx->cur_byte++;
state = (state << 8) | buf[i];
if (dctx->cur_byte == 24) {
dctx->h = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 26) {
dctx->w = (state >> 32) & 0xFFFF;
} else if (dctx->cur_byte == 42) {
int cid = (state >> 32) & 0xFFFFFFFF;
int remaining;
if (cid <= 0)
continue;
remaining = avpriv_dnxhd_get_frame_size(cid);
if (remaining <= 0) {
remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);
if (remaining <= 0)
continue;
}
dctx->remaining = remaining;
if (buf_size - i + 47 >= dctx->remaining) {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
} else {
dctx->remaining -= buf_size;
}
}
}
} else if (pic_found) {
if (dctx->remaining > buf_size) {
dctx->remaining -= buf_size;
} else {
int remaining = dctx->remaining;
pc->frame_start_found = 0;
pc->state64 = -1;
dctx->cur_byte = 0;
dctx->remaining = 0;
return remaining;
}
}
pc->frame_start_found = pic_found;
pc->state64 = state;
return END_NOT_FOUND;
} | {
"deleted": [
{
"line_no": 39,
"char_start": 1200,
"char_end": 1268,
"line": " dctx->remaining = avpriv_dnxhd_get_frame_size(cid);\n"
},
{
"line_no": 40,
"char_start": 1268,
"char_end": 1312,
"line": " if (dctx->remaining <= 0) {\n"
},
{
"line_no": 41,
"char_start": 1312,
"char_end": 1398,
"line": " dctx->remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);\n"
},
{
"line_no": 42,
"char_start": 1398,
"char_end": 1444,
"line": " if (dctx->remaining <= 0)\n"
},
{
"line_no": 43,
"char_start": 1444,
"char_end": 1492,
"line": " return dctx->remaining;\n"
}
],
"added": [
{
"line_no": 35,
"char_start": 1138,
"char_end": 1169,
"line": " int remaining;\n"
},
{
"line_no": 40,
"char_start": 1231,
"char_end": 1293,
"line": " remaining = avpriv_dnxhd_get_frame_size(cid);\n"
},
{
"line_no": 41,
"char_start": 1293,
"char_end": 1331,
"line": " if (remaining <= 0) {\n"
},
{
"line_no": 42,
"char_start": 1331,
"char_end": 1411,
"line": " remaining = dnxhd_get_hr_frame_size(cid, dctx->w, dctx->h);\n"
},
{
"line_no": 43,
"char_start": 1411,
"char_end": 1451,
"line": " if (remaining <= 0)\n"
},
{
"line_no": 44,
"char_start": 1451,
"char_end": 1485,
"line": " continue;\n"
},
{
"line_no": 46,
"char_start": 1503,
"char_end": 1548,
"line": " dctx->remaining = remaining;\n"
}
]
} | {
"deleted": [
{
"char_start": 1216,
"char_end": 1222,
"chars": "dctx->"
},
{
"char_start": 1288,
"char_end": 1294,
"chars": "dctx->"
},
{
"char_start": 1332,
"char_end": 1338,
"chars": "dctx->"
},
{
"char_start": 1422,
"char_end": 1428,
"chars": "dctx->"
},
{
"char_start": 1468,
"char_end": 1476,
"chars": "return d"
},
{
"char_start": 1477,
"char_end": 1486,
"chars": "tx->remai"
},
{
"char_start": 1489,
"char_end": 1490,
"chars": "g"
}
],
"added": [
{
"char_start": 1138,
"char_end": 1169,
"chars": " int remaining;\n"
},
{
"char_start": 1476,
"char_end": 1478,
"chars": "on"
},
{
"char_start": 1481,
"char_end": 1483,
"chars": "ue"
},
{
"char_start": 1502,
"char_end": 1547,
"chars": "\n dctx->remaining = remaining;"
}
]
} | github.com/FFmpeg/FFmpeg/commit/0a709e2a10b8288a0cc383547924ecfe285cef89 | libavcodec/dnxhd_parser.c | cwe-476 |
__rds_rdma_map | static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,
u64 *cookie_ret, struct rds_mr **mr_ret)
{
struct rds_mr *mr = NULL, *found;
unsigned int nr_pages;
struct page **pages = NULL;
struct scatterlist *sg;
void *trans_private;
unsigned long flags;
rds_rdma_cookie_t cookie;
unsigned int nents;
long i;
int ret;
if (rs->rs_bound_addr == 0) {
ret = -ENOTCONN; /* XXX not a great errno */
goto out;
}
if (!rs->rs_transport->get_mr) {
ret = -EOPNOTSUPP;
goto out;
}
nr_pages = rds_pages_in_vec(&args->vec);
if (nr_pages == 0) {
ret = -EINVAL;
goto out;
}
/* Restrict the size of mr irrespective of underlying transport
* To account for unaligned mr regions, subtract one from nr_pages
*/
if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {
ret = -EMSGSIZE;
goto out;
}
rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n",
args->vec.addr, args->vec.bytes, nr_pages);
/* XXX clamp nr_pages to limit the size of this alloc? */
pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
if (!pages) {
ret = -ENOMEM;
goto out;
}
mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);
if (!mr) {
ret = -ENOMEM;
goto out;
}
refcount_set(&mr->r_refcount, 1);
RB_CLEAR_NODE(&mr->r_rb_node);
mr->r_trans = rs->rs_transport;
mr->r_sock = rs;
if (args->flags & RDS_RDMA_USE_ONCE)
mr->r_use_once = 1;
if (args->flags & RDS_RDMA_INVALIDATE)
mr->r_invalidate = 1;
if (args->flags & RDS_RDMA_READWRITE)
mr->r_write = 1;
/*
* Pin the pages that make up the user buffer and transfer the page
* pointers to the mr's sg array. We check to see if we've mapped
* the whole region after transferring the partial page references
* to the sg array so that we can have one page ref cleanup path.
*
* For now we have no flag that tells us whether the mapping is
* r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to
* the zero page.
*/
ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);
if (ret < 0)
goto out;
nents = ret;
sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);
if (!sg) {
ret = -ENOMEM;
goto out;
}
WARN_ON(!nents);
sg_init_table(sg, nents);
/* Stick all pages into the scatterlist */
for (i = 0 ; i < nents; i++)
sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);
rdsdebug("RDS: trans_private nents is %u\n", nents);
/* Obtain a transport specific MR. If this succeeds, the
* s/g list is now owned by the MR.
* Note that dma_map() implies that pending writes are
* flushed to RAM, so no dma_sync is needed here. */
trans_private = rs->rs_transport->get_mr(sg, nents, rs,
&mr->r_key);
if (IS_ERR(trans_private)) {
for (i = 0 ; i < nents; i++)
put_page(sg_page(&sg[i]));
kfree(sg);
ret = PTR_ERR(trans_private);
goto out;
}
mr->r_trans_private = trans_private;
rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n",
mr->r_key, (void *)(unsigned long) args->cookie_addr);
/* The user may pass us an unaligned address, but we can only
* map page aligned regions. So we keep the offset, and build
* a 64bit cookie containing <R_Key, offset> and pass that
* around. */
cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);
if (cookie_ret)
*cookie_ret = cookie;
if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {
ret = -EFAULT;
goto out;
}
/* Inserting the new MR into the rbtree bumps its
* reference count. */
spin_lock_irqsave(&rs->rs_rdma_lock, flags);
found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);
spin_unlock_irqrestore(&rs->rs_rdma_lock, flags);
BUG_ON(found && found != mr);
rdsdebug("RDS: get_mr key is %x\n", mr->r_key);
if (mr_ret) {
refcount_inc(&mr->r_refcount);
*mr_ret = mr;
}
ret = 0;
out:
kfree(pages);
if (mr)
rds_mr_put(mr);
return ret;
} | static int __rds_rdma_map(struct rds_sock *rs, struct rds_get_mr_args *args,
u64 *cookie_ret, struct rds_mr **mr_ret)
{
struct rds_mr *mr = NULL, *found;
unsigned int nr_pages;
struct page **pages = NULL;
struct scatterlist *sg;
void *trans_private;
unsigned long flags;
rds_rdma_cookie_t cookie;
unsigned int nents;
long i;
int ret;
if (rs->rs_bound_addr == 0 || !rs->rs_transport) {
ret = -ENOTCONN; /* XXX not a great errno */
goto out;
}
if (!rs->rs_transport->get_mr) {
ret = -EOPNOTSUPP;
goto out;
}
nr_pages = rds_pages_in_vec(&args->vec);
if (nr_pages == 0) {
ret = -EINVAL;
goto out;
}
/* Restrict the size of mr irrespective of underlying transport
* To account for unaligned mr regions, subtract one from nr_pages
*/
if ((nr_pages - 1) > (RDS_MAX_MSG_SIZE >> PAGE_SHIFT)) {
ret = -EMSGSIZE;
goto out;
}
rdsdebug("RDS: get_mr addr %llx len %llu nr_pages %u\n",
args->vec.addr, args->vec.bytes, nr_pages);
/* XXX clamp nr_pages to limit the size of this alloc? */
pages = kcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL);
if (!pages) {
ret = -ENOMEM;
goto out;
}
mr = kzalloc(sizeof(struct rds_mr), GFP_KERNEL);
if (!mr) {
ret = -ENOMEM;
goto out;
}
refcount_set(&mr->r_refcount, 1);
RB_CLEAR_NODE(&mr->r_rb_node);
mr->r_trans = rs->rs_transport;
mr->r_sock = rs;
if (args->flags & RDS_RDMA_USE_ONCE)
mr->r_use_once = 1;
if (args->flags & RDS_RDMA_INVALIDATE)
mr->r_invalidate = 1;
if (args->flags & RDS_RDMA_READWRITE)
mr->r_write = 1;
/*
* Pin the pages that make up the user buffer and transfer the page
* pointers to the mr's sg array. We check to see if we've mapped
* the whole region after transferring the partial page references
* to the sg array so that we can have one page ref cleanup path.
*
* For now we have no flag that tells us whether the mapping is
* r/o or r/w. We need to assume r/w, or we'll do a lot of RDMA to
* the zero page.
*/
ret = rds_pin_pages(args->vec.addr, nr_pages, pages, 1);
if (ret < 0)
goto out;
nents = ret;
sg = kcalloc(nents, sizeof(*sg), GFP_KERNEL);
if (!sg) {
ret = -ENOMEM;
goto out;
}
WARN_ON(!nents);
sg_init_table(sg, nents);
/* Stick all pages into the scatterlist */
for (i = 0 ; i < nents; i++)
sg_set_page(&sg[i], pages[i], PAGE_SIZE, 0);
rdsdebug("RDS: trans_private nents is %u\n", nents);
/* Obtain a transport specific MR. If this succeeds, the
* s/g list is now owned by the MR.
* Note that dma_map() implies that pending writes are
* flushed to RAM, so no dma_sync is needed here. */
trans_private = rs->rs_transport->get_mr(sg, nents, rs,
&mr->r_key);
if (IS_ERR(trans_private)) {
for (i = 0 ; i < nents; i++)
put_page(sg_page(&sg[i]));
kfree(sg);
ret = PTR_ERR(trans_private);
goto out;
}
mr->r_trans_private = trans_private;
rdsdebug("RDS: get_mr put_user key is %x cookie_addr %p\n",
mr->r_key, (void *)(unsigned long) args->cookie_addr);
/* The user may pass us an unaligned address, but we can only
* map page aligned regions. So we keep the offset, and build
* a 64bit cookie containing <R_Key, offset> and pass that
* around. */
cookie = rds_rdma_make_cookie(mr->r_key, args->vec.addr & ~PAGE_MASK);
if (cookie_ret)
*cookie_ret = cookie;
if (args->cookie_addr && put_user(cookie, (u64 __user *)(unsigned long) args->cookie_addr)) {
ret = -EFAULT;
goto out;
}
/* Inserting the new MR into the rbtree bumps its
* reference count. */
spin_lock_irqsave(&rs->rs_rdma_lock, flags);
found = rds_mr_tree_walk(&rs->rs_rdma_keys, mr->r_key, mr);
spin_unlock_irqrestore(&rs->rs_rdma_lock, flags);
BUG_ON(found && found != mr);
rdsdebug("RDS: get_mr key is %x\n", mr->r_key);
if (mr_ret) {
refcount_inc(&mr->r_refcount);
*mr_ret = mr;
}
ret = 0;
out:
kfree(pages);
if (mr)
rds_mr_put(mr);
return ret;
} | {
"deleted": [
{
"line_no": 15,
"char_start": 349,
"char_end": 380,
"line": "\tif (rs->rs_bound_addr == 0) {\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 349,
"char_end": 401,
"line": "\tif (rs->rs_bound_addr == 0 || !rs->rs_transport) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 376,
"char_end": 397,
"chars": " || !rs->rs_transport"
}
]
} | github.com/torvalds/linux/commit/f3069c6d33f6ae63a1668737bc78aaaa51bff7ca | net/rds/rdma.c | cwe-476 |
daemon_AuthUserPwd | daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
HANDLE Token;
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "LogonUser() failed");
return -1;
}
// This call should change the current thread to the selected user.
// I didn't test it.
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
// This call is needed to get the uid
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
#ifdef HAVE_GETSPNAM
// This call is needed to get the password; otherwise 'x' is returned
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
if (strcmp(user_password, (char *) crypt(password, user_password)) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
if (setuid(user->pw_uid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setuid");
return -1;
}
/* if (setgid(user->pw_gid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
return -1;
}
*/
return 0;
#endif
} | daemon_AuthUserPwd(char *username, char *password, char *errbuf)
{
#ifdef _WIN32
/*
* Warning: the user which launches the process must have the
* SE_TCB_NAME right.
* This corresponds to have the "Act as part of the Operating System"
* turned on (administrative tools, local security settings, local
* policies, user right assignment)
* However, it seems to me that if you run it as a service, this
* right should be provided by default.
*
* XXX - hopefully, this returns errors such as ERROR_LOGON_FAILURE,
* which merely indicates that the user name or password is
* incorrect, not whether it's the user name or the password
* that's incorrect, so a client that's trying to brute-force
* accounts doesn't know whether it's the user name or the
* password that's incorrect, so it doesn't know whether to
* stop trying to log in with a given user name and move on
* to another user name.
*/
HANDLE Token;
if (LogonUser(username, ".", password, LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT, &Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "LogonUser() failed");
return -1;
}
// This call should change the current thread to the selected user.
// I didn't test it.
if (ImpersonateLoggedOnUser(Token) == 0)
{
pcap_fmt_errmsg_for_win32_err(errbuf, PCAP_ERRBUF_SIZE,
GetLastError(), "ImpersonateLoggedOnUser() failed");
CloseHandle(Token);
return -1;
}
CloseHandle(Token);
return 0;
#else
/*
* See
*
* http://www.unixpapa.com/incnote/passwd.html
*
* We use the Solaris/Linux shadow password authentication if
* we have getspnam(), otherwise we just do traditional
* authentication, which, on some platforms, might work, even
* with shadow passwords, if we're running as root. Traditional
* authenticaion won't work if we're not running as root, as
* I think these days all UN*Xes either won't return the password
* at all with getpwnam() or will only do so if you're root.
*
* XXX - perhaps what we *should* be using is PAM, if we have
* it. That might hide all the details of username/password
* authentication, whether it's done with a visible-to-root-
* only password database or some other authentication mechanism,
* behind its API.
*/
struct passwd *user;
char *user_password;
#ifdef HAVE_GETSPNAM
struct spwd *usersp;
#endif
char *crypt_password;
// This call is needed to get the uid
if ((user = getpwnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
#ifdef HAVE_GETSPNAM
// This call is needed to get the password; otherwise 'x' is returned
if ((usersp = getspnam(username)) == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
user_password = usersp->sp_pwdp;
#else
/*
* XXX - what about other platforms?
* The unixpapa.com page claims this Just Works on *BSD if you're
* running as root - it's from 2000, so it doesn't indicate whether
* macOS (which didn't come out until 2001, under the name Mac OS
* X) behaves like the *BSDs or not, and might also work on AIX.
* HP-UX does something else.
*
* Again, hopefully PAM hides all that.
*/
user_password = user->pw_passwd;
#endif
crypt_password = crypt(password, user_password);
if (crypt_password == NULL)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed");
return -1;
}
if (strcmp(user_password, crypt_password) != 0)
{
pcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, "Authentication failed: user name or password incorrect");
return -1;
}
if (setuid(user->pw_uid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setuid");
return -1;
}
/* if (setgid(user->pw_gid))
{
pcap_fmt_errmsg_for_errno(errbuf, PCAP_ERRBUF_SIZE,
errno, "setgid");
return -1;
}
*/
return 0;
#endif
} | {
"deleted": [
{
"line_no": 98,
"char_start": 3317,
"char_end": 3391,
"line": "\tif (strcmp(user_password, (char *) crypt(password, user_password)) != 0)\n"
}
],
"added": [
{
"line_no": 68,
"char_start": 2384,
"char_end": 2407,
"line": "\tchar *crypt_password;\n"
},
{
"line_no": 99,
"char_start": 3340,
"char_end": 3390,
"line": "\tcrypt_password = crypt(password, user_password);\n"
},
{
"line_no": 100,
"char_start": 3390,
"char_end": 3419,
"line": "\tif (crypt_password == NULL)\n"
},
{
"line_no": 101,
"char_start": 3419,
"char_end": 3422,
"line": "\t{\n"
},
{
"line_no": 102,
"char_start": 3422,
"char_end": 3490,
"line": "\t\tpcap_snprintf(errbuf, PCAP_ERRBUF_SIZE, \"Authentication failed\");\n"
},
{
"line_no": 103,
"char_start": 3490,
"char_end": 3503,
"line": "\t\treturn -1;\n"
},
{
"line_no": 104,
"char_start": 3503,
"char_end": 3506,
"line": "\t}\n"
},
{
"line_no": 105,
"char_start": 3506,
"char_end": 3555,
"line": "\tif (strcmp(user_password, crypt_password) != 0)\n"
}
]
} | {
"deleted": [
{
"char_start": 3318,
"char_end": 3323,
"chars": "if (s"
},
{
"char_start": 3326,
"char_end": 3327,
"chars": "m"
},
{
"char_start": 3342,
"char_end": 3343,
"chars": ","
},
{
"char_start": 3346,
"char_end": 3347,
"chars": "h"
},
{
"char_start": 3350,
"char_end": 3351,
"chars": "*"
},
{
"char_start": 3355,
"char_end": 3357,
"chars": "yp"
},
{
"char_start": 3369,
"char_end": 3372,
"chars": "use"
},
{
"char_start": 3382,
"char_end": 3383,
"chars": ")"
}
],
"added": [
{
"char_start": 2384,
"char_end": 2407,
"chars": "\tchar *crypt_password;\n"
},
{
"char_start": 3341,
"char_end": 3350,
"chars": "crypt_pas"
},
{
"char_start": 3351,
"char_end": 3353,
"chars": "wo"
},
{
"char_start": 3354,
"char_end": 3358,
"chars": "d = "
},
{
"char_start": 3359,
"char_end": 3361,
"chars": "ry"
},
{
"char_start": 3362,
"char_end": 3363,
"chars": "t"
},
{
"char_start": 3364,
"char_end": 3374,
"chars": "password, "
},
{
"char_start": 3387,
"char_end": 3393,
"chars": ");\n\tif"
},
{
"char_start": 3396,
"char_end": 3402,
"chars": "rypt_p"
},
{
"char_start": 3403,
"char_end": 3407,
"chars": "sswo"
},
{
"char_start": 3408,
"char_end": 3409,
"chars": "d"
},
{
"char_start": 3410,
"char_end": 3417,
"chars": "== NULL"
},
{
"char_start": 3418,
"char_end": 3445,
"chars": "\n\t{\n\t\tpcap_snprintf(errbuf,"
},
{
"char_start": 3446,
"char_end": 3473,
"chars": "PCAP_ERRBUF_SIZE, \"Authenti"
},
{
"char_start": 3474,
"char_end": 3492,
"chars": "ation failed\");\n\t\t"
},
{
"char_start": 3493,
"char_end": 3512,
"chars": "eturn -1;\n\t}\n\tif (s"
},
{
"char_start": 3513,
"char_end": 3517,
"chars": "rcmp"
},
{
"char_start": 3518,
"char_end": 3523,
"chars": "user_"
},
{
"char_start": 3533,
"char_end": 3534,
"chars": "c"
},
{
"char_start": 3535,
"char_end": 3538,
"chars": "ypt"
}
]
} | github.com/the-tcpdump-group/libpcap/commit/437b273761adedcbd880f714bfa44afeec186a31 | rpcapd/daemon.c | cwe-476 |
run | static int run(const CommandLineOptions& options)
{
IR::Module irModule;
// Load the module.
if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; }
if(options.onlyCheck) { return EXIT_SUCCESS; }
// Compile the module.
Runtime::Module* module = nullptr;
if(!options.precompiled) { module = Runtime::compileModule(irModule); }
else
{
const UserSection* precompiledObjectSection = nullptr;
for(const UserSection& userSection : irModule.userSections)
{
if(userSection.name == "wavm.precompiled_object")
{
precompiledObjectSection = &userSection;
break;
}
}
if(!precompiledObjectSection)
{
Log::printf(Log::error, "Input file did not contain 'wavm.precompiled_object' section");
return EXIT_FAILURE;
}
else
{
module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data);
}
}
// Link the module with the intrinsic modules.
Compartment* compartment = Runtime::createCompartment();
Context* context = Runtime::createContext(compartment);
RootResolver rootResolver(compartment);
Emscripten::Instance* emscriptenInstance = nullptr;
if(options.enableEmscripten)
{
emscriptenInstance = Emscripten::instantiate(compartment, irModule);
if(emscriptenInstance)
{
rootResolver.moduleNameToInstanceMap.set("env", emscriptenInstance->env);
rootResolver.moduleNameToInstanceMap.set("asm2wasm", emscriptenInstance->asm2wasm);
rootResolver.moduleNameToInstanceMap.set("global", emscriptenInstance->global);
}
}
if(options.enableThreadTest)
{
ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment);
rootResolver.moduleNameToInstanceMap.set("threadTest", threadTestInstance);
}
LinkResult linkResult = linkModule(irModule, rootResolver);
if(!linkResult.success)
{
Log::printf(Log::error, "Failed to link module:\n");
for(auto& missingImport : linkResult.missingImports)
{
Log::printf(Log::error,
"Missing import: module=\"%s\" export=\"%s\" type=\"%s\"\n",
missingImport.moduleName.c_str(),
missingImport.exportName.c_str(),
asString(missingImport.type).c_str());
}
return EXIT_FAILURE;
}
// Instantiate the module.
ModuleInstance* moduleInstance = instantiateModule(
compartment, module, std::move(linkResult.resolvedImports), options.filename);
if(!moduleInstance) { return EXIT_FAILURE; }
// Call the module start function, if it has one.
FunctionInstance* startFunction = getStartFunction(moduleInstance);
if(startFunction) { invokeFunctionChecked(context, startFunction, {}); }
if(options.enableEmscripten)
{
// Call the Emscripten global initalizers.
Emscripten::initializeGlobals(context, irModule, moduleInstance);
}
// Look up the function export to call.
FunctionInstance* functionInstance;
if(!options.functionName)
{
functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "main"));
if(!functionInstance)
{ functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "_main")); }
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export main function\n");
return EXIT_FAILURE;
}
}
else
{
functionInstance
= asFunctionNullable(getInstanceExport(moduleInstance, options.functionName));
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export '%s'\n", options.functionName);
return EXIT_FAILURE;
}
}
FunctionType functionType = getFunctionType(functionInstance);
// Set up the arguments for the invoke.
std::vector<Value> invokeArgs;
if(!options.functionName)
{
if(functionType.params().size() == 2)
{
MemoryInstance* defaultMemory = Runtime::getDefaultMemory(moduleInstance);
if(!defaultMemory)
{
Log::printf(
Log::error,
"Module does not declare a default memory object to put arguments in.\n");
return EXIT_FAILURE;
}
std::vector<const char*> argStrings;
argStrings.push_back(options.filename);
char** args = options.args;
while(*args) { argStrings.push_back(*args++); };
Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);
}
else if(functionType.params().size() > 0)
{
Log::printf(Log::error,
"WebAssembly function requires %" PRIu64
" argument(s), but only 0 or 2 can be passed!",
functionType.params().size());
return EXIT_FAILURE;
}
}
else
{
for(U32 i = 0; options.args[i]; ++i)
{
Value value;
switch(functionType.params()[i])
{
case ValueType::i32: value = (U32)atoi(options.args[i]); break;
case ValueType::i64: value = (U64)atol(options.args[i]); break;
case ValueType::f32: value = (F32)atof(options.args[i]); break;
case ValueType::f64: value = atof(options.args[i]); break;
case ValueType::v128:
case ValueType::anyref:
case ValueType::anyfunc:
Errors::fatalf("Cannot parse command-line argument for %s function parameter",
asString(functionType.params()[i]));
default: Errors::unreachable();
}
invokeArgs.push_back(value);
}
}
// Invoke the function.
Timing::Timer executionTimer;
IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs);
Timing::logTimer("Invoked function", executionTimer);
if(options.functionName)
{
Log::printf(Log::debug,
"%s returned: %s\n",
options.functionName,
asString(functionResults).c_str());
return EXIT_SUCCESS;
}
else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32)
{
return functionResults[0].i32;
}
else
{
return EXIT_SUCCESS;
}
} | static int run(const CommandLineOptions& options)
{
IR::Module irModule;
// Load the module.
if(!loadModule(options.filename, irModule)) { return EXIT_FAILURE; }
if(options.onlyCheck) { return EXIT_SUCCESS; }
// Compile the module.
Runtime::Module* module = nullptr;
if(!options.precompiled) { module = Runtime::compileModule(irModule); }
else
{
const UserSection* precompiledObjectSection = nullptr;
for(const UserSection& userSection : irModule.userSections)
{
if(userSection.name == "wavm.precompiled_object")
{
precompiledObjectSection = &userSection;
break;
}
}
if(!precompiledObjectSection)
{
Log::printf(Log::error, "Input file did not contain 'wavm.precompiled_object' section");
return EXIT_FAILURE;
}
else
{
module = Runtime::loadPrecompiledModule(irModule, precompiledObjectSection->data);
}
}
// Link the module with the intrinsic modules.
Compartment* compartment = Runtime::createCompartment();
Context* context = Runtime::createContext(compartment);
RootResolver rootResolver(compartment);
Emscripten::Instance* emscriptenInstance = nullptr;
if(options.enableEmscripten)
{
emscriptenInstance = Emscripten::instantiate(compartment, irModule);
if(emscriptenInstance)
{
rootResolver.moduleNameToInstanceMap.set("env", emscriptenInstance->env);
rootResolver.moduleNameToInstanceMap.set("asm2wasm", emscriptenInstance->asm2wasm);
rootResolver.moduleNameToInstanceMap.set("global", emscriptenInstance->global);
}
}
if(options.enableThreadTest)
{
ModuleInstance* threadTestInstance = ThreadTest::instantiate(compartment);
rootResolver.moduleNameToInstanceMap.set("threadTest", threadTestInstance);
}
LinkResult linkResult = linkModule(irModule, rootResolver);
if(!linkResult.success)
{
Log::printf(Log::error, "Failed to link module:\n");
for(auto& missingImport : linkResult.missingImports)
{
Log::printf(Log::error,
"Missing import: module=\"%s\" export=\"%s\" type=\"%s\"\n",
missingImport.moduleName.c_str(),
missingImport.exportName.c_str(),
asString(missingImport.type).c_str());
}
return EXIT_FAILURE;
}
// Instantiate the module.
ModuleInstance* moduleInstance = instantiateModule(
compartment, module, std::move(linkResult.resolvedImports), options.filename);
if(!moduleInstance) { return EXIT_FAILURE; }
// Call the module start function, if it has one.
FunctionInstance* startFunction = getStartFunction(moduleInstance);
if(startFunction) { invokeFunctionChecked(context, startFunction, {}); }
if(options.enableEmscripten)
{
// Call the Emscripten global initalizers.
Emscripten::initializeGlobals(context, irModule, moduleInstance);
}
// Look up the function export to call.
FunctionInstance* functionInstance;
if(!options.functionName)
{
functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "main"));
if(!functionInstance)
{ functionInstance = asFunctionNullable(getInstanceExport(moduleInstance, "_main")); }
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export main function\n");
return EXIT_FAILURE;
}
}
else
{
functionInstance
= asFunctionNullable(getInstanceExport(moduleInstance, options.functionName));
if(!functionInstance)
{
Log::printf(Log::error, "Module does not export '%s'\n", options.functionName);
return EXIT_FAILURE;
}
}
FunctionType functionType = getFunctionType(functionInstance);
// Set up the arguments for the invoke.
std::vector<Value> invokeArgs;
if(!options.functionName)
{
if(functionType.params().size() == 2)
{
if(!emscriptenInstance)
{
Log::printf(
Log::error,
"Module does not declare a default memory object to put arguments in.\n");
return EXIT_FAILURE;
}
else
{
std::vector<const char*> argStrings;
argStrings.push_back(options.filename);
char** args = options.args;
while(*args) { argStrings.push_back(*args++); };
wavmAssert(emscriptenInstance);
Emscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);
}
}
else if(functionType.params().size() > 0)
{
Log::printf(Log::error,
"WebAssembly function requires %" PRIu64
" argument(s), but only 0 or 2 can be passed!",
functionType.params().size());
return EXIT_FAILURE;
}
}
else
{
for(U32 i = 0; options.args[i]; ++i)
{
Value value;
switch(functionType.params()[i])
{
case ValueType::i32: value = (U32)atoi(options.args[i]); break;
case ValueType::i64: value = (U64)atol(options.args[i]); break;
case ValueType::f32: value = (F32)atof(options.args[i]); break;
case ValueType::f64: value = atof(options.args[i]); break;
case ValueType::v128:
case ValueType::anyref:
case ValueType::anyfunc:
Errors::fatalf("Cannot parse command-line argument for %s function parameter",
asString(functionType.params()[i]));
default: Errors::unreachable();
}
invokeArgs.push_back(value);
}
}
// Invoke the function.
Timing::Timer executionTimer;
IR::ValueTuple functionResults = invokeFunctionChecked(context, functionInstance, invokeArgs);
Timing::logTimer("Invoked function", executionTimer);
if(options.functionName)
{
Log::printf(Log::debug,
"%s returned: %s\n",
options.functionName,
asString(functionResults).c_str());
return EXIT_SUCCESS;
}
else if(functionResults.size() == 1 && functionResults[0].type == ValueType::i32)
{
return functionResults[0].i32;
}
else
{
return EXIT_SUCCESS;
}
} | {
"deleted": [
{
"line_no": 119,
"char_start": 3608,
"char_end": 3686,
"line": "\t\t\tMemoryInstance* defaultMemory = Runtime::getDefaultMemory(moduleInstance);\n"
},
{
"line_no": 120,
"char_start": 3686,
"char_end": 3708,
"line": "\t\t\tif(!defaultMemory)\n"
},
{
"line_no": 128,
"char_start": 3858,
"char_end": 3898,
"line": "\t\t\tstd::vector<const char*> argStrings;\n"
},
{
"line_no": 129,
"char_start": 3898,
"char_end": 3941,
"line": "\t\t\targStrings.push_back(options.filename);\n"
},
{
"line_no": 130,
"char_start": 3941,
"char_end": 3972,
"line": "\t\t\tchar** args = options.args;\n"
},
{
"line_no": 131,
"char_start": 3972,
"char_end": 4024,
"line": "\t\t\twhile(*args) { argStrings.push_back(*args++); };\n"
},
{
"line_no": 132,
"char_start": 4024,
"char_end": 4025,
"line": "\n"
},
{
"line_no": 133,
"char_start": 4025,
"char_end": 4103,
"line": "\t\t\tEmscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);\n"
}
],
"added": [
{
"line_no": 119,
"char_start": 3608,
"char_end": 3635,
"line": "\t\t\tif(!emscriptenInstance)\n"
},
{
"line_no": 126,
"char_start": 3784,
"char_end": 3792,
"line": "\t\t\telse\n"
},
{
"line_no": 127,
"char_start": 3792,
"char_end": 3797,
"line": "\t\t\t{\n"
},
{
"line_no": 128,
"char_start": 3797,
"char_end": 3838,
"line": "\t\t\t\tstd::vector<const char*> argStrings;\n"
},
{
"line_no": 129,
"char_start": 3838,
"char_end": 3882,
"line": "\t\t\t\targStrings.push_back(options.filename);\n"
},
{
"line_no": 130,
"char_start": 3882,
"char_end": 3914,
"line": "\t\t\t\tchar** args = options.args;\n"
},
{
"line_no": 131,
"char_start": 3914,
"char_end": 3967,
"line": "\t\t\t\twhile(*args) { argStrings.push_back(*args++); };\n"
},
{
"line_no": 133,
"char_start": 3968,
"char_end": 4004,
"line": "\t\t\t\twavmAssert(emscriptenInstance);\n"
},
{
"line_no": 134,
"char_start": 4004,
"char_end": 4083,
"line": "\t\t\t\tEmscripten::injectCommandArgs(emscriptenInstance, argStrings, invokeArgs);\n"
},
{
"line_no": 135,
"char_start": 4083,
"char_end": 4088,
"line": "\t\t\t}\n"
}
]
} | {
"deleted": [
{
"char_start": 3611,
"char_end": 3612,
"chars": "M"
},
{
"char_start": 3614,
"char_end": 3619,
"chars": "oryIn"
},
{
"char_start": 3620,
"char_end": 3623,
"chars": "tan"
},
{
"char_start": 3624,
"char_end": 3638,
"chars": "e* defaultMemo"
},
{
"char_start": 3639,
"char_end": 3647,
"chars": "y = Runt"
},
{
"char_start": 3648,
"char_end": 3654,
"chars": "me::ge"
},
{
"char_start": 3655,
"char_end": 3656,
"chars": "D"
},
{
"char_start": 3657,
"char_end": 3675,
"chars": "faultMemory(module"
},
{
"char_start": 3683,
"char_end": 3706,
"chars": ");\n\t\t\tif(!defaultMemory"
}
],
"added": [
{
"char_start": 3611,
"char_end": 3615,
"chars": "if(!"
},
{
"char_start": 3621,
"char_end": 3622,
"chars": "p"
},
{
"char_start": 3624,
"char_end": 3625,
"chars": "n"
},
{
"char_start": 3784,
"char_end": 3791,
"chars": "\t\t\telse"
},
{
"char_start": 3795,
"char_end": 3801,
"chars": "{\n\t\t\t\t"
},
{
"char_start": 3838,
"char_end": 3839,
"chars": "\t"
},
{
"char_start": 3882,
"char_end": 3883,
"chars": "\t"
},
{
"char_start": 3917,
"char_end": 3918,
"chars": "\t"
},
{
"char_start": 3971,
"char_end": 4008,
"chars": "\twavmAssert(emscriptenInstance);\n\t\t\t\t"
},
{
"char_start": 4082,
"char_end": 4087,
"chars": "\n\t\t\t}"
}
]
} | github.com/WAVM/WAVM/commit/31d670b6489e6d708c3b04b911cdf14ac43d846d | Programs/wavm/wavm.cpp | cwe-476 |
open_ssl_connection | open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred)
{
SSL_CTX *ssl_ctx = NULL;
SSL *ssl = NULL;
int n, finished = 0;
X509_VERIFY_PARAM *param;
uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode;
if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method())))
{
rfbClientLog("Could not create new SSL context.\n");
return NULL;
}
param = X509_VERIFY_PARAM_new();
/* Setup verification if not anonymous */
if (!anonTLS)
{
if (cred->x509Credential.x509CACertFile)
{
if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL))
{
rfbClientLog("Failed to load CA certificate from %s.\n",
cred->x509Credential.x509CACertFile);
goto error_free_ctx;
}
} else {
rfbClientLog("Using default paths for certificate verification.\n");
SSL_CTX_set_default_verify_paths (ssl_ctx);
}
if (cred->x509Credential.x509CACrlFile)
{
if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx))
{
rfbClientLog("CRLs could not be loaded.\n");
goto error_free_ctx;
}
if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll;
}
if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)
{
if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1)
{
rfbClientLog("Client certificate could not be loaded.\n");
goto error_free_ctx;
}
if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile,
SSL_FILETYPE_PEM) != 1)
{
rfbClientLog("Client private key could not be loaded.\n");
goto error_free_ctx;
}
if (SSL_CTX_check_private_key(ssl_ctx) == 0) {
rfbClientLog("Client certificate and private key do not match.\n");
goto error_free_ctx;
}
}
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
if (verify_crls == rfbX509CrlVerifyClient)
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
else if (verify_crls == rfbX509CrlVerifyAll)
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost)))
{
rfbClientLog("Could not set server name for verification.\n");
goto error_free_ctx;
}
SSL_CTX_set1_param(ssl_ctx, param);
}
if (!(ssl = SSL_new (ssl_ctx)))
{
rfbClientLog("Could not create a new SSL session.\n");
goto error_free_ctx;
}
/* TODO: finetune this list, take into account anonTLS bool */
SSL_set_cipher_list(ssl, "ALL");
SSL_set_fd (ssl, sockfd);
SSL_CTX_set_app_data (ssl_ctx, client);
do
{
n = SSL_connect(ssl);
if (n != 1)
{
if (wait_for_data(ssl, n, 1) != 1)
{
finished = 1;
SSL_shutdown(ssl);
goto error_free_ssl;
}
}
} while( n != 1 && finished != 1 );
X509_VERIFY_PARAM_free(param);
return ssl;
error_free_ssl:
SSL_free(ssl);
error_free_ctx:
X509_VERIFY_PARAM_free(param);
SSL_CTX_free(ssl_ctx);
return NULL;
} | open_ssl_connection (rfbClient *client, int sockfd, rfbBool anonTLS, rfbCredential *cred)
{
SSL_CTX *ssl_ctx = NULL;
SSL *ssl = NULL;
int n, finished = 0;
X509_VERIFY_PARAM *param;
uint8_t verify_crls;
if (!(ssl_ctx = SSL_CTX_new(SSLv23_client_method())))
{
rfbClientLog("Could not create new SSL context.\n");
return NULL;
}
param = X509_VERIFY_PARAM_new();
/* Setup verification if not anonymous */
if (!anonTLS)
{
verify_crls = cred->x509Credential.x509CrlVerifyMode;
if (cred->x509Credential.x509CACertFile)
{
if (!SSL_CTX_load_verify_locations(ssl_ctx, cred->x509Credential.x509CACertFile, NULL))
{
rfbClientLog("Failed to load CA certificate from %s.\n",
cred->x509Credential.x509CACertFile);
goto error_free_ctx;
}
} else {
rfbClientLog("Using default paths for certificate verification.\n");
SSL_CTX_set_default_verify_paths (ssl_ctx);
}
if (cred->x509Credential.x509CACrlFile)
{
if (!load_crls_from_file(cred->x509Credential.x509CACrlFile, ssl_ctx))
{
rfbClientLog("CRLs could not be loaded.\n");
goto error_free_ctx;
}
if (verify_crls == rfbX509CrlVerifyNone) verify_crls = rfbX509CrlVerifyAll;
}
if (cred->x509Credential.x509ClientCertFile && cred->x509Credential.x509ClientKeyFile)
{
if (SSL_CTX_use_certificate_chain_file(ssl_ctx, cred->x509Credential.x509ClientCertFile) != 1)
{
rfbClientLog("Client certificate could not be loaded.\n");
goto error_free_ctx;
}
if (SSL_CTX_use_PrivateKey_file(ssl_ctx, cred->x509Credential.x509ClientKeyFile,
SSL_FILETYPE_PEM) != 1)
{
rfbClientLog("Client private key could not be loaded.\n");
goto error_free_ctx;
}
if (SSL_CTX_check_private_key(ssl_ctx) == 0) {
rfbClientLog("Client certificate and private key do not match.\n");
goto error_free_ctx;
}
}
SSL_CTX_set_verify(ssl_ctx, SSL_VERIFY_PEER, NULL);
if (verify_crls == rfbX509CrlVerifyClient)
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK);
else if (verify_crls == rfbX509CrlVerifyAll)
X509_VERIFY_PARAM_set_flags(param, X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
if(!X509_VERIFY_PARAM_set1_host(param, client->serverHost, strlen(client->serverHost)))
{
rfbClientLog("Could not set server name for verification.\n");
goto error_free_ctx;
}
SSL_CTX_set1_param(ssl_ctx, param);
}
if (!(ssl = SSL_new (ssl_ctx)))
{
rfbClientLog("Could not create a new SSL session.\n");
goto error_free_ctx;
}
/* TODO: finetune this list, take into account anonTLS bool */
SSL_set_cipher_list(ssl, "ALL");
SSL_set_fd (ssl, sockfd);
SSL_CTX_set_app_data (ssl_ctx, client);
do
{
n = SSL_connect(ssl);
if (n != 1)
{
if (wait_for_data(ssl, n, 1) != 1)
{
finished = 1;
SSL_shutdown(ssl);
goto error_free_ssl;
}
}
} while( n != 1 && finished != 1 );
X509_VERIFY_PARAM_free(param);
return ssl;
error_free_ssl:
SSL_free(ssl);
error_free_ctx:
X509_VERIFY_PARAM_free(param);
SSL_CTX_free(ssl_ctx);
return NULL;
} | {
"deleted": [
{
"line_no": 7,
"char_start": 189,
"char_end": 253,
"line": " uint8_t verify_crls = cred->x509Credential.x509CrlVerifyMode;\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 189,
"char_end": 212,
"line": " uint8_t verify_crls;\n"
},
{
"line_no": 20,
"char_start": 452,
"char_end": 510,
"line": " verify_crls = cred->x509Credential.x509CrlVerifyMode;\n"
}
]
} | {
"deleted": [
{
"char_start": 210,
"char_end": 251,
"chars": " = cred->x509Credential.x509CrlVerifyMode"
}
],
"added": [
{
"char_start": 451,
"char_end": 509,
"chars": "\n verify_crls = cred->x509Credential.x509CrlVerifyMode;"
}
]
} | github.com/LibVNC/libvncserver/commit/33441d90a506d5f3ae9388f2752901227e430553 | libvncclient/tls_openssl.c | cwe-476 |
copyIPv6IfDifferent | static void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src) {
memcpy(dest, src, sizeof(struct in6_addr));
}
} | static void copyIPv6IfDifferent(void * dest, const void * src)
{
if(dest != src && src != NULL) {
memcpy(dest, src, sizeof(struct in6_addr));
}
} | {
"deleted": [
{
"line_no": 3,
"char_start": 65,
"char_end": 84,
"line": "\tif(dest != src) {\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 65,
"char_end": 99,
"line": "\tif(dest != src && src != NULL) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 80,
"char_end": 95,
"chars": " && src != NULL"
}
]
} | github.com/miniupnp/miniupnp/commit/cb8a02af7a5677cf608e86d57ab04241cf34e24f | miniupnpd/pcpserver.c | cwe-476 |
archive_acl_from_text_l | archive_acl_from_text_l(struct archive_acl *acl, const char *text,
int want_type, struct archive_string_conv *sc)
{
struct {
const char *start;
const char *end;
} field[6], name;
const char *s, *st;
int numfields, fields, n, r, sol, ret;
int type, types, tag, permset, id;
size_t len;
char sep;
switch (want_type) {
case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E:
want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
__LA_FALLTHROUGH;
case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
numfields = 5;
break;
case ARCHIVE_ENTRY_ACL_TYPE_NFS4:
numfields = 6;
break;
default:
return (ARCHIVE_FATAL);
}
ret = ARCHIVE_OK;
types = 0;
while (text != NULL && *text != '\0') {
/*
* Parse the fields out of the next entry,
* advance 'text' to start of next entry.
*/
fields = 0;
do {
const char *start, *end;
next_field(&text, &start, &end, &sep);
if (fields < numfields) {
field[fields].start = start;
field[fields].end = end;
}
++fields;
} while (sep == ':');
/* Set remaining fields to blank. */
for (n = fields; n < numfields; ++n)
field[n].start = field[n].end = NULL;
if (field[0].start != NULL && *(field[0].start) == '#') {
/* Comment, skip entry */
continue;
}
n = 0;
sol = 0;
id = -1;
permset = 0;
name.start = name.end = NULL;
if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
/* POSIX.1e ACLs */
/*
* Default keyword "default:user::rwx"
* if found, we have one more field
*
* We also support old Solaris extension:
* "defaultuser::rwx" is the default ACL corresponding
* to "user::rwx", etc. valid only for first field
*/
s = field[0].start;
len = field[0].end - field[0].start;
if (*s == 'd' && (len == 1 || (len >= 7
&& memcmp((s + 1), "efault", 6) == 0))) {
type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT;
if (len > 7)
field[0].start += 7;
else
n = 1;
} else
type = want_type;
/* Check for a numeric ID in field n+1 or n+3. */
isint(field[n + 1].start, field[n + 1].end, &id);
/* Field n+3 is optional. */
if (id == -1 && fields > (n + 3))
isint(field[n + 3].start, field[n + 3].end,
&id);
tag = 0;
s = field[n].start;
st = field[n].start + 1;
len = field[n].end - field[n].start;
switch (*s) {
case 'u':
if (len == 1 || (len == 4
&& memcmp(st, "ser", 3) == 0))
tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
break;
case 'g':
if (len == 1 || (len == 5
&& memcmp(st, "roup", 4) == 0))
tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
break;
case 'o':
if (len == 1 || (len == 5
&& memcmp(st, "ther", 4) == 0))
tag = ARCHIVE_ENTRY_ACL_OTHER;
break;
case 'm':
if (len == 1 || (len == 4
&& memcmp(st, "ask", 3) == 0))
tag = ARCHIVE_ENTRY_ACL_MASK;
break;
default:
break;
}
switch (tag) {
case ARCHIVE_ENTRY_ACL_OTHER:
case ARCHIVE_ENTRY_ACL_MASK:
if (fields == (n + 2)
&& field[n + 1].start < field[n + 1].end
&& ismode(field[n + 1].start,
field[n + 1].end, &permset)) {
/* This is Solaris-style "other:rwx" */
sol = 1;
} else if (fields == (n + 3) &&
field[n + 1].start < field[n + 1].end) {
/* Invalid mask or other field */
ret = ARCHIVE_WARN;
continue;
}
break;
case ARCHIVE_ENTRY_ACL_USER_OBJ:
case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
if (id != -1 ||
field[n + 1].start < field[n + 1].end) {
name = field[n + 1];
if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ)
tag = ARCHIVE_ENTRY_ACL_USER;
else
tag = ARCHIVE_ENTRY_ACL_GROUP;
}
break;
default:
/* Invalid tag, skip entry */
ret = ARCHIVE_WARN;
continue;
}
/*
* Without "default:" we expect mode in field 3
* Exception: Solaris other and mask fields
*/
if (permset == 0 && !ismode(field[n + 2 - sol].start,
field[n + 2 - sol].end, &permset)) {
/* Invalid mode, skip entry */
ret = ARCHIVE_WARN;
continue;
}
} else {
/* NFS4 ACLs */
s = field[0].start;
len = field[0].end - field[0].start;
tag = 0;
switch (len) {
case 4:
if (memcmp(s, "user", 4) == 0)
tag = ARCHIVE_ENTRY_ACL_USER;
break;
case 5:
if (memcmp(s, "group", 5) == 0)
tag = ARCHIVE_ENTRY_ACL_GROUP;
break;
case 6:
if (memcmp(s, "owner@", 6) == 0)
tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
else if (memcmp(s, "group@", 6) == 0)
tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
break;
case 9:
if (memcmp(s, "everyone@", 9) == 0)
tag = ARCHIVE_ENTRY_ACL_EVERYONE;
break;
default:
break;
}
if (tag == 0) {
/* Invalid tag, skip entry */
ret = ARCHIVE_WARN;
continue;
} else if (tag == ARCHIVE_ENTRY_ACL_USER ||
tag == ARCHIVE_ENTRY_ACL_GROUP) {
n = 1;
name = field[1];
isint(name.start, name.end, &id);
} else
n = 0;
if (!is_nfs4_perms(field[1 + n].start,
field[1 + n].end, &permset)) {
/* Invalid NFSv4 perms, skip entry */
ret = ARCHIVE_WARN;
continue;
}
if (!is_nfs4_flags(field[2 + n].start,
field[2 + n].end, &permset)) {
/* Invalid NFSv4 flags, skip entry */
ret = ARCHIVE_WARN;
continue;
}
s = field[3 + n].start;
len = field[3 + n].end - field[3 + n].start;
type = 0;
if (len == 4) {
if (memcmp(s, "deny", 4) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
} else if (len == 5) {
if (memcmp(s, "allow", 5) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
else if (memcmp(s, "audit", 5) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT;
else if (memcmp(s, "alarm", 5) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_ALARM;
}
if (type == 0) {
/* Invalid entry type, skip entry */
ret = ARCHIVE_WARN;
continue;
}
isint(field[4 + n].start, field[4 + n].end,
&id);
}
/* Add entry to the internal list. */
r = archive_acl_add_entry_len_l(acl, type, permset,
tag, id, name.start, name.end - name.start, sc);
if (r < ARCHIVE_WARN)
return (r);
if (r != ARCHIVE_OK)
ret = ARCHIVE_WARN;
types |= type;
}
/* Reset ACL */
archive_acl_reset(acl, types);
return (ret);
} | archive_acl_from_text_l(struct archive_acl *acl, const char *text,
int want_type, struct archive_string_conv *sc)
{
struct {
const char *start;
const char *end;
} field[6], name;
const char *s, *st;
int numfields, fields, n, r, sol, ret;
int type, types, tag, permset, id;
size_t len;
char sep;
switch (want_type) {
case ARCHIVE_ENTRY_ACL_TYPE_POSIX1E:
want_type = ARCHIVE_ENTRY_ACL_TYPE_ACCESS;
__LA_FALLTHROUGH;
case ARCHIVE_ENTRY_ACL_TYPE_ACCESS:
case ARCHIVE_ENTRY_ACL_TYPE_DEFAULT:
numfields = 5;
break;
case ARCHIVE_ENTRY_ACL_TYPE_NFS4:
numfields = 6;
break;
default:
return (ARCHIVE_FATAL);
}
ret = ARCHIVE_OK;
types = 0;
while (text != NULL && *text != '\0') {
/*
* Parse the fields out of the next entry,
* advance 'text' to start of next entry.
*/
fields = 0;
do {
const char *start, *end;
next_field(&text, &start, &end, &sep);
if (fields < numfields) {
field[fields].start = start;
field[fields].end = end;
}
++fields;
} while (sep == ':');
/* Set remaining fields to blank. */
for (n = fields; n < numfields; ++n)
field[n].start = field[n].end = NULL;
if (field[0].start != NULL && *(field[0].start) == '#') {
/* Comment, skip entry */
continue;
}
n = 0;
sol = 0;
id = -1;
permset = 0;
name.start = name.end = NULL;
if (want_type != ARCHIVE_ENTRY_ACL_TYPE_NFS4) {
/* POSIX.1e ACLs */
/*
* Default keyword "default:user::rwx"
* if found, we have one more field
*
* We also support old Solaris extension:
* "defaultuser::rwx" is the default ACL corresponding
* to "user::rwx", etc. valid only for first field
*/
s = field[0].start;
len = field[0].end - field[0].start;
if (*s == 'd' && (len == 1 || (len >= 7
&& memcmp((s + 1), "efault", 6) == 0))) {
type = ARCHIVE_ENTRY_ACL_TYPE_DEFAULT;
if (len > 7)
field[0].start += 7;
else
n = 1;
} else
type = want_type;
/* Check for a numeric ID in field n+1 or n+3. */
isint(field[n + 1].start, field[n + 1].end, &id);
/* Field n+3 is optional. */
if (id == -1 && fields > (n + 3))
isint(field[n + 3].start, field[n + 3].end,
&id);
tag = 0;
s = field[n].start;
st = field[n].start + 1;
len = field[n].end - field[n].start;
if (len == 0) {
ret = ARCHIVE_WARN;
continue;
}
switch (*s) {
case 'u':
if (len == 1 || (len == 4
&& memcmp(st, "ser", 3) == 0))
tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
break;
case 'g':
if (len == 1 || (len == 5
&& memcmp(st, "roup", 4) == 0))
tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
break;
case 'o':
if (len == 1 || (len == 5
&& memcmp(st, "ther", 4) == 0))
tag = ARCHIVE_ENTRY_ACL_OTHER;
break;
case 'm':
if (len == 1 || (len == 4
&& memcmp(st, "ask", 3) == 0))
tag = ARCHIVE_ENTRY_ACL_MASK;
break;
default:
break;
}
switch (tag) {
case ARCHIVE_ENTRY_ACL_OTHER:
case ARCHIVE_ENTRY_ACL_MASK:
if (fields == (n + 2)
&& field[n + 1].start < field[n + 1].end
&& ismode(field[n + 1].start,
field[n + 1].end, &permset)) {
/* This is Solaris-style "other:rwx" */
sol = 1;
} else if (fields == (n + 3) &&
field[n + 1].start < field[n + 1].end) {
/* Invalid mask or other field */
ret = ARCHIVE_WARN;
continue;
}
break;
case ARCHIVE_ENTRY_ACL_USER_OBJ:
case ARCHIVE_ENTRY_ACL_GROUP_OBJ:
if (id != -1 ||
field[n + 1].start < field[n + 1].end) {
name = field[n + 1];
if (tag == ARCHIVE_ENTRY_ACL_USER_OBJ)
tag = ARCHIVE_ENTRY_ACL_USER;
else
tag = ARCHIVE_ENTRY_ACL_GROUP;
}
break;
default:
/* Invalid tag, skip entry */
ret = ARCHIVE_WARN;
continue;
}
/*
* Without "default:" we expect mode in field 3
* Exception: Solaris other and mask fields
*/
if (permset == 0 && !ismode(field[n + 2 - sol].start,
field[n + 2 - sol].end, &permset)) {
/* Invalid mode, skip entry */
ret = ARCHIVE_WARN;
continue;
}
} else {
/* NFS4 ACLs */
s = field[0].start;
len = field[0].end - field[0].start;
tag = 0;
switch (len) {
case 4:
if (memcmp(s, "user", 4) == 0)
tag = ARCHIVE_ENTRY_ACL_USER;
break;
case 5:
if (memcmp(s, "group", 5) == 0)
tag = ARCHIVE_ENTRY_ACL_GROUP;
break;
case 6:
if (memcmp(s, "owner@", 6) == 0)
tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
else if (memcmp(s, "group@", 6) == 0)
tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
break;
case 9:
if (memcmp(s, "everyone@", 9) == 0)
tag = ARCHIVE_ENTRY_ACL_EVERYONE;
break;
default:
break;
}
if (tag == 0) {
/* Invalid tag, skip entry */
ret = ARCHIVE_WARN;
continue;
} else if (tag == ARCHIVE_ENTRY_ACL_USER ||
tag == ARCHIVE_ENTRY_ACL_GROUP) {
n = 1;
name = field[1];
isint(name.start, name.end, &id);
} else
n = 0;
if (!is_nfs4_perms(field[1 + n].start,
field[1 + n].end, &permset)) {
/* Invalid NFSv4 perms, skip entry */
ret = ARCHIVE_WARN;
continue;
}
if (!is_nfs4_flags(field[2 + n].start,
field[2 + n].end, &permset)) {
/* Invalid NFSv4 flags, skip entry */
ret = ARCHIVE_WARN;
continue;
}
s = field[3 + n].start;
len = field[3 + n].end - field[3 + n].start;
type = 0;
if (len == 4) {
if (memcmp(s, "deny", 4) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_DENY;
} else if (len == 5) {
if (memcmp(s, "allow", 5) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_ALLOW;
else if (memcmp(s, "audit", 5) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_AUDIT;
else if (memcmp(s, "alarm", 5) == 0)
type = ARCHIVE_ENTRY_ACL_TYPE_ALARM;
}
if (type == 0) {
/* Invalid entry type, skip entry */
ret = ARCHIVE_WARN;
continue;
}
isint(field[4 + n].start, field[4 + n].end,
&id);
}
/* Add entry to the internal list. */
r = archive_acl_add_entry_len_l(acl, type, permset,
tag, id, name.start, name.end - name.start, sc);
if (r < ARCHIVE_WARN)
return (r);
if (r != ARCHIVE_OK)
ret = ARCHIVE_WARN;
types |= type;
}
/* Reset ACL */
archive_acl_reset(acl, types);
return (ret);
} | {
"deleted": [],
"added": [
{
"line_no": 98,
"char_start": 2311,
"char_end": 2330,
"line": "\t\t\tif (len == 0) {\n"
},
{
"line_no": 99,
"char_start": 2330,
"char_end": 2354,
"line": "\t\t\t\tret = ARCHIVE_WARN;\n"
},
{
"line_no": 100,
"char_start": 2354,
"char_end": 2368,
"line": "\t\t\t\tcontinue;\n"
},
{
"line_no": 101,
"char_start": 2368,
"char_end": 2373,
"line": "\t\t\t}\n"
},
{
"line_no": 102,
"char_start": 2373,
"char_end": 2374,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2314,
"char_end": 2377,
"chars": "if (len == 0) {\n\t\t\t\tret = ARCHIVE_WARN;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t"
}
]
} | github.com/libarchive/libarchive/commit/15bf44fd2c1ad0e3fd87048b3fcc90c4dcff1175 | libarchive/archive_acl.c | cwe-476 |
avcodec_open2 | int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
{
int ret = 0;
int codec_init_ok = 0;
AVDictionary *tmp = NULL;
const AVPixFmtDescriptor *pixdesc;
if (avcodec_is_open(avctx))
return 0;
if ((!codec && !avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
return AVERROR(EINVAL);
}
if ((codec && avctx->codec && codec != avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
"but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
return AVERROR(EINVAL);
}
if (!codec)
codec = avctx->codec;
if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
return AVERROR(EINVAL);
if (options)
av_dict_copy(&tmp, *options, 0);
ff_lock_avcodec(avctx, codec);
avctx->internal = av_mallocz(sizeof(*avctx->internal));
if (!avctx->internal) {
ret = AVERROR(ENOMEM);
goto end;
}
avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
if (!avctx->internal->pool) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->to_free = av_frame_alloc();
if (!avctx->internal->to_free) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->compat_decode_frame = av_frame_alloc();
if (!avctx->internal->compat_decode_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_frame = av_frame_alloc();
if (!avctx->internal->buffer_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_pkt = av_packet_alloc();
if (!avctx->internal->buffer_pkt) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->ds.in_pkt = av_packet_alloc();
if (!avctx->internal->ds.in_pkt) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->last_pkt_props = av_packet_alloc();
if (!avctx->internal->last_pkt_props) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->skip_samples_multiplier = 1;
if (codec->priv_data_size > 0) {
if (!avctx->priv_data) {
avctx->priv_data = av_mallocz(codec->priv_data_size);
if (!avctx->priv_data) {
ret = AVERROR(ENOMEM);
goto end;
}
if (codec->priv_class) {
*(const AVClass **)avctx->priv_data = codec->priv_class;
av_opt_set_defaults(avctx->priv_data);
}
}
if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
goto free_and_end;
} else {
avctx->priv_data = NULL;
}
if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
goto free_and_end;
if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) {
av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist);
ret = AVERROR(EINVAL);
goto free_and_end;
}
// only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions
if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
(avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) {
if (avctx->coded_width && avctx->coded_height)
ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
else if (avctx->width && avctx->height)
ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
if (ret < 0)
goto free_and_end;
}
if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
&& ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0
|| av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) {
av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
ff_set_dimensions(avctx, 0, 0);
}
if (avctx->width > 0 && avctx->height > 0) {
if (av_image_check_sar(avctx->width, avctx->height,
avctx->sample_aspect_ratio) < 0) {
av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
avctx->sample_aspect_ratio.num,
avctx->sample_aspect_ratio.den);
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
}
}
/* if the decoder init function was already called previously,
* free the already allocated subtitle_header before overwriting it */
if (av_codec_is_decoder(codec))
av_freep(&avctx->subtitle_header);
if (avctx->channels > FF_SANE_NB_CHANNELS) {
av_log(avctx, AV_LOG_ERROR, "Too many channels: %d\n", avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->codec = codec;
if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
avctx->codec_id == AV_CODEC_ID_NONE) {
avctx->codec_type = codec->type;
avctx->codec_id = codec->id;
}
if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
&& avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->frame_number = 0;
avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
AVCodec *codec2;
av_log(avctx, AV_LOG_ERROR,
"The %s '%s' is experimental but experimental codecs are not enabled, "
"add '-strict %d' if you want to use it.\n",
codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
codec_string, codec2->name);
ret = AVERROR_EXPERIMENTAL;
goto free_and_end;
}
if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
(!avctx->time_base.num || !avctx->time_base.den)) {
avctx->time_base.num = 1;
avctx->time_base.den = avctx->sample_rate;
}
if (!HAVE_THREADS)
av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) {
ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem
ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
ff_lock_avcodec(avctx, codec);
if (ret < 0)
goto free_and_end;
}
if (av_codec_is_decoder(avctx->codec)) {
ret = ff_decode_bsfs_init(avctx);
if (ret < 0)
goto free_and_end;
}
if (HAVE_THREADS
&& !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
ret = ff_thread_init(avctx);
if (ret < 0) {
goto free_and_end;
}
}
if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
avctx->thread_count = 1;
if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
avctx->codec->max_lowres);
avctx->lowres = avctx->codec->max_lowres;
}
if (av_codec_is_encoder(avctx->codec)) {
int i;
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
avctx->coded_frame = av_frame_alloc();
if (!avctx->coded_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->sample_fmts) {
for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
break;
if (avctx->channels == 1 &&
av_get_planar_sample_fmt(avctx->sample_fmt) ==
av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
avctx->sample_fmt = avctx->codec->sample_fmts[i];
break;
}
}
if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->codec->pix_fmts) {
for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
break;
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
&& !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
&& avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
avctx->color_range = AVCOL_RANGE_JPEG;
}
if (avctx->codec->supported_samplerates) {
for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
break;
if (avctx->codec->supported_samplerates[i] == 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->sample_rate < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->channel_layouts) {
if (!avctx->channel_layout) {
av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
} else {
for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
if (avctx->channel_layout == avctx->codec->channel_layouts[i])
break;
if (avctx->codec->channel_layouts[i] == 0) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
}
if (avctx->channel_layout && avctx->channels) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR,
"Channel layout '%s' with %d channels does not match number of specified channels %d\n",
buf, channels, avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
} else if (avctx->channel_layout) {
avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
}
if (avctx->channels < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n",
avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
if ( avctx->bits_per_raw_sample < 0
|| (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
}
if (avctx->width <= 0 || avctx->height <= 0) {
av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
&& avctx->bit_rate>0 && avctx->bit_rate<1000) {
av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate);
}
if (!avctx->rc_initial_buffer_occupancy)
avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4;
if (avctx->ticks_per_frame && avctx->time_base.num &&
avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
av_log(avctx, AV_LOG_ERROR,
"ticks_per_frame %d too large for the timebase %d/%d.",
avctx->ticks_per_frame,
avctx->time_base.num,
avctx->time_base.den);
goto free_and_end;
}
if (avctx->hw_frames_ctx) {
AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
if (frames_ctx->format != avctx->pix_fmt) {
av_log(avctx, AV_LOG_ERROR,
"Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
avctx->sw_pix_fmt != frames_ctx->sw_format) {
av_log(avctx, AV_LOG_ERROR,
"Mismatching AVCodecContext.sw_pix_fmt (%s) "
"and AVHWFramesContext.sw_format (%s)\n",
av_get_pix_fmt_name(avctx->sw_pix_fmt),
av_get_pix_fmt_name(frames_ctx->sw_format));
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->sw_pix_fmt = frames_ctx->sw_format;
}
}
avctx->pts_correction_num_faulty_pts =
avctx->pts_correction_num_faulty_dts = 0;
avctx->pts_correction_last_pts =
avctx->pts_correction_last_dts = INT64_MIN;
if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
&& avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
av_log(avctx, AV_LOG_WARNING,
"gray decoding requested but not enabled at configuration time\n");
if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
|| avctx->internal->frame_thread_encoder)) {
ret = avctx->codec->init(avctx);
if (ret < 0) {
goto free_and_end;
}
codec_init_ok = 1;
}
ret=0;
if (av_codec_is_decoder(avctx->codec)) {
if (!avctx->bit_rate)
avctx->bit_rate = get_bit_rate(avctx);
/* validate channel layout from the decoder */
if (avctx->channel_layout) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (!avctx->channels)
avctx->channels = channels;
else if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_WARNING,
"Channel layout '%s' with %d channels does not match specified number of channels %d: "
"ignoring specified channel layout\n",
buf, channels, avctx->channels);
avctx->channel_layout = 0;
}
}
if (avctx->channels && avctx->channels < 0 ||
avctx->channels > FF_SANE_NB_CHANNELS) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->bits_per_coded_sample < 0) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->sub_charenc) {
if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
"supported with subtitles codecs\n");
ret = AVERROR(EINVAL);
goto free_and_end;
} else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
"subtitles character encoding will be ignored\n",
avctx->codec_descriptor->name);
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
} else {
/* input character encoding is set for a text based subtitle
* codec at this point */
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
#if CONFIG_ICONV
iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
if (cd == (iconv_t)-1) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
"with input character encoding \"%s\"\n", avctx->sub_charenc);
goto free_and_end;
}
iconv_close(cd);
#else
av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
"conversion needs a libavcodec built with iconv support "
"for this codec\n");
ret = AVERROR(ENOSYS);
goto free_and_end;
#endif
}
}
}
#if FF_API_AVCTX_TIMEBASE
if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
#endif
}
if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) {
av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class);
}
end:
ff_unlock_avcodec(codec);
if (options) {
av_dict_free(options);
*options = tmp;
}
return ret;
free_and_end:
if (avctx->codec &&
(codec_init_ok ||
(avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)))
avctx->codec->close(avctx);
if (codec->priv_class && codec->priv_data_size)
av_opt_free(avctx->priv_data);
av_opt_free(avctx);
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
av_frame_free(&avctx->coded_frame);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
av_dict_free(&tmp);
av_freep(&avctx->priv_data);
if (avctx->internal) {
av_frame_free(&avctx->internal->to_free);
av_frame_free(&avctx->internal->compat_decode_frame);
av_frame_free(&avctx->internal->buffer_frame);
av_packet_free(&avctx->internal->buffer_pkt);
av_packet_free(&avctx->internal->last_pkt_props);
av_packet_free(&avctx->internal->ds.in_pkt);
ff_decode_bsfs_uninit(avctx);
av_freep(&avctx->internal->pool);
}
av_freep(&avctx->internal);
avctx->codec = NULL;
goto end;
} | int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)
{
int ret = 0;
int codec_init_ok = 0;
AVDictionary *tmp = NULL;
const AVPixFmtDescriptor *pixdesc;
if (avcodec_is_open(avctx))
return 0;
if ((!codec && !avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");
return AVERROR(EINVAL);
}
if ((codec && avctx->codec && codec != avctx->codec)) {
av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "
"but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);
return AVERROR(EINVAL);
}
if (!codec)
codec = avctx->codec;
if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)
return AVERROR(EINVAL);
if (options)
av_dict_copy(&tmp, *options, 0);
ff_lock_avcodec(avctx, codec);
avctx->internal = av_mallocz(sizeof(*avctx->internal));
if (!avctx->internal) {
ret = AVERROR(ENOMEM);
goto end;
}
avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));
if (!avctx->internal->pool) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->to_free = av_frame_alloc();
if (!avctx->internal->to_free) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->compat_decode_frame = av_frame_alloc();
if (!avctx->internal->compat_decode_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_frame = av_frame_alloc();
if (!avctx->internal->buffer_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->buffer_pkt = av_packet_alloc();
if (!avctx->internal->buffer_pkt) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->ds.in_pkt = av_packet_alloc();
if (!avctx->internal->ds.in_pkt) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->last_pkt_props = av_packet_alloc();
if (!avctx->internal->last_pkt_props) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
avctx->internal->skip_samples_multiplier = 1;
if (codec->priv_data_size > 0) {
if (!avctx->priv_data) {
avctx->priv_data = av_mallocz(codec->priv_data_size);
if (!avctx->priv_data) {
ret = AVERROR(ENOMEM);
goto end;
}
if (codec->priv_class) {
*(const AVClass **)avctx->priv_data = codec->priv_class;
av_opt_set_defaults(avctx->priv_data);
}
}
if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)
goto free_and_end;
} else {
avctx->priv_data = NULL;
}
if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)
goto free_and_end;
if (avctx->codec_whitelist && av_match_list(codec->name, avctx->codec_whitelist, ',') <= 0) {
av_log(avctx, AV_LOG_ERROR, "Codec (%s) not on whitelist \'%s\'\n", codec->name, avctx->codec_whitelist);
ret = AVERROR(EINVAL);
goto free_and_end;
}
// only call ff_set_dimensions() for non H.264/VP6F/DXV codecs so as not to overwrite previously setup dimensions
if (!(avctx->coded_width && avctx->coded_height && avctx->width && avctx->height &&
(avctx->codec_id == AV_CODEC_ID_H264 || avctx->codec_id == AV_CODEC_ID_VP6F || avctx->codec_id == AV_CODEC_ID_DXV))) {
if (avctx->coded_width && avctx->coded_height)
ret = ff_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);
else if (avctx->width && avctx->height)
ret = ff_set_dimensions(avctx, avctx->width, avctx->height);
if (ret < 0)
goto free_and_end;
}
if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)
&& ( av_image_check_size2(avctx->coded_width, avctx->coded_height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0
|| av_image_check_size2(avctx->width, avctx->height, avctx->max_pixels, AV_PIX_FMT_NONE, 0, avctx) < 0)) {
av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");
ff_set_dimensions(avctx, 0, 0);
}
if (avctx->width > 0 && avctx->height > 0) {
if (av_image_check_sar(avctx->width, avctx->height,
avctx->sample_aspect_ratio) < 0) {
av_log(avctx, AV_LOG_WARNING, "ignoring invalid SAR: %u/%u\n",
avctx->sample_aspect_ratio.num,
avctx->sample_aspect_ratio.den);
avctx->sample_aspect_ratio = (AVRational){ 0, 1 };
}
}
/* if the decoder init function was already called previously,
* free the already allocated subtitle_header before overwriting it */
if (av_codec_is_decoder(codec))
av_freep(&avctx->subtitle_header);
if (avctx->channels > FF_SANE_NB_CHANNELS) {
av_log(avctx, AV_LOG_ERROR, "Too many channels: %d\n", avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->codec = codec;
if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&
avctx->codec_id == AV_CODEC_ID_NONE) {
avctx->codec_type = codec->type;
avctx->codec_id = codec->id;
}
if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type
&& avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {
av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->frame_number = 0;
avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);
if ((avctx->codec->capabilities & AV_CODEC_CAP_EXPERIMENTAL) &&
avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {
const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";
AVCodec *codec2;
av_log(avctx, AV_LOG_ERROR,
"The %s '%s' is experimental but experimental codecs are not enabled, "
"add '-strict %d' if you want to use it.\n",
codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);
codec2 = av_codec_is_encoder(codec) ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);
if (!(codec2->capabilities & AV_CODEC_CAP_EXPERIMENTAL))
av_log(avctx, AV_LOG_ERROR, "Alternatively use the non experimental %s '%s'.\n",
codec_string, codec2->name);
ret = AVERROR_EXPERIMENTAL;
goto free_and_end;
}
if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&
(!avctx->time_base.num || !avctx->time_base.den)) {
avctx->time_base.num = 1;
avctx->time_base.den = avctx->sample_rate;
}
if (!HAVE_THREADS)
av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");
if (CONFIG_FRAME_THREAD_ENCODER && av_codec_is_encoder(avctx->codec)) {
ff_unlock_avcodec(codec); //we will instantiate a few encoders thus kick the counter to prevent false detection of a problem
ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);
ff_lock_avcodec(avctx, codec);
if (ret < 0)
goto free_and_end;
}
if (av_codec_is_decoder(avctx->codec)) {
ret = ff_decode_bsfs_init(avctx);
if (ret < 0)
goto free_and_end;
}
if (HAVE_THREADS
&& !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {
ret = ff_thread_init(avctx);
if (ret < 0) {
goto free_and_end;
}
}
if (!HAVE_THREADS && !(codec->capabilities & AV_CODEC_CAP_AUTO_THREADS))
avctx->thread_count = 1;
if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {
av_log(avctx, AV_LOG_WARNING, "The maximum value for lowres supported by the decoder is %d\n",
avctx->codec->max_lowres);
avctx->lowres = avctx->codec->max_lowres;
}
if (av_codec_is_encoder(avctx->codec)) {
int i;
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
avctx->coded_frame = av_frame_alloc();
if (!avctx->coded_frame) {
ret = AVERROR(ENOMEM);
goto free_and_end;
}
FF_ENABLE_DEPRECATION_WARNINGS
#endif
if (avctx->time_base.num <= 0 || avctx->time_base.den <= 0) {
av_log(avctx, AV_LOG_ERROR, "The encoder timebase is not set.\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->sample_fmts) {
for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
if (avctx->sample_fmt == avctx->codec->sample_fmts[i])
break;
if (avctx->channels == 1 &&
av_get_planar_sample_fmt(avctx->sample_fmt) ==
av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {
avctx->sample_fmt = avctx->codec->sample_fmts[i];
break;
}
}
if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->codec->pix_fmts) {
for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)
if (avctx->pix_fmt == avctx->codec->pix_fmts[i])
break;
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE
&& !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)
&& avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {
char buf[128];
snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);
av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",
(char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ420P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ411P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ422P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ440P ||
avctx->codec->pix_fmts[i] == AV_PIX_FMT_YUVJ444P)
avctx->color_range = AVCOL_RANGE_JPEG;
}
if (avctx->codec->supported_samplerates) {
for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)
if (avctx->sample_rate == avctx->codec->supported_samplerates[i])
break;
if (avctx->codec->supported_samplerates[i] == 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if (avctx->sample_rate < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",
avctx->sample_rate);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->codec->channel_layouts) {
if (!avctx->channel_layout) {
av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");
} else {
for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)
if (avctx->channel_layout == avctx->codec->channel_layouts[i])
break;
if (avctx->codec->channel_layouts[i] == 0) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
}
if (avctx->channel_layout && avctx->channels) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_ERROR,
"Channel layout '%s' with %d channels does not match number of specified channels %d\n",
buf, channels, avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
} else if (avctx->channel_layout) {
avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
}
if (avctx->channels < 0) {
av_log(avctx, AV_LOG_ERROR, "Specified number of channels %d is not supported\n",
avctx->channels);
ret = AVERROR(EINVAL);
goto free_and_end;
}
if(avctx->codec_type == AVMEDIA_TYPE_VIDEO) {
pixdesc = av_pix_fmt_desc_get(avctx->pix_fmt);
if ( avctx->bits_per_raw_sample < 0
|| (avctx->bits_per_raw_sample > 8 && pixdesc->comp[0].depth <= 8)) {
av_log(avctx, AV_LOG_WARNING, "Specified bit depth %d not possible with the specified pixel formats depth %d\n",
avctx->bits_per_raw_sample, pixdesc->comp[0].depth);
avctx->bits_per_raw_sample = pixdesc->comp[0].depth;
}
if (avctx->width <= 0 || avctx->height <= 0) {
av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
}
if ( (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)
&& avctx->bit_rate>0 && avctx->bit_rate<1000) {
av_log(avctx, AV_LOG_WARNING, "Bitrate %"PRId64" is extremely low, maybe you mean %"PRId64"k\n", avctx->bit_rate, avctx->bit_rate);
}
if (!avctx->rc_initial_buffer_occupancy)
avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3LL / 4;
if (avctx->ticks_per_frame && avctx->time_base.num &&
avctx->ticks_per_frame > INT_MAX / avctx->time_base.num) {
av_log(avctx, AV_LOG_ERROR,
"ticks_per_frame %d too large for the timebase %d/%d.",
avctx->ticks_per_frame,
avctx->time_base.num,
avctx->time_base.den);
goto free_and_end;
}
if (avctx->hw_frames_ctx) {
AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
if (frames_ctx->format != avctx->pix_fmt) {
av_log(avctx, AV_LOG_ERROR,
"Mismatching AVCodecContext.pix_fmt and AVHWFramesContext.format\n");
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->sw_pix_fmt != AV_PIX_FMT_NONE &&
avctx->sw_pix_fmt != frames_ctx->sw_format) {
av_log(avctx, AV_LOG_ERROR,
"Mismatching AVCodecContext.sw_pix_fmt (%s) "
"and AVHWFramesContext.sw_format (%s)\n",
av_get_pix_fmt_name(avctx->sw_pix_fmt),
av_get_pix_fmt_name(frames_ctx->sw_format));
ret = AVERROR(EINVAL);
goto free_and_end;
}
avctx->sw_pix_fmt = frames_ctx->sw_format;
}
}
avctx->pts_correction_num_faulty_pts =
avctx->pts_correction_num_faulty_dts = 0;
avctx->pts_correction_last_pts =
avctx->pts_correction_last_dts = INT64_MIN;
if ( !CONFIG_GRAY && avctx->flags & AV_CODEC_FLAG_GRAY
&& avctx->codec_descriptor->type == AVMEDIA_TYPE_VIDEO)
av_log(avctx, AV_LOG_WARNING,
"gray decoding requested but not enabled at configuration time\n");
if ( avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)
|| avctx->internal->frame_thread_encoder)) {
ret = avctx->codec->init(avctx);
if (ret < 0) {
goto free_and_end;
}
codec_init_ok = 1;
}
ret=0;
if (av_codec_is_decoder(avctx->codec)) {
if (!avctx->bit_rate)
avctx->bit_rate = get_bit_rate(avctx);
/* validate channel layout from the decoder */
if (avctx->channel_layout) {
int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);
if (!avctx->channels)
avctx->channels = channels;
else if (channels != avctx->channels) {
char buf[512];
av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);
av_log(avctx, AV_LOG_WARNING,
"Channel layout '%s' with %d channels does not match specified number of channels %d: "
"ignoring specified channel layout\n",
buf, channels, avctx->channels);
avctx->channel_layout = 0;
}
}
if (avctx->channels && avctx->channels < 0 ||
avctx->channels > FF_SANE_NB_CHANNELS) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->bits_per_coded_sample < 0) {
ret = AVERROR(EINVAL);
goto free_and_end;
}
if (avctx->sub_charenc) {
if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {
av_log(avctx, AV_LOG_ERROR, "Character encoding is only "
"supported with subtitles codecs\n");
ret = AVERROR(EINVAL);
goto free_and_end;
} else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {
av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "
"subtitles character encoding will be ignored\n",
avctx->codec_descriptor->name);
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;
} else {
/* input character encoding is set for a text based subtitle
* codec at this point */
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)
avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;
if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {
#if CONFIG_ICONV
iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);
if (cd == (iconv_t)-1) {
ret = AVERROR(errno);
av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "
"with input character encoding \"%s\"\n", avctx->sub_charenc);
goto free_and_end;
}
iconv_close(cd);
#else
av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "
"conversion needs a libavcodec built with iconv support "
"for this codec\n");
ret = AVERROR(ENOSYS);
goto free_and_end;
#endif
}
}
}
#if FF_API_AVCTX_TIMEBASE
if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
avctx->time_base = av_inv_q(av_mul_q(avctx->framerate, (AVRational){avctx->ticks_per_frame, 1}));
#endif
}
if (codec->priv_data_size > 0 && avctx->priv_data && codec->priv_class) {
av_assert0(*(const AVClass **)avctx->priv_data == codec->priv_class);
}
end:
ff_unlock_avcodec(codec);
if (options) {
av_dict_free(options);
*options = tmp;
}
return ret;
free_and_end:
if (avctx->codec && avctx->codec->close &&
(codec_init_ok ||
(avctx->codec->caps_internal & FF_CODEC_CAP_INIT_CLEANUP)))
avctx->codec->close(avctx);
if (codec->priv_class && codec->priv_data_size)
av_opt_free(avctx->priv_data);
av_opt_free(avctx);
#if FF_API_CODED_FRAME
FF_DISABLE_DEPRECATION_WARNINGS
av_frame_free(&avctx->coded_frame);
FF_ENABLE_DEPRECATION_WARNINGS
#endif
av_dict_free(&tmp);
av_freep(&avctx->priv_data);
if (avctx->internal) {
av_frame_free(&avctx->internal->to_free);
av_frame_free(&avctx->internal->compat_decode_frame);
av_frame_free(&avctx->internal->buffer_frame);
av_packet_free(&avctx->internal->buffer_pkt);
av_packet_free(&avctx->internal->last_pkt_props);
av_packet_free(&avctx->internal->ds.in_pkt);
ff_decode_bsfs_uninit(avctx);
av_freep(&avctx->internal->pool);
}
av_freep(&avctx->internal);
avctx->codec = NULL;
goto end;
} | {
"deleted": [
{
"line_no": 486,
"char_start": 20499,
"char_end": 20523,
"line": " if (avctx->codec &&\n"
}
],
"added": [
{
"line_no": 486,
"char_start": 20499,
"char_end": 20546,
"line": " if (avctx->codec && avctx->codec->close &&\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 20522,
"char_end": 20545,
"chars": " avctx->codec->close &&"
}
]
} | github.com/FFmpeg/FFmpeg/commit/8df6884832ec413cf032dfaa45c23b1c7876670c | libavcodec/utils.c | cwe-476 |
tflite::Subgraph::Invoke | TfLiteStatus Subgraph::Invoke() {
if (!consistent_) {
ReportError("Invoke called on model that is not consistent.");
return kTfLiteError;
}
TfLiteStatus status = kTfLiteOk;
if (state_ == kStateUninvokable) {
ReportError("Invoke called on model that is not ready.");
return kTfLiteError;
} else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) {
ReportError("Non-persistent memory is not available.");
return kTfLiteError;
}
// This is only needed for UseNNAPI(true);
if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) {
TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate()));
// only need to modify the graph once upon the first invocation.
applied_nnapi_delegate_ = true;
}
// Invocations are always done in node order.
// Note that calling Invoke repeatedly will cause the original memory plan to
// be reused, unless either ResizeInputTensor() or AllocateTensors() has been
// called.
for (int execution_plan_index = 0;
execution_plan_index < execution_plan_.size(); execution_plan_index++) {
if (execution_plan_index == next_execution_plan_index_to_prepare_) {
TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors());
TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >=
execution_plan_index);
}
int node_index = execution_plan_[execution_plan_index];
TfLiteNode& node = nodes_and_registration_[node_index].first;
const TfLiteRegistration& registration =
nodes_and_registration_[node_index].second;
const char* op_name = nullptr;
if (profiler_) op_name = GetTFLiteOpName(registration);
TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index);
// TODO(ycling): This is an extra loop through inputs to check if the data
// need to be copied from Delegate buffer to raw memory, which is often not
// needed. We may want to cache this in prepare to know if this needs to be
// done for a node or not.
for (int i = 0; i < node.inputs->size; ++i) {
int tensor_index = node.inputs->data[i];
if (tensor_index == kTfLiteOptionalTensor) {
continue;
}
TfLiteTensor* tensor = &tensors_[tensor_index];
if (tensor->delegate && tensor->delegate != node.delegate &&
tensor->data_is_stale) {
TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index));
}
}
if (check_cancelled_func_ != nullptr &&
check_cancelled_func_(cancellation_data_)) {
ReportError("Client requested cancel during Invoke()");
return kTfLiteError;
}
EnsureTensorsVectorCapacity();
tensor_resized_since_op_invoke_ = false;
if (OpInvoke(registration, &node) != kTfLiteOk) {
return ReportOpError(&context_, node, registration, node_index,
"failed to invoke");
}
// Force execution prep for downstream ops if the latest op triggered the
// resize of a dynamic tensor.
if (tensor_resized_since_op_invoke_ &&
HasDynamicTensor(context_, node.outputs)) {
next_execution_plan_index_to_prepare_ = execution_plan_index + 1;
// This happens when an intermediate dynamic tensor is resized.
// We don't have to prepare all the ops, but we need to recompute
// the allocation plan.
if (next_execution_plan_index_to_plan_allocation_ >
next_execution_plan_index_to_prepare_) {
next_execution_plan_index_to_plan_allocation_ =
next_execution_plan_index_to_prepare_;
if (memory_planner_) {
TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter(
next_execution_plan_index_to_plan_allocation_ - 1));
}
}
}
}
return status;
} | TfLiteStatus Subgraph::Invoke() {
if (!consistent_) {
ReportError("Invoke called on model that is not consistent.");
return kTfLiteError;
}
TfLiteStatus status = kTfLiteOk;
if (state_ == kStateUninvokable) {
ReportError("Invoke called on model that is not ready.");
return kTfLiteError;
} else if (memory_planner_ && !memory_planner_->HasNonPersistentMemory()) {
ReportError("Non-persistent memory is not available.");
return kTfLiteError;
}
// This is only needed for UseNNAPI(true);
if (should_apply_nnapi_delegate_ && !applied_nnapi_delegate_) {
TF_LITE_ENSURE_OK(&context_, ModifyGraphWithDelegate(NnApiDelegate()));
// only need to modify the graph once upon the first invocation.
applied_nnapi_delegate_ = true;
}
// Invocations are always done in node order.
// Note that calling Invoke repeatedly will cause the original memory plan to
// be reused, unless either ResizeInputTensor() or AllocateTensors() has been
// called.
for (int execution_plan_index = 0;
execution_plan_index < execution_plan_.size(); execution_plan_index++) {
if (execution_plan_index == next_execution_plan_index_to_prepare_) {
TF_LITE_ENSURE_STATUS(PrepareOpsAndTensors());
TF_LITE_ENSURE(&context_, next_execution_plan_index_to_prepare_ >=
execution_plan_index);
}
int node_index = execution_plan_[execution_plan_index];
TfLiteNode& node = nodes_and_registration_[node_index].first;
const TfLiteRegistration& registration =
nodes_and_registration_[node_index].second;
const char* op_name = nullptr;
if (profiler_) op_name = GetTFLiteOpName(registration);
TFLITE_SCOPED_TAGGED_OPERATOR_PROFILE(profiler_.get(), op_name, node_index);
// TODO(ycling): This is an extra loop through inputs to check if the data
// need to be copied from Delegate buffer to raw memory, which is often not
// needed. We may want to cache this in prepare to know if this needs to be
// done for a node or not.
for (int i = 0; i < node.inputs->size; ++i) {
int tensor_index = node.inputs->data[i];
if (tensor_index == kTfLiteOptionalTensor) {
continue;
}
TfLiteTensor* tensor = &tensors_[tensor_index];
if (tensor->delegate && tensor->delegate != node.delegate &&
tensor->data_is_stale) {
TF_LITE_ENSURE_STATUS(EnsureTensorDataIsReadable(tensor_index));
}
if (tensor->data.raw == nullptr && tensor->bytes > 0) {
if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1) {
// In general, having a tensor here with no buffer will be an error.
// However, for the reshape operator, the second input tensor is only
// used for the shape, not for the data. Thus, null buffer is ok.
continue;
} else {
// In all other cases, we need to return an error as otherwise we will
// trigger a null pointer dereference (likely).
ReportError("Input tensor %d lacks data", tensor_index);
return kTfLiteError;
}
}
}
if (check_cancelled_func_ != nullptr &&
check_cancelled_func_(cancellation_data_)) {
ReportError("Client requested cancel during Invoke()");
return kTfLiteError;
}
EnsureTensorsVectorCapacity();
tensor_resized_since_op_invoke_ = false;
if (OpInvoke(registration, &node) != kTfLiteOk) {
return ReportOpError(&context_, node, registration, node_index,
"failed to invoke");
}
// Force execution prep for downstream ops if the latest op triggered the
// resize of a dynamic tensor.
if (tensor_resized_since_op_invoke_ &&
HasDynamicTensor(context_, node.outputs)) {
next_execution_plan_index_to_prepare_ = execution_plan_index + 1;
// This happens when an intermediate dynamic tensor is resized.
// We don't have to prepare all the ops, but we need to recompute
// the allocation plan.
if (next_execution_plan_index_to_plan_allocation_ >
next_execution_plan_index_to_prepare_) {
next_execution_plan_index_to_plan_allocation_ =
next_execution_plan_index_to_prepare_;
if (memory_planner_) {
TF_LITE_ENSURE_STATUS(memory_planner_->ResetAllocationsAfter(
next_execution_plan_index_to_plan_allocation_ - 1));
}
}
}
}
return status;
} | {
"deleted": [],
"added": [
{
"line_no": 57,
"char_start": 2461,
"char_end": 2523,
"line": " if (tensor->data.raw == nullptr && tensor->bytes > 0) {\n"
},
{
"line_no": 58,
"char_start": 2523,
"char_end": 2599,
"line": " if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1) {\n"
},
{
"line_no": 62,
"char_start": 2834,
"char_end": 2854,
"line": " continue;\n"
},
{
"line_no": 63,
"char_start": 2854,
"char_end": 2871,
"line": " } else {\n"
},
{
"line_no": 66,
"char_start": 3010,
"char_end": 3077,
"line": " ReportError(\"Input tensor %d lacks data\", tensor_index);\n"
},
{
"line_no": 67,
"char_start": 3077,
"char_end": 3108,
"line": " return kTfLiteError;\n"
},
{
"line_no": 68,
"char_start": 3108,
"char_end": 3118,
"line": " }\n"
},
{
"line_no": 69,
"char_start": 3118,
"char_end": 3126,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2465,
"char_end": 3130,
"chars": " if (tensor->data.raw == nullptr && tensor->bytes > 0) {\n if (registration.builtin_code == kTfLiteBuiltinReshape && i == 1) {\n // In general, having a tensor here with no buffer will be an error.\n // However, for the reshape operator, the second input tensor is only\n // used for the shape, not for the data. Thus, null buffer is ok.\n continue;\n } else {\n // In all other cases, we need to return an error as otherwise we will\n // trigger a null pointer dereference (likely).\n ReportError(\"Input tensor %d lacks data\", tensor_index);\n return kTfLiteError;\n }\n }\n "
}
]
} | github.com/tensorflow/tensorflow/commit/0b5662bc2be13a8c8f044d925d87fb6e56247cd8 | tensorflow/lite/core/subgraph.cc | cwe-476 |
store_versioninfo_gnu_verdef | static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
} | static Sdb *store_versioninfo_gnu_verdef(ELFOBJ *bin, Elf_(Shdr) *shdr, int sz) {
const char *section_name = "";
const char *link_section_name = "";
char *end = NULL;
Elf_(Shdr) *link_shdr = NULL;
ut8 dfs[sizeof (Elf_(Verdef))] = {0};
Sdb *sdb;
int cnt, i;
if (shdr->sh_link > bin->ehdr.e_shnum) {
return false;
}
link_shdr = &bin->shdr[shdr->sh_link];
if (shdr->sh_size < 1 || shdr->sh_size > SIZE_MAX) {
return false;
}
Elf_(Verdef) *defs = calloc (shdr->sh_size, sizeof (char));
if (!defs) {
return false;
}
if (bin->shstrtab && shdr->sh_name < bin->shstrtab_size) {
section_name = &bin->shstrtab[shdr->sh_name];
}
if (link_shdr && bin->shstrtab && link_shdr->sh_name < bin->shstrtab_size) {
link_section_name = &bin->shstrtab[link_shdr->sh_name];
}
if (!defs) {
bprintf ("Warning: Cannot allocate memory (Check Elf_(Verdef))\n");
return NULL;
}
sdb = sdb_new0 ();
end = (char *)defs + shdr->sh_size;
sdb_set (sdb, "section_name", section_name, 0);
sdb_num_set (sdb, "entries", shdr->sh_info, 0);
sdb_num_set (sdb, "addr", shdr->sh_addr, 0);
sdb_num_set (sdb, "offset", shdr->sh_offset, 0);
sdb_num_set (sdb, "link", shdr->sh_link, 0);
sdb_set (sdb, "link_section_name", link_section_name, 0);
for (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && (end - (char *)defs > i); ++cnt) {
Sdb *sdb_verdef = sdb_new0 ();
char *vstart = ((char*)defs) + i;
char key[32] = {0};
Elf_(Verdef) *verdef = (Elf_(Verdef)*)vstart;
Elf_(Verdaux) aux = {0};
int j = 0;
int isum = 0;
r_buf_read_at (bin->b, shdr->sh_offset + i, dfs, sizeof (Elf_(Verdef)));
verdef->vd_version = READ16 (dfs, j)
verdef->vd_flags = READ16 (dfs, j)
verdef->vd_ndx = READ16 (dfs, j)
verdef->vd_cnt = READ16 (dfs, j)
verdef->vd_hash = READ32 (dfs, j)
verdef->vd_aux = READ32 (dfs, j)
verdef->vd_next = READ32 (dfs, j)
int vdaux = verdef->vd_aux;
if (vdaux < 1 || (char *)UINTPTR_MAX - vstart < vdaux) {
sdb_free (sdb_verdef);
goto out_error;
}
vstart += vdaux;
if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {
sdb_free (sdb_verdef);
goto out_error;
}
j = 0;
aux.vda_name = READ32 (vstart, j)
aux.vda_next = READ32 (vstart, j)
isum = i + verdef->vd_aux;
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
goto out_error;
}
sdb_num_set (sdb_verdef, "idx", i, 0);
sdb_num_set (sdb_verdef, "vd_version", verdef->vd_version, 0);
sdb_num_set (sdb_verdef, "vd_ndx", verdef->vd_ndx, 0);
sdb_num_set (sdb_verdef, "vd_cnt", verdef->vd_cnt, 0);
sdb_set (sdb_verdef, "vda_name", &bin->dynstr[aux.vda_name], 0);
sdb_set (sdb_verdef, "flags", get_ver_flags (verdef->vd_flags), 0);
for (j = 1; j < verdef->vd_cnt; ++j) {
int k;
Sdb *sdb_parent = sdb_new0 ();
isum += aux.vda_next;
vstart += aux.vda_next;
if (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
k = 0;
aux.vda_name = READ32 (vstart, k)
aux.vda_next = READ32 (vstart, k)
if (aux.vda_name > bin->dynstr_size) {
sdb_free (sdb_verdef);
sdb_free (sdb_parent);
goto out_error;
}
sdb_num_set (sdb_parent, "idx", isum, 0);
sdb_num_set (sdb_parent, "parent", j, 0);
sdb_set (sdb_parent, "vda_name", &bin->dynstr[aux.vda_name], 0);
snprintf (key, sizeof (key), "parent%d", j - 1);
sdb_ns_set (sdb_verdef, key, sdb_parent);
}
snprintf (key, sizeof (key), "verdef%d", cnt);
sdb_ns_set (sdb, key, sdb_verdef);
if (!verdef->vd_next) {
sdb_free (sdb_verdef);
goto out_error;
}
if ((st32)verdef->vd_next < 1) {
eprintf ("Warning: Invalid vd_next in the ELF version\n");
break;
}
i += verdef->vd_next;
}
free (defs);
return sdb;
out_error:
free (defs);
sdb_free (sdb);
return NULL;
} | {
"deleted": [
{
"line_no": 39,
"char_start": 1241,
"char_end": 1331,
"line": "\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && ((char *)defs + i < end); ++cnt) {\n"
},
{
"line_no": 57,
"char_start": 1885,
"char_end": 1904,
"line": "\t\tif (vdaux < 1) {\n"
},
{
"line_no": 62,
"char_start": 1972,
"char_end": 2035,
"line": "\t\tif (vstart > end || vstart + sizeof (Elf_(Verdaux)) > end) {\n"
},
{
"line_no": 89,
"char_start": 2782,
"char_end": 2845,
"line": "\t\t\tif (vstart > end || vstart + sizeof(Elf_(Verdaux)) > end) {\n"
}
],
"added": [
{
"line_no": 39,
"char_start": 1241,
"char_end": 1331,
"line": "\tfor (cnt = 0, i = 0; i >= 0 && cnt < shdr->sh_info && (end - (char *)defs > i); ++cnt) {\n"
},
{
"line_no": 57,
"char_start": 1885,
"char_end": 1944,
"line": "\t\tif (vdaux < 1 || (char *)UINTPTR_MAX - vstart < vdaux) {\n"
},
{
"line_no": 62,
"char_start": 2012,
"char_end": 2075,
"line": "\t\tif (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {\n"
},
{
"line_no": 89,
"char_start": 2822,
"char_end": 2886,
"line": "\t\t\tif (vstart > end || end - vstart < sizeof (Elf_(Verdaux))) {\n"
}
]
} | {
"deleted": [
{
"char_start": 1310,
"char_end": 1311,
"chars": "+"
},
{
"char_start": 1313,
"char_end": 1319,
"chars": " < end"
},
{
"char_start": 2001,
"char_end": 2002,
"chars": "+"
},
{
"char_start": 2025,
"char_end": 2031,
"chars": " > end"
},
{
"char_start": 2812,
"char_end": 2813,
"chars": "+"
},
{
"char_start": 2835,
"char_end": 2841,
"chars": " > end"
}
],
"added": [
{
"char_start": 1297,
"char_end": 1303,
"chars": "end - "
},
{
"char_start": 1316,
"char_end": 1317,
"chars": ">"
},
{
"char_start": 1900,
"char_end": 1940,
"chars": " || (char *)UINTPTR_MAX - vstart < vdaux"
},
{
"char_start": 2034,
"char_end": 2040,
"chars": "end - "
},
{
"char_start": 2047,
"char_end": 2048,
"chars": "<"
},
{
"char_start": 2845,
"char_end": 2851,
"chars": "end - "
},
{
"char_start": 2858,
"char_end": 2859,
"chars": "<"
},
{
"char_start": 2866,
"char_end": 2867,
"chars": " "
}
]
} | github.com/radare/radare2/commit/62e39f34b2705131a2d08aff0c2e542c6a52cf0e | libr/bin/format/elf/elf.c | cwe-476 |
upnp_redirect | upnp_redirect(const char * rhost, unsigned short eport,
const char * iaddr, unsigned short iport,
const char * protocol, const char * desc,
unsigned int leaseduration)
{
int proto, r;
char iaddr_old[32];
char rhost_old[32];
unsigned short iport_old;
struct in_addr address;
unsigned int timestamp;
proto = proto_atoi(protocol);
if(inet_aton(iaddr, &address) <= 0) {
syslog(LOG_ERR, "inet_aton(%s) FAILED", iaddr);
return -1;
}
if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm,
eport, address, iport)) {
syslog(LOG_INFO, "redirection permission check failed for "
"%hu->%s:%hu %s", eport, iaddr, iport, protocol);
return -3;
}
/* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001)
* - 2.2.20.PortMappingDescription :
* Overwriting Previous / Existing Port Mappings:
* If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient
* are exactly the same as an existing mapping, the existing mapping values
* for InternalPort, PortMappingDescription, PortMappingEnabled and
* PortMappingLeaseDuration are overwritten.
* Rejecting a New Port Mapping:
* In cases where the RemoteHost, ExternalPort and PortMappingProtocol
* are the same as an existing mapping, but the InternalClient is
* different, the action is rejected with an appropriate error.
* Add or Reject New Port Mapping behavior based on vendor implementation:
* In cases where the ExternalPort, PortMappingProtocol and InternalClient
* are the same, but RemoteHost is different, the vendor can choose to
* support both mappings simultaneously, or reject the second mapping
* with an appropriate error.
*
* - 2.4.16.AddPortMapping
* This action creates a new port mapping or overwrites an existing
* mapping with the same internal client. If the ExternalPort and
* PortMappingProtocol pair is already mapped to another internal client,
* an error is returned.
*
* IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010)
* Protocol ExternalPort RemoteHost InternalClient Result
* = = ≠ ≠ Failure
* = = ≠ = Failure or success
* (vendor specific)
* = = = ≠ Failure
* = = = = Success (overwrite)
*/
rhost_old[0] = '\0';
r = get_redirect_rule(ext_if_name, eport, proto,
iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0,
rhost_old, sizeof(rhost_old),
×tamp, 0, 0);
if(r == 0) {
if(strcmp(iaddr, iaddr_old)==0 &&
((rhost == NULL && rhost_old[0]=='\0') ||
(rhost && (strcmp(rhost, "*") == 0) && rhost_old[0]=='\0') ||
(rhost && (strcmp(rhost, rhost_old) == 0)))) {
syslog(LOG_INFO, "updating existing port mapping %hu %s (rhost '%s') => %s:%hu",
eport, protocol, rhost_old, iaddr_old, iport_old);
timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;
if(iport != iport_old) {
r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp);
} else {
r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp);
}
#ifdef ENABLE_LEASEFILE
if(r == 0) {
lease_file_remove(eport, proto);
lease_file_add(eport, iaddr, iport, proto, desc, timestamp);
}
#endif /* ENABLE_LEASEFILE */
return r;
} else {
syslog(LOG_INFO, "port %hu %s (rhost '%s') already redirected to %s:%hu",
eport, protocol, rhost_old, iaddr_old, iport_old);
return -2;
}
#ifdef CHECK_PORTINUSE
} else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) {
syslog(LOG_INFO, "port %hu protocol %s already in use",
eport, protocol);
return -4;
#endif /* CHECK_PORTINUSE */
} else {
timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;
syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s",
eport, iaddr, iport, protocol, desc);
return upnp_redirect_internal(rhost, eport, iaddr, iport, proto,
desc, timestamp);
}
} | upnp_redirect(const char * rhost, unsigned short eport,
const char * iaddr, unsigned short iport,
const char * protocol, const char * desc,
unsigned int leaseduration)
{
int proto, r;
char iaddr_old[32];
char rhost_old[32];
unsigned short iport_old;
struct in_addr address;
unsigned int timestamp;
proto = proto_atoi(protocol);
if(inet_aton(iaddr, &address) <= 0) {
syslog(LOG_ERR, "inet_aton(%s) FAILED", iaddr);
return -1;
}
if(!check_upnp_rule_against_permissions(upnppermlist, num_upnpperm,
eport, address, iport)) {
syslog(LOG_INFO, "redirection permission check failed for "
"%hu->%s:%hu %s", eport, iaddr, iport, protocol);
return -3;
}
if (desc == NULL)
desc = ""; /* assume empty description */
/* IGDv1 (WANIPConnection:1 Service Template Version 1.01 / Nov 12, 2001)
* - 2.2.20.PortMappingDescription :
* Overwriting Previous / Existing Port Mappings:
* If the RemoteHost, ExternalPort, PortMappingProtocol and InternalClient
* are exactly the same as an existing mapping, the existing mapping values
* for InternalPort, PortMappingDescription, PortMappingEnabled and
* PortMappingLeaseDuration are overwritten.
* Rejecting a New Port Mapping:
* In cases where the RemoteHost, ExternalPort and PortMappingProtocol
* are the same as an existing mapping, but the InternalClient is
* different, the action is rejected with an appropriate error.
* Add or Reject New Port Mapping behavior based on vendor implementation:
* In cases where the ExternalPort, PortMappingProtocol and InternalClient
* are the same, but RemoteHost is different, the vendor can choose to
* support both mappings simultaneously, or reject the second mapping
* with an appropriate error.
*
* - 2.4.16.AddPortMapping
* This action creates a new port mapping or overwrites an existing
* mapping with the same internal client. If the ExternalPort and
* PortMappingProtocol pair is already mapped to another internal client,
* an error is returned.
*
* IGDv2 (WANIPConnection:2 Service Standardized DCP (SDCP) Sep 10, 2010)
* Protocol ExternalPort RemoteHost InternalClient Result
* = = ≠ ≠ Failure
* = = ≠ = Failure or success
* (vendor specific)
* = = = ≠ Failure
* = = = = Success (overwrite)
*/
rhost_old[0] = '\0';
r = get_redirect_rule(ext_if_name, eport, proto,
iaddr_old, sizeof(iaddr_old), &iport_old, 0, 0,
rhost_old, sizeof(rhost_old),
×tamp, 0, 0);
if(r == 0) {
if(strcmp(iaddr, iaddr_old)==0 &&
((rhost == NULL && rhost_old[0]=='\0') ||
(rhost && (strcmp(rhost, "*") == 0) && rhost_old[0]=='\0') ||
(rhost && (strcmp(rhost, rhost_old) == 0)))) {
syslog(LOG_INFO, "updating existing port mapping %hu %s (rhost '%s') => %s:%hu",
eport, protocol, rhost_old, iaddr_old, iport_old);
timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;
if(iport != iport_old) {
r = update_portmapping(ext_if_name, eport, proto, iport, desc, timestamp);
} else {
r = update_portmapping_desc_timestamp(ext_if_name, eport, proto, desc, timestamp);
}
#ifdef ENABLE_LEASEFILE
if(r == 0) {
lease_file_remove(eport, proto);
lease_file_add(eport, iaddr, iport, proto, desc, timestamp);
}
#endif /* ENABLE_LEASEFILE */
return r;
} else {
syslog(LOG_INFO, "port %hu %s (rhost '%s') already redirected to %s:%hu",
eport, protocol, rhost_old, iaddr_old, iport_old);
return -2;
}
#ifdef CHECK_PORTINUSE
} else if (port_in_use(ext_if_name, eport, proto, iaddr, iport) > 0) {
syslog(LOG_INFO, "port %hu protocol %s already in use",
eport, protocol);
return -4;
#endif /* CHECK_PORTINUSE */
} else {
timestamp = (leaseduration > 0) ? upnp_time() + leaseduration : 0;
syslog(LOG_INFO, "redirecting port %hu to %s:%hu protocol %s for: %s",
eport, iaddr, iport, protocol, desc);
return upnp_redirect_internal(rhost, eport, iaddr, iport, proto,
desc, timestamp);
}
} | {
"deleted": [],
"added": [
{
"line_no": 25,
"char_start": 767,
"char_end": 768,
"line": "\n"
},
{
"line_no": 26,
"char_start": 768,
"char_end": 787,
"line": "\tif (desc == NULL)\n"
},
{
"line_no": 27,
"char_start": 787,
"char_end": 831,
"line": "\t\tdesc = \"\";\t/* assume empty description */\n"
},
{
"line_no": 28,
"char_start": 831,
"char_end": 832,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 767,
"char_end": 832,
"chars": "\n\tif (desc == NULL)\n\t\tdesc = \"\";\t/* assume empty description */\n\n"
}
]
} | github.com/miniupnp/miniupnp/commit/f321c2066b96d18afa5158dfa2d2873a2957ef38 | miniupnpd/upnpredirect.c | cwe-476 |
WriteOnePNGImage | static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)
{
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
Image
*image;
ImageInfo
*image_info;
char
s[2];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
PNGErrorInfo
error_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
image = CloneImage(IMimage,0,0,MagickFalse,exception);
image_info=(ImageInfo *) CloneImageInfo(IMimage_info);
if (image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed");
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MagickPathExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MagickPathExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s",
im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s",
libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_vpAg=mng_info->ping_exclude_vpAg;
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image,exception);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register Quantum
*r;
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 ||
LosslessReduceDepthOK(image,exception) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
number_opaque = (int) image->colors;
number_transparent = 0;
number_semitransparent = 0;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 &&
image->alpha_trait == UndefinedPixelTrait)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
if (image->alpha_trait != UndefinedPixelTrait)
{
number_transparent = 2;
number_semitransparent = 1;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->alpha_trait is MagickFalse, we ignore the alpha channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
int
n;
PixelInfo
opaque[260],
semitransparent[260],
transparent[260];
register const Quantum
*s;
register Quantum
*q,
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->alpha_trait=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait == UndefinedPixelTrait ||
GetPixelAlpha(image,q) == OpaqueAlpha)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelInfoPixel(image, q, opaque);
opaque[0].alpha=OpaqueAlpha;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (Magick_png_color_equal(image,q,opaque+i))
break;
}
if (i == (ssize_t) number_opaque && number_opaque < 259)
{
number_opaque++;
GetPixelInfoPixel(image, q, opaque+i);
opaque[i].alpha=OpaqueAlpha;
}
}
}
else if (GetPixelAlpha(image,q) == TransparentAlpha)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelInfoPixel(image, q, transparent);
ping_trans_color.red=(unsigned short)
GetPixelRed(image,q);
ping_trans_color.green=(unsigned short)
GetPixelGreen(image,q);
ping_trans_color.blue=(unsigned short)
GetPixelBlue(image,q);
ping_trans_color.gray=(unsigned short)
GetPixelGray(image,q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (Magick_png_color_equal(image,q,transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelInfoPixel(image,q,transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelInfoPixel(image,q,semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (Magick_png_color_equal(image,q,semitransparent+i)
&& GetPixelAlpha(image,q) ==
semitransparent[i].alpha)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelInfoPixel(image, q, semitransparent+i);
}
}
}
q+=GetPixelChannels(image);
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != GetPixelGreen(image,s) ||
GetPixelRed(image,s) != GetPixelBlue(image,s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != 0 &&
GetPixelRed(image,s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
}
}
}
}
if (image_colors < 257)
{
PixelInfo
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors,exception) ==
MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->alpha_trait == UndefinedPixelTrait ||
image->colormap[i].alpha == GetPixelAlpha(image,q)) &&
image->colormap[i].red == GetPixelRed(image,q) &&
image->colormap[i].green == GetPixelGreen(image,q) &&
image->colormap[i].blue == GetPixelBlue(image,q))
{
SetPixelIndex(image,i,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) < OpaqueAlpha/2)
{
SetPixelViaPixelInfo(image,&image->background_color,r);
SetPixelAlpha(image,TransparentAlpha,r);
}
else
SetPixelAlpha(image,OpaqueAlpha,r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].alpha =
(image->colormap[i].alpha > TransparentAlpha/2 ?
TransparentAlpha : OpaqueAlpha);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR04PixelRGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR03RGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR02PixelBlue(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 &&
GetPixelAlpha(image,r) == OpaqueAlpha)
{
SetPixelRed(image,ScaleCharToQuantum(0x24),r);
}
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
register const Quantum
*q;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) != TransparentAlpha &&
(unsigned short) GetPixelRed(image,q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(image,q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(image,q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q+=GetPixelChannels(image);
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->alpha_trait !=
UndefinedPixelTrait ? MagickTrue : MagickFalse;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",IMimage->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->resolution.x != 0) && (image->resolution.y != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;
ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorAlphaType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteAlphaType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->alpha_trait == UndefinedPixelTrait &&
ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(GetPixelInfoIntensity(image,
image->colormap)) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=
ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte)
ScaleQuantumToChar(image->colormap[i].alpha);
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16) ((maxval/65535.)*
(ScaleQuantumToShort(((GetPixelInfoIntensity(image,
&image->background_color))) +.5)));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This will be addressed soon in a
release that accomodates "-define png:compression-strategy", etc.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)
{
/* Add an opaque matte channel */
image->alpha_trait = BlendPixelTrait;
(void) SetImageAlpha(image,OpaqueAlpha,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
ping_have_iCCP = MagickTrue;
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
}
else
{
/* Do not write hex-encoded ICC chunk */
name=GetNextImageProfile(image);
continue;
}
}
#endif /* WRITE_iCCP */
if (LocaleCompare(name,"exif") == 0)
{
/* Do not write hex-encoded ICC chunk; we will
write it later as an eXIf chunk */
name=GetNextImageProfile(image);
continue;
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXt chunk with uuencoded %s profile",
name);
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
}
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME",exception);
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify",exception);
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp,exception);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
/* write any png-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging);
png_write_info(ping,ping_info);
/* write any PNG-chunk-m profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging);
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
/* write vpAg chunk (deprecated, replaced by caNv) */
if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
unsigned char
chunk[14];
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
}
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const Quantum
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",
pass);
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property,exception);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write any PNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging);
/* write exIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
PNGType(chunk,mng_eXIf);
if (length < 7)
{
ping_profile=DestroyStringInfo(ping_profile);
break; /* otherwise crashes */
}
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data+6);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),
data+6, (uInt) length));
ping_profile=DestroyStringInfo(ping_profile);
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
} | static MagickBooleanType WriteOnePNGImage(MngInfo *mng_info,
const ImageInfo *IMimage_info,Image *IMimage,ExceptionInfo *exception)
{
char
im_vers[32],
libpng_runv[32],
libpng_vers[32],
zlib_runv[32],
zlib_vers[32];
Image
*image;
ImageInfo
*image_info;
char
s[2];
const char
*name,
*property,
*value;
const StringInfo
*profile;
int
num_passes,
pass,
ping_wrote_caNv;
png_byte
ping_trans_alpha[256];
png_color
palette[257];
png_color_16
ping_background,
ping_trans_color;
png_info
*ping_info;
png_struct
*ping;
png_uint_32
ping_height,
ping_width;
ssize_t
y;
MagickBooleanType
image_matte,
logging,
matte,
ping_have_blob,
ping_have_cheap_transparency,
ping_have_color,
ping_have_non_bw,
ping_have_PLTE,
ping_have_bKGD,
ping_have_eXIf,
ping_have_iCCP,
ping_have_pHYs,
ping_have_sRGB,
ping_have_tRNS,
ping_exclude_bKGD,
ping_exclude_cHRM,
ping_exclude_date,
/* ping_exclude_EXIF, */
ping_exclude_eXIf,
ping_exclude_gAMA,
ping_exclude_iCCP,
/* ping_exclude_iTXt, */
ping_exclude_oFFs,
ping_exclude_pHYs,
ping_exclude_sRGB,
ping_exclude_tEXt,
ping_exclude_tIME,
/* ping_exclude_tRNS, */
ping_exclude_vpAg,
ping_exclude_caNv,
ping_exclude_zCCP, /* hex-encoded iCCP */
ping_exclude_zTXt,
ping_preserve_colormap,
ping_preserve_iCCP,
ping_need_colortype_warning,
status,
tried_332,
tried_333,
tried_444;
MemoryInfo
*volatile pixel_info;
QuantumInfo
*quantum_info;
PNGErrorInfo
error_info;
register ssize_t
i,
x;
unsigned char
*ping_pixels;
volatile int
image_colors,
ping_bit_depth,
ping_color_type,
ping_interlace_method,
ping_compression_method,
ping_filter_method,
ping_num_trans;
volatile size_t
image_depth,
old_bit_depth;
size_t
quality,
rowbytes,
save_image_depth;
int
j,
number_colors,
number_opaque,
number_semitransparent,
number_transparent,
ping_pHYs_unit_type;
png_uint_32
ping_pHYs_x_resolution,
ping_pHYs_y_resolution;
logging=LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter WriteOnePNGImage()");
image = CloneImage(IMimage,0,0,MagickFalse,exception);
if (image == (Image *) NULL)
return(MagickFalse);
image_info=(ImageInfo *) CloneImageInfo(IMimage_info);
if (image_info == (ImageInfo *) NULL)
ThrowWriterException(ResourceLimitError, "MemoryAllocationFailed");
/* Define these outside of the following "if logging()" block so they will
* show in debuggers.
*/
*im_vers='\0';
(void) ConcatenateMagickString(im_vers,
MagickLibVersionText,MagickPathExtent);
(void) ConcatenateMagickString(im_vers,
MagickLibAddendum,MagickPathExtent);
*libpng_vers='\0';
(void) ConcatenateMagickString(libpng_vers,
PNG_LIBPNG_VER_STRING,32);
*libpng_runv='\0';
(void) ConcatenateMagickString(libpng_runv,
png_get_libpng_ver(NULL),32);
*zlib_vers='\0';
(void) ConcatenateMagickString(zlib_vers,
ZLIB_VERSION,32);
*zlib_runv='\0';
(void) ConcatenateMagickString(zlib_runv,
zlib_version,32);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," IM version = %s",
im_vers);
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Libpng version = %s",
libpng_vers);
if (LocaleCompare(libpng_vers,libpng_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
libpng_runv);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule()," Zlib version = %s",
zlib_vers);
if (LocaleCompare(zlib_vers,zlib_runv) != 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule()," running with %s",
zlib_runv);
}
}
/* Initialize some stuff */
ping_bit_depth=0,
ping_color_type=0,
ping_interlace_method=0,
ping_compression_method=0,
ping_filter_method=0,
ping_num_trans = 0;
ping_background.red = 0;
ping_background.green = 0;
ping_background.blue = 0;
ping_background.gray = 0;
ping_background.index = 0;
ping_trans_color.red=0;
ping_trans_color.green=0;
ping_trans_color.blue=0;
ping_trans_color.gray=0;
ping_pHYs_unit_type = 0;
ping_pHYs_x_resolution = 0;
ping_pHYs_y_resolution = 0;
ping_have_blob=MagickFalse;
ping_have_cheap_transparency=MagickFalse;
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
ping_have_PLTE=MagickFalse;
ping_have_bKGD=MagickFalse;
ping_have_eXIf=MagickTrue;
ping_have_iCCP=MagickFalse;
ping_have_pHYs=MagickFalse;
ping_have_sRGB=MagickFalse;
ping_have_tRNS=MagickFalse;
ping_exclude_bKGD=mng_info->ping_exclude_bKGD;
ping_exclude_caNv=mng_info->ping_exclude_caNv;
ping_exclude_cHRM=mng_info->ping_exclude_cHRM;
ping_exclude_date=mng_info->ping_exclude_date;
ping_exclude_eXIf=mng_info->ping_exclude_eXIf;
ping_exclude_gAMA=mng_info->ping_exclude_gAMA;
ping_exclude_iCCP=mng_info->ping_exclude_iCCP;
/* ping_exclude_iTXt=mng_info->ping_exclude_iTXt; */
ping_exclude_oFFs=mng_info->ping_exclude_oFFs;
ping_exclude_pHYs=mng_info->ping_exclude_pHYs;
ping_exclude_sRGB=mng_info->ping_exclude_sRGB;
ping_exclude_tEXt=mng_info->ping_exclude_tEXt;
ping_exclude_tIME=mng_info->ping_exclude_tIME;
/* ping_exclude_tRNS=mng_info->ping_exclude_tRNS; */
ping_exclude_vpAg=mng_info->ping_exclude_vpAg;
ping_exclude_zCCP=mng_info->ping_exclude_zCCP; /* hex-encoded iCCP in zTXt */
ping_exclude_zTXt=mng_info->ping_exclude_zTXt;
ping_preserve_colormap = mng_info->ping_preserve_colormap;
ping_preserve_iCCP = mng_info->ping_preserve_iCCP;
ping_need_colortype_warning = MagickFalse;
/* Recognize the ICC sRGB profile and convert it to the sRGB chunk,
* i.e., eliminate the ICC profile and set image->rendering_intent.
* Note that this will not involve any changes to the actual pixels
* but merely passes information to applications that read the resulting
* PNG image.
*
* To do: recognize other variants of the sRGB profile, using the CRC to
* verify all recognized variants including the 7 already known.
*
* Work around libpng16+ rejecting some "known invalid sRGB profiles".
*
* Use something other than image->rendering_intent to record the fact
* that the sRGB profile was found.
*
* Record the ICC version (currently v2 or v4) of the incoming sRGB ICC
* profile. Record the Blackpoint Compensation, if any.
*/
if (ping_exclude_sRGB == MagickFalse && ping_preserve_iCCP == MagickFalse)
{
char
*name;
const StringInfo
*profile;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
int
icheck,
got_crc=0;
png_uint_32
length,
profile_crc=0;
unsigned char
*data;
length=(png_uint_32) GetStringInfoLength(profile);
for (icheck=0; sRGB_info[icheck].len > 0; icheck++)
{
if (length == sRGB_info[icheck].len)
{
if (got_crc == 0)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got a %lu-byte ICC profile (potentially sRGB)",
(unsigned long) length);
data=GetStringInfoDatum(profile);
profile_crc=crc32(0,data,length);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" with crc=%8x",(unsigned int) profile_crc);
got_crc++;
}
if (profile_crc == sRGB_info[icheck].crc)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" It is sRGB with rendering intent = %s",
Magick_RenderingIntentString_from_PNG_RenderingIntent(
sRGB_info[icheck].intent));
if (image->rendering_intent==UndefinedIntent)
{
image->rendering_intent=
Magick_RenderingIntent_from_PNG_RenderingIntent(
sRGB_info[icheck].intent);
}
ping_exclude_iCCP = MagickTrue;
ping_exclude_zCCP = MagickTrue;
ping_have_sRGB = MagickTrue;
break;
}
}
}
if (sRGB_info[icheck].len == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Got %lu-byte ICC profile not recognized as sRGB",
(unsigned long) length);
}
}
name=GetNextImageProfile(image);
}
}
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
if (logging != MagickFalse)
{
if (image->storage_class == UndefinedClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=UndefinedClass");
if (image->storage_class == DirectClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=DirectClass");
if (image->storage_class == PseudoClass)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->storage_class=PseudoClass");
(void) LogMagickEvent(CoderEvent,GetMagickModule(), image->taint ?
" image->taint=MagickTrue":
" image->taint=MagickFalse");
}
if (image->storage_class == PseudoClass &&
(mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(mng_info->write_png_colortype != 1 &&
mng_info->write_png_colortype != 5)))
{
(void) SyncImage(image,exception);
image->storage_class = DirectClass;
}
if (ping_preserve_colormap == MagickFalse)
{
if (image->storage_class != PseudoClass && image->colormap != NULL)
{
/* Free the bogus colormap; it can cause trouble later */
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Freeing bogus colormap");
(void) RelinquishMagickMemory(image->colormap);
image->colormap=NULL;
}
}
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
(void) TransformImageColorspace(image,sRGBColorspace,exception);
/*
Sometimes we get PseudoClass images whose RGB values don't match
the colors in the colormap. This code syncs the RGB values.
*/
if (image->depth <= 8 && image->taint && image->storage_class == PseudoClass)
(void) SyncImage(image,exception);
#if (MAGICKCORE_QUANTUM_DEPTH == 8)
if (image->depth > 8)
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reducing PNG bit depth to 8 since this is a Q8 build.");
image->depth=8;
}
#endif
/* Respect the -depth option */
if (image->depth < 4)
{
register Quantum
*r;
if (image->depth > 2)
{
/* Scale to 4-bit */
LBR04PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR04PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR04PacketRGBO(image->colormap[i]);
}
}
}
else if (image->depth > 1)
{
/* Scale to 2-bit */
LBR02PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR02PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR02PacketRGBO(image->colormap[i]);
}
}
}
else
{
/* Scale to 1-bit */
LBR01PacketRGBO(image->background_color);
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
LBR01PixelRGBA(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
for (i=0; i < (ssize_t) image->colors; i++)
{
LBR01PacketRGBO(image->colormap[i]);
}
}
}
}
/* To do: set to next higher multiple of 8 */
if (image->depth < 8)
image->depth=8;
#if (MAGICKCORE_QUANTUM_DEPTH > 16)
/* PNG does not handle depths greater than 16 so reduce it even
* if lossy
*/
if (image->depth > 8)
image->depth=16;
#endif
#if (MAGICKCORE_QUANTUM_DEPTH > 8)
if (image->depth > 8)
{
/* To do: fill low byte properly */
image->depth=16;
}
if (image->depth == 16 && mng_info->write_png_depth != 16)
if (mng_info->write_png8 ||
LosslessReduceDepthOK(image,exception) != MagickFalse)
image->depth = 8;
#endif
image_colors = (int) image->colors;
number_opaque = (int) image->colors;
number_transparent = 0;
number_semitransparent = 0;
if (mng_info->write_png_colortype &&
(mng_info->write_png_colortype > 4 || (mng_info->write_png_depth >= 8 &&
mng_info->write_png_colortype < 4 &&
image->alpha_trait == UndefinedPixelTrait)))
{
/* Avoid the expensive BUILD_PALETTE operation if we're sure that we
* are not going to need the result.
*/
if (mng_info->write_png_colortype == 1 ||
mng_info->write_png_colortype == 5)
ping_have_color=MagickFalse;
if (image->alpha_trait != UndefinedPixelTrait)
{
number_transparent = 2;
number_semitransparent = 1;
}
}
if (mng_info->write_png_colortype < 7)
{
/* BUILD_PALETTE
*
* Normally we run this just once, but in the case of writing PNG8
* we reduce the transparency to binary and run again, then if there
* are still too many colors we reduce to a simple 4-4-4-1, then 3-3-3-1
* RGBA palette and run again, and then to a simple 3-3-2-1 RGBA
* palette. Then (To do) we take care of a final reduction that is only
* needed if there are still 256 colors present and one of them has both
* transparent and opaque instances.
*/
tried_332 = MagickFalse;
tried_333 = MagickFalse;
tried_444 = MagickFalse;
for (j=0; j<6; j++)
{
/*
* Sometimes we get DirectClass images that have 256 colors or fewer.
* This code will build a colormap.
*
* Also, sometimes we get PseudoClass images with an out-of-date
* colormap. This code will replace the colormap with a new one.
* Sometimes we get PseudoClass images that have more than 256 colors.
* This code will delete the colormap and change the image to
* DirectClass.
*
* If image->alpha_trait is MagickFalse, we ignore the alpha channel
* even though it sometimes contains left-over non-opaque values.
*
* Also we gather some information (number of opaque, transparent,
* and semitransparent pixels, and whether the image has any non-gray
* pixels or only black-and-white pixels) that we might need later.
*
* Even if the user wants to force GrayAlpha or RGBA (colortype 4 or 6)
* we need to check for bogus non-opaque values, at least.
*/
int
n;
PixelInfo
opaque[260],
semitransparent[260],
transparent[260];
register const Quantum
*s;
register Quantum
*q,
*r;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Enter BUILD_PALETTE:");
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->columns=%.20g",(double) image->columns);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->rows=%.20g",(double) image->rows);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->alpha_trait=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
if (image->storage_class == PseudoClass && image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Original colormap:");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < 256; i++)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
for (i=image->colors - 10; i < (ssize_t) image->colors; i++)
{
if (i > 255)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d",(int) image->colors);
if (image->colors == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" (zero means unknown)");
if (ping_preserve_colormap == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Regenerate the colormap");
}
image_colors=0;
number_opaque = 0;
number_semitransparent = 0;
number_transparent = 0;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (image->alpha_trait == UndefinedPixelTrait ||
GetPixelAlpha(image,q) == OpaqueAlpha)
{
if (number_opaque < 259)
{
if (number_opaque == 0)
{
GetPixelInfoPixel(image, q, opaque);
opaque[0].alpha=OpaqueAlpha;
number_opaque=1;
}
for (i=0; i< (ssize_t) number_opaque; i++)
{
if (Magick_png_color_equal(image,q,opaque+i))
break;
}
if (i == (ssize_t) number_opaque && number_opaque < 259)
{
number_opaque++;
GetPixelInfoPixel(image, q, opaque+i);
opaque[i].alpha=OpaqueAlpha;
}
}
}
else if (GetPixelAlpha(image,q) == TransparentAlpha)
{
if (number_transparent < 259)
{
if (number_transparent == 0)
{
GetPixelInfoPixel(image, q, transparent);
ping_trans_color.red=(unsigned short)
GetPixelRed(image,q);
ping_trans_color.green=(unsigned short)
GetPixelGreen(image,q);
ping_trans_color.blue=(unsigned short)
GetPixelBlue(image,q);
ping_trans_color.gray=(unsigned short)
GetPixelGray(image,q);
number_transparent = 1;
}
for (i=0; i< (ssize_t) number_transparent; i++)
{
if (Magick_png_color_equal(image,q,transparent+i))
break;
}
if (i == (ssize_t) number_transparent &&
number_transparent < 259)
{
number_transparent++;
GetPixelInfoPixel(image,q,transparent+i);
}
}
}
else
{
if (number_semitransparent < 259)
{
if (number_semitransparent == 0)
{
GetPixelInfoPixel(image,q,semitransparent);
number_semitransparent = 1;
}
for (i=0; i< (ssize_t) number_semitransparent; i++)
{
if (Magick_png_color_equal(image,q,semitransparent+i)
&& GetPixelAlpha(image,q) ==
semitransparent[i].alpha)
break;
}
if (i == (ssize_t) number_semitransparent &&
number_semitransparent < 259)
{
number_semitransparent++;
GetPixelInfoPixel(image, q, semitransparent+i);
}
}
}
q+=GetPixelChannels(image);
}
}
if (mng_info->write_png8 == MagickFalse &&
ping_exclude_bKGD == MagickFalse)
{
/* Add the background color to the palette, if it
* isn't already there.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Check colormap for background (%d,%d,%d)",
(int) image->background_color.red,
(int) image->background_color.green,
(int) image->background_color.blue);
}
for (i=0; i<number_opaque; i++)
{
if (opaque[i].red == image->background_color.red &&
opaque[i].green == image->background_color.green &&
opaque[i].blue == image->background_color.blue)
break;
}
if (number_opaque < 259 && i == number_opaque)
{
opaque[i] = image->background_color;
ping_background.index = i;
number_opaque++;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",(int) i);
}
}
else if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in the colormap to add background color");
}
image_colors=number_opaque+number_transparent+number_semitransparent;
if (logging != MagickFalse)
{
if (image_colors > 256)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has more than 256 colors");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image has %d colors",image_colors);
}
if (ping_preserve_colormap != MagickFalse)
break;
if (mng_info->write_png_colortype != 7) /* We won't need this info */
{
ping_have_color=MagickFalse;
ping_have_non_bw=MagickFalse;
if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
"incompatible colorspace");
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
}
if(image_colors > 256)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != GetPixelGreen(image,s) ||
GetPixelRed(image,s) != GetPixelBlue(image,s))
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
if (ping_have_color != MagickFalse)
break;
/* Worst case is black-and-white; we are looking at every
* pixel twice.
*/
if (ping_have_non_bw == MagickFalse)
{
s=q;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelRed(image,s) != 0 &&
GetPixelRed(image,s) != QuantumRange)
{
ping_have_non_bw=MagickTrue;
break;
}
s+=GetPixelChannels(image);
}
}
}
}
}
if (image_colors < 257)
{
PixelInfo
colormap[260];
/*
* Initialize image colormap.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Sort the new colormap");
/* Sort palette, transparent first */;
n = 0;
for (i=0; i<number_transparent; i++)
colormap[n++] = transparent[i];
for (i=0; i<number_semitransparent; i++)
colormap[n++] = semitransparent[i];
for (i=0; i<number_opaque; i++)
colormap[n++] = opaque[i];
ping_background.index +=
(number_transparent + number_semitransparent);
/* image_colors < 257; search the colormap instead of the pixels
* to get ping_have_color and ping_have_non_bw
*/
for (i=0; i<n; i++)
{
if (ping_have_color == MagickFalse)
{
if (colormap[i].red != colormap[i].green ||
colormap[i].red != colormap[i].blue)
{
ping_have_color=MagickTrue;
ping_have_non_bw=MagickTrue;
break;
}
}
if (ping_have_non_bw == MagickFalse)
{
if (colormap[i].red != 0 && colormap[i].red != QuantumRange)
ping_have_non_bw=MagickTrue;
}
}
if ((mng_info->ping_exclude_tRNS == MagickFalse ||
(number_transparent == 0 && number_semitransparent == 0)) &&
(((mng_info->write_png_colortype-1) ==
PNG_COLOR_TYPE_PALETTE) ||
(mng_info->write_png_colortype == 0)))
{
if (logging != MagickFalse)
{
if (n != (ssize_t) image_colors)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_colors (%d) and n (%d) don't match",
image_colors, n);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" AcquireImageColormap");
}
image->colors = image_colors;
if (AcquireImageColormap(image,image_colors,exception) ==
MagickFalse)
ThrowWriterException(ResourceLimitError,
"MemoryAllocationFailed");
for (i=0; i< (ssize_t) image_colors; i++)
image->colormap[i] = colormap[i];
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d (%d)",
(int) image->colors, image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Update the pixel indexes");
}
/* Sync the pixel indices with the new colormap */
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
for (i=0; i< (ssize_t) image_colors; i++)
{
if ((image->alpha_trait == UndefinedPixelTrait ||
image->colormap[i].alpha == GetPixelAlpha(image,q)) &&
image->colormap[i].red == GetPixelRed(image,q) &&
image->colormap[i].green == GetPixelGreen(image,q) &&
image->colormap[i].blue == GetPixelBlue(image,q))
{
SetPixelIndex(image,i,q);
break;
}
}
q+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->colors=%d", (int) image->colors);
if (image->colormap != NULL)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" i (red,green,blue,alpha)");
for (i=0; i < (ssize_t) image->colors; i++)
{
if (i < 300 || i >= (ssize_t) image->colors - 10)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" %d (%d,%d,%d,%d)",
(int) i,
(int) image->colormap[i].red,
(int) image->colormap[i].green,
(int) image->colormap[i].blue,
(int) image->colormap[i].alpha);
}
}
}
if (number_transparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent = %d",
number_transparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_transparent > 256");
if (number_opaque < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque = %d",
number_opaque);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_opaque > 256");
if (number_semitransparent < 257)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent = %d",
number_semitransparent);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" number_semitransparent > 256");
if (ping_have_non_bw == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are black or white");
else if (ping_have_color == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" All pixels and the background are gray");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" At least one pixel or the background is non-gray");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Exit BUILD_PALETTE:");
}
if (mng_info->write_png8 == MagickFalse)
break;
/* Make any reductions necessary for the PNG8 format */
if (image_colors <= 256 &&
image_colors != 0 && image->colormap != NULL &&
number_semitransparent == 0 &&
number_transparent <= 1)
break;
/* PNG8 can't have semitransparent colors so we threshold the
* opacity to 0 or OpaqueOpacity, and PNG8 can only have one
* transparent color so if more than one is transparent we merge
* them into image->background_color.
*/
if (number_semitransparent != 0 || number_transparent > 1)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Thresholding the alpha channel to binary");
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) < OpaqueAlpha/2)
{
SetPixelViaPixelInfo(image,&image->background_color,r);
SetPixelAlpha(image,TransparentAlpha,r);
}
else
SetPixelAlpha(image,OpaqueAlpha,r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
if (image_colors != 0 && image_colors <= 256 &&
image->colormap != NULL)
for (i=0; i<image_colors; i++)
image->colormap[i].alpha =
(image->colormap[i].alpha > TransparentAlpha/2 ?
TransparentAlpha : OpaqueAlpha);
}
continue;
}
/* PNG8 can't have more than 256 colors so we quantize the pixels and
* background color to the 4-4-4-1, 3-3-3-1 or 3-3-2-1 palette. If the
* image is mostly gray, the 4-4-4-1 palette is likely to end up with 256
* colors or less.
*/
if (tried_444 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 4-4-4");
tried_444 = MagickTrue;
LBR04PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 4-4-4");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR04PixelRGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 4-4-4");
for (i=0; i<image_colors; i++)
{
LBR04PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_333 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-3");
tried_333 = MagickTrue;
LBR03PacketRGB(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-3-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR03RGB(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-3-1");
for (i=0; i<image_colors; i++)
{
LBR03PacketRGB(image->colormap[i]);
}
}
continue;
}
if (tried_332 == MagickFalse && (image_colors == 0 || image_colors > 256))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the background color to 3-3-2");
tried_332 = MagickTrue;
/* Red and green were already done so we only quantize the blue
* channel
*/
LBR02PacketBlue(image->background_color);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,r) == OpaqueAlpha)
LBR02PixelBlue(r);
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else /* Should not reach this; colormap already exists and
must be <= 256 */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Quantizing the colormap to 3-3-2-1");
for (i=0; i<image_colors; i++)
{
LBR02PacketBlue(image->colormap[i]);
}
}
continue;
}
if (image_colors == 0 || image_colors > 256)
{
/* Take care of special case with 256 opaque colors + 1 transparent
* color. We don't need to quantize to 2-3-2-1; we only need to
* eliminate one color, so we'll merge the two darkest red
* colors (0x49, 0, 0) -> (0x24, 0, 0).
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red background colors to 3-3-2-1");
if (ScaleQuantumToChar(image->background_color.red) == 0x49 &&
ScaleQuantumToChar(image->background_color.green) == 0x00 &&
ScaleQuantumToChar(image->background_color.blue) == 0x00)
{
image->background_color.red=ScaleCharToQuantum(0x24);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Merging two dark red pixel colors to 3-3-2-1");
if (image->colormap == NULL)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
r=GetAuthenticPixels(image,0,y,image->columns,1,exception);
if (r == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (ScaleQuantumToChar(GetPixelRed(image,r)) == 0x49 &&
ScaleQuantumToChar(GetPixelGreen(image,r)) == 0x00 &&
ScaleQuantumToChar(GetPixelBlue(image,r)) == 0x00 &&
GetPixelAlpha(image,r) == OpaqueAlpha)
{
SetPixelRed(image,ScaleCharToQuantum(0x24),r);
}
r+=GetPixelChannels(image);
}
if (SyncAuthenticPixels(image,exception) == MagickFalse)
break;
}
}
else
{
for (i=0; i<image_colors; i++)
{
if (ScaleQuantumToChar(image->colormap[i].red) == 0x49 &&
ScaleQuantumToChar(image->colormap[i].green) == 0x00 &&
ScaleQuantumToChar(image->colormap[i].blue) == 0x00)
{
image->colormap[i].red=ScaleCharToQuantum(0x24);
}
}
}
}
}
}
/* END OF BUILD_PALETTE */
/* If we are excluding the tRNS chunk and there is transparency,
* then we must write a Gray-Alpha (color-type 4) or RGBA (color-type 6)
* PNG.
*/
if (mng_info->ping_exclude_tRNS != MagickFalse &&
(number_transparent != 0 || number_semitransparent != 0))
{
unsigned int colortype=mng_info->write_png_colortype;
if (ping_have_color == MagickFalse)
mng_info->write_png_colortype = 5;
else
mng_info->write_png_colortype = 7;
if (colortype != 0 &&
mng_info->write_png_colortype != colortype)
ping_need_colortype_warning=MagickTrue;
}
/* See if cheap transparency is possible. It is only possible
* when there is a single transparent color, no semitransparent
* color, and no opaque color that has the same RGB components
* as the transparent color. We only need this information if
* we are writing a PNG with colortype 0 or 2, and we have not
* excluded the tRNS chunk.
*/
if (number_transparent == 1 &&
mng_info->write_png_colortype < 4)
{
ping_have_cheap_transparency = MagickTrue;
if (number_semitransparent != 0)
ping_have_cheap_transparency = MagickFalse;
else if (image_colors == 0 || image_colors > 256 ||
image->colormap == NULL)
{
register const Quantum
*q;
for (y=0; y < (ssize_t) image->rows; y++)
{
q=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (q == (Quantum *) NULL)
break;
for (x=0; x < (ssize_t) image->columns; x++)
{
if (GetPixelAlpha(image,q) != TransparentAlpha &&
(unsigned short) GetPixelRed(image,q) ==
ping_trans_color.red &&
(unsigned short) GetPixelGreen(image,q) ==
ping_trans_color.green &&
(unsigned short) GetPixelBlue(image,q) ==
ping_trans_color.blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
q+=GetPixelChannels(image);
}
if (ping_have_cheap_transparency == MagickFalse)
break;
}
}
else
{
/* Assuming that image->colormap[0] is the one transparent color
* and that all others are opaque.
*/
if (image_colors > 1)
for (i=1; i<image_colors; i++)
if (image->colormap[i].red == image->colormap[0].red &&
image->colormap[i].green == image->colormap[0].green &&
image->colormap[i].blue == image->colormap[0].blue)
{
ping_have_cheap_transparency = MagickFalse;
break;
}
}
if (logging != MagickFalse)
{
if (ping_have_cheap_transparency == MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is not possible.");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Cheap transparency is possible.");
}
}
else
ping_have_cheap_transparency = MagickFalse;
image_depth=image->depth;
quantum_info = (QuantumInfo *) NULL;
number_colors=0;
image_colors=(int) image->colors;
image_matte=image->alpha_trait !=
UndefinedPixelTrait ? MagickTrue : MagickFalse;
if (mng_info->write_png_colortype < 5)
mng_info->IsPalette=image->storage_class == PseudoClass &&
image_colors <= 256 && image->colormap != NULL;
else
mng_info->IsPalette = MagickFalse;
if ((mng_info->write_png_colortype == 4 || mng_info->write_png8) &&
(image->colors == 0 || image->colormap == NULL))
{
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
(void) ThrowMagickException(exception,GetMagickModule(),CoderError,
"Cannot write PNG8 or color-type 3; colormap is NULL",
"`%s'",IMimage->filename);
return(MagickFalse);
}
/*
Allocate the PNG structures
*/
#ifdef PNG_USER_MEM_SUPPORTED
error_info.image=image;
error_info.exception=exception;
ping=png_create_write_struct_2(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler,(void *) NULL,
(png_malloc_ptr) Magick_png_malloc,(png_free_ptr) Magick_png_free);
#else
ping=png_create_write_struct(PNG_LIBPNG_VER_STRING,&error_info,
MagickPNGErrorHandler,MagickPNGWarningHandler);
#endif
if (ping == (png_struct *) NULL)
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
ping_info=png_create_info_struct(ping);
if (ping_info == (png_info *) NULL)
{
png_destroy_write_struct(&ping,(png_info **) NULL);
ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed");
}
png_set_write_fn(ping,image,png_put_data,png_flush_data);
pixel_info=(MemoryInfo *) NULL;
if (setjmp(png_jmpbuf(ping)))
{
/*
PNG write failed.
*/
#ifdef PNG_DEBUG
if (image_info->verbose)
(void) printf("PNG write has failed.\n");
#endif
png_destroy_write_struct(&ping,&ping_info);
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
if (pixel_info != (MemoryInfo *) NULL)
pixel_info=RelinquishVirtualMemory(pixel_info);
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
return(MagickFalse);
}
/* { For navigation to end of SETJMP-protected block. Within this
* block, use png_error() instead of Throwing an Exception, to ensure
* that libpng is able to clean up, and that the semaphore is unlocked.
*/
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
LockSemaphoreInfo(ping_semaphore);
#endif
#ifdef PNG_BENIGN_ERRORS_SUPPORTED
/* Allow benign errors */
png_set_benign_errors(ping, 1);
#endif
#ifdef PNG_SET_USER_LIMITS_SUPPORTED
/* Reject images with too many rows or columns */
png_set_user_limits(ping,
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(WidthResource)),
(png_uint_32) MagickMin(0x7fffffffL,
GetMagickResourceLimit(HeightResource)));
#endif /* PNG_SET_USER_LIMITS_SUPPORTED */
/*
Prepare PNG for writing.
*/
#if defined(PNG_MNG_FEATURES_SUPPORTED)
if (mng_info->write_mng)
{
(void) png_permit_mng_features(ping,PNG_ALL_MNG_FEATURES);
# ifdef PNG_WRITE_CHECK_FOR_INVALID_INDEX_SUPPORTED
/* Disable new libpng-1.5.10 feature when writing a MNG because
* zero-length PLTE is OK
*/
png_set_check_for_invalid_index (ping, 0);
# endif
}
#else
# ifdef PNG_WRITE_EMPTY_PLTE_SUPPORTED
if (mng_info->write_mng)
png_permit_empty_plte(ping,MagickTrue);
# endif
#endif
x=0;
ping_width=(png_uint_32) image->columns;
ping_height=(png_uint_32) image->rows;
if (mng_info->write_png8 || mng_info->write_png24 || mng_info->write_png32)
image_depth=8;
if (mng_info->write_png48 || mng_info->write_png64)
image_depth=16;
if (mng_info->write_png_depth != 0)
image_depth=mng_info->write_png_depth;
/* Adjust requested depth to next higher valid depth if necessary */
if (image_depth > 8)
image_depth=16;
if ((image_depth > 4) && (image_depth < 8))
image_depth=8;
if (image_depth == 3)
image_depth=4;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" width=%.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" height=%.20g",(double) ping_height);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_matte=%.20g",(double) image->alpha_trait);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth=%.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative ping_bit_depth=%.20g",(double) image_depth);
}
save_image_depth=image_depth;
ping_bit_depth=(png_byte) save_image_depth;
#if defined(PNG_pHYs_SUPPORTED)
if (ping_exclude_pHYs == MagickFalse)
{
if ((image->resolution.x != 0) && (image->resolution.y != 0) &&
(!mng_info->write_mng || !mng_info->equal_physs))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
if (image->units == PixelsPerInchResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=
(png_uint_32) ((100.0*image->resolution.x+0.5)/2.54);
ping_pHYs_y_resolution=
(png_uint_32) ((100.0*image->resolution.y+0.5)/2.54);
}
else if (image->units == PixelsPerCentimeterResolution)
{
ping_pHYs_unit_type=PNG_RESOLUTION_METER;
ping_pHYs_x_resolution=(png_uint_32) (100.0*image->resolution.x+0.5);
ping_pHYs_y_resolution=(png_uint_32) (100.0*image->resolution.y+0.5);
}
else
{
ping_pHYs_unit_type=PNG_RESOLUTION_UNKNOWN;
ping_pHYs_x_resolution=(png_uint_32) image->resolution.x;
ping_pHYs_y_resolution=(png_uint_32) image->resolution.y;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Set up PNG pHYs chunk: xres: %.20g, yres: %.20g, units: %d.",
(double) ping_pHYs_x_resolution,(double) ping_pHYs_y_resolution,
(int) ping_pHYs_unit_type);
ping_have_pHYs = MagickTrue;
}
}
#endif
if (ping_exclude_bKGD == MagickFalse)
{
if ((!mng_info->adjoin || !mng_info->equal_backgrounds))
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_background.red=(png_uint_16)
(ScaleQuantumToShort(image->background_color.red) & mask);
ping_background.green=(png_uint_16)
(ScaleQuantumToShort(image->background_color.green) & mask);
ping_background.blue=(png_uint_16)
(ScaleQuantumToShort(image->background_color.blue) & mask);
ping_background.gray=(png_uint_16) ping_background.green;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (1)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth=%d",ping_bit_depth);
}
ping_have_bKGD = MagickTrue;
}
/*
Select the color type.
*/
matte=image_matte;
old_bit_depth=0;
if (mng_info->IsPalette && mng_info->write_png8)
{
/* To do: make this a function cause it's used twice, except
for reducing the sample depth from 8. */
number_colors=image_colors;
ping_have_tRNS=MagickFalse;
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors (%d)",
number_colors, image_colors);
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
#if MAGICKCORE_QUANTUM_DEPTH == 8
" %3ld (%3d,%3d,%3d)",
#else
" %5ld (%5d,%5d,%5d)",
#endif
(long) i,palette[i].red,palette[i].green,palette[i].blue);
}
ping_have_PLTE=MagickTrue;
image_depth=ping_bit_depth;
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
Identify which colormap entry is transparent.
*/
assert(number_colors <= 256);
assert(image->colormap != NULL);
for (i=0; i < (ssize_t) number_transparent; i++)
ping_trans_alpha[i]=0;
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
ping_have_tRNS=MagickTrue;
}
if (ping_exclude_bKGD == MagickFalse)
{
/*
* Identify which colormap entry is the background color.
*/
for (i=0; i < (ssize_t) MagickMax(1L*number_colors-1L,1L); i++)
if (IsPNGColorEqual(ping_background,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
}
}
} /* end of write_png8 */
else if (mng_info->write_png_colortype == 1)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
}
else if (mng_info->write_png24 || mng_info->write_png48 ||
mng_info->write_png_colortype == 3)
{
image_matte=MagickFalse;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
}
else if (mng_info->write_png32 || mng_info->write_png64 ||
mng_info->write_png_colortype == 7)
{
image_matte=MagickTrue;
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
}
else /* mng_info->write_pngNN not specified */
{
image_depth=ping_bit_depth;
if (mng_info->write_png_colortype != 0)
{
ping_color_type=(png_byte) mng_info->write_png_colortype-1;
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
image_matte=MagickTrue;
else
image_matte=MagickFalse;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG colortype %d was specified:",(int) ping_color_type);
}
else /* write_png_colortype not specified */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selecting PNG colortype:");
ping_color_type=(png_byte) ((matte != MagickFalse)?
PNG_COLOR_TYPE_RGB_ALPHA:PNG_COLOR_TYPE_RGB);
if (image_info->type == TrueColorType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
if (image_info->type == TrueColorAlphaType)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB_ALPHA;
image_matte=MagickTrue;
}
if (image_info->type == PaletteType ||
image_info->type == PaletteAlphaType)
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (mng_info->write_png_colortype == 0 &&
image_info->type == UndefinedType)
{
if (ping_have_color == MagickFalse)
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_GRAY_ALPHA;
image_matte=MagickTrue;
}
}
else
{
if (image_matte == MagickFalse)
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGB;
image_matte=MagickFalse;
}
else
{
ping_color_type=(png_byte) PNG_COLOR_TYPE_RGBA;
image_matte=MagickTrue;
}
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Selected PNG colortype=%d",ping_color_type);
if (ping_bit_depth < 8)
{
if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
ping_color_type == PNG_COLOR_TYPE_RGB ||
ping_color_type == PNG_COLOR_TYPE_RGB_ALPHA)
ping_bit_depth=8;
}
old_bit_depth=ping_bit_depth;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->alpha_trait == UndefinedPixelTrait &&
ping_have_non_bw == MagickFalse)
ping_bit_depth=1;
}
if (ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
size_t one = 1;
ping_bit_depth=1;
if (image->colors == 0)
{
/* DO SOMETHING */
png_error(ping,"image has 0 colors");
}
while ((int) (one << ping_bit_depth) < (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Number of colors: %.20g",(double) image_colors);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG bit depth: %d",ping_bit_depth);
}
if (ping_bit_depth < (int) mng_info->write_png_depth)
ping_bit_depth = mng_info->write_png_depth;
}
image_depth=ping_bit_depth;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Tentative PNG color type: %s (%.20g)",
PngColorTypeToString(ping_color_type),
(double) ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_info->type: %.20g",(double) image_info->type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image_depth: %.20g",(double) image_depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" image->depth: %.20g",(double) image->depth);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_bit_depth: %.20g",(double) ping_bit_depth);
}
if (matte != MagickFalse)
{
if (mng_info->IsPalette)
{
if (mng_info->write_png_colortype == 0)
{
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
if (ping_have_color != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_RGBA;
}
/*
* Determine if there is any transparent color.
*/
if (number_transparent + number_semitransparent == 0)
{
/*
No transparent pixels are present. Change 4 or 6 to 0 or 2.
*/
image_matte=MagickFalse;
if (mng_info->write_png_colortype == 0)
ping_color_type&=0x03;
}
else
{
unsigned int
mask;
mask=0xffff;
if (ping_bit_depth == 8)
mask=0x00ff;
if (ping_bit_depth == 4)
mask=0x000f;
if (ping_bit_depth == 2)
mask=0x0003;
if (ping_bit_depth == 1)
mask=0x0001;
ping_trans_color.red=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].red) & mask);
ping_trans_color.green=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].green) & mask);
ping_trans_color.blue=(png_uint_16)
(ScaleQuantumToShort(image->colormap[0].blue) & mask);
ping_trans_color.gray=(png_uint_16)
(ScaleQuantumToShort(GetPixelInfoIntensity(image,
image->colormap)) & mask);
ping_trans_color.index=(png_byte) 0;
ping_have_tRNS=MagickTrue;
}
if (ping_have_tRNS != MagickFalse)
{
/*
* Determine if there is one and only one transparent color
* and if so if it is fully transparent.
*/
if (ping_have_cheap_transparency == MagickFalse)
ping_have_tRNS=MagickFalse;
}
if (ping_have_tRNS != MagickFalse)
{
if (mng_info->write_png_colortype == 0)
ping_color_type &= 0x03; /* changes 4 or 6 to 0 or 2 */
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
else
{
if (image_depth == 8)
{
ping_trans_color.red&=0xff;
ping_trans_color.green&=0xff;
ping_trans_color.blue&=0xff;
ping_trans_color.gray&=0xff;
}
}
}
matte=image_matte;
if (ping_have_tRNS != MagickFalse)
image_matte=MagickFalse;
if ((mng_info->IsPalette) &&
mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE &&
ping_have_color == MagickFalse &&
(image_matte == MagickFalse || image_depth >= 8))
{
size_t one=1;
if (image_matte != MagickFalse)
ping_color_type=PNG_COLOR_TYPE_GRAY_ALPHA;
else if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_GRAY_ALPHA)
{
ping_color_type=PNG_COLOR_TYPE_GRAY;
if (save_image_depth == 16 && image_depth == 8)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (0)");
}
ping_trans_color.gray*=0x0101;
}
}
if (image_depth > MAGICKCORE_QUANTUM_DEPTH)
image_depth=MAGICKCORE_QUANTUM_DEPTH;
if ((image_colors == 0) ||
((ssize_t) (image_colors-1) > (ssize_t) MaxColormapSize))
image_colors=(int) (one << image_depth);
if (image_depth > 8)
ping_bit_depth=16;
else
{
ping_bit_depth=8;
if ((int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
if(!mng_info->write_png_depth)
{
ping_bit_depth=1;
while ((int) (one << ping_bit_depth)
< (ssize_t) image_colors)
ping_bit_depth <<= 1;
}
}
else if (ping_color_type ==
PNG_COLOR_TYPE_GRAY && image_colors < 17 &&
mng_info->IsPalette)
{
/* Check if grayscale is reducible */
int
depth_4_ok=MagickTrue,
depth_2_ok=MagickTrue,
depth_1_ok=MagickTrue;
for (i=0; i < (ssize_t) image_colors; i++)
{
unsigned char
intensity;
intensity=ScaleQuantumToChar(image->colormap[i].red);
if ((intensity & 0x0f) != ((intensity & 0xf0) >> 4))
depth_4_ok=depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x03) != ((intensity & 0x0c) >> 2))
depth_2_ok=depth_1_ok=MagickFalse;
else if ((intensity & 0x01) != ((intensity & 0x02) >> 1))
depth_1_ok=MagickFalse;
}
if (depth_1_ok && mng_info->write_png_depth <= 1)
ping_bit_depth=1;
else if (depth_2_ok && mng_info->write_png_depth <= 2)
ping_bit_depth=2;
else if (depth_4_ok && mng_info->write_png_depth <= 4)
ping_bit_depth=4;
}
}
image_depth=ping_bit_depth;
}
else
if (mng_info->IsPalette)
{
number_colors=image_colors;
if (image_depth <= 8)
{
/*
Set image palette.
*/
ping_color_type=(png_byte) PNG_COLOR_TYPE_PALETTE;
if (!(mng_info->have_write_global_plte && matte == MagickFalse))
{
for (i=0; i < (ssize_t) number_colors; i++)
{
palette[i].red=ScaleQuantumToChar(image->colormap[i].red);
palette[i].green=
ScaleQuantumToChar(image->colormap[i].green);
palette[i].blue=ScaleQuantumToChar(image->colormap[i].blue);
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up PLTE chunk with %d colors",
number_colors);
ping_have_PLTE=MagickTrue;
}
/* color_type is PNG_COLOR_TYPE_PALETTE */
if (mng_info->write_png_depth == 0)
{
size_t
one;
ping_bit_depth=1;
one=1;
while ((one << ping_bit_depth) < (size_t) number_colors)
ping_bit_depth <<= 1;
}
ping_num_trans=0;
if (matte != MagickFalse)
{
/*
* Set up trans_colors array.
*/
assert(number_colors <= 256);
ping_num_trans=(unsigned short) (number_transparent +
number_semitransparent);
if (ping_num_trans == 0)
ping_have_tRNS=MagickFalse;
else
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color (1)");
}
ping_have_tRNS=MagickTrue;
for (i=0; i < ping_num_trans; i++)
{
ping_trans_alpha[i]= (png_byte)
ScaleQuantumToChar(image->colormap[i].alpha);
}
}
}
}
}
else
{
if (image_depth < 8)
image_depth=8;
if ((save_image_depth == 16) && (image_depth == 8))
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color from (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
ping_trans_color.red*=0x0101;
ping_trans_color.green*=0x0101;
ping_trans_color.blue*=0x0101;
ping_trans_color.gray*=0x0101;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to (%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
if (ping_bit_depth < (ssize_t) mng_info->write_png_depth)
ping_bit_depth = (ssize_t) mng_info->write_png_depth;
/*
Adjust background and transparency samples in sub-8-bit grayscale files.
*/
if (ping_bit_depth < 8 && ping_color_type ==
PNG_COLOR_TYPE_GRAY)
{
png_uint_16
maxval;
size_t
one=1;
maxval=(png_uint_16) ((one << ping_bit_depth)-1);
if (ping_exclude_bKGD == MagickFalse)
{
ping_background.gray=(png_uint_16) ((maxval/65535.)*
(ScaleQuantumToShort(((GetPixelInfoIntensity(image,
&image->background_color))) +.5)));
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk (2)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background_color index is %d",
(int) ping_background.index);
ping_have_bKGD = MagickTrue;
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Scaling ping_trans_color.gray from %d",
(int)ping_trans_color.gray);
ping_trans_color.gray=(png_uint_16) ((maxval/255.)*(
ping_trans_color.gray)+.5);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" to %d", (int)ping_trans_color.gray);
}
if (ping_exclude_bKGD == MagickFalse)
{
if (mng_info->IsPalette && (int) ping_color_type == PNG_COLOR_TYPE_PALETTE)
{
/*
Identify which colormap entry is the background color.
*/
number_colors=image_colors;
for (i=0; i < (ssize_t) MagickMax(1L*number_colors,1L); i++)
if (IsPNGColorEqual(image->background_color,image->colormap[i]))
break;
ping_background.index=(png_byte) i;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk with index=%d",(int) i);
}
if (i < (ssize_t) number_colors)
{
ping_have_bKGD = MagickTrue;
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background =(%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
}
}
else /* Can't happen */
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" No room in PLTE to add bKGD color");
ping_have_bKGD = MagickFalse;
}
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color type: %s (%d)", PngColorTypeToString(ping_color_type),
ping_color_type);
/*
Initialize compression level and filtering.
*/
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up deflate compression");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression buffer size: 32768");
}
png_set_compression_buffer_size(ping,32768L);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression mem level: 9");
png_set_compression_mem_level(ping, 9);
/* Untangle the "-quality" setting:
Undefined is 0; the default is used.
Default is 75
10's digit:
0 or omitted: Use Z_HUFFMAN_ONLY strategy with the
zlib default compression level
1-9: the zlib compression level
1's digit:
0-4: the PNG filter method
5: libpng adaptive filtering if compression level > 5
libpng filter type "none" if compression level <= 5
or if image is grayscale or palette
6: libpng adaptive filtering
7: "LOCO" filtering (intrapixel differing) if writing
a MNG, otherwise "none". Did not work in IM-6.7.0-9
and earlier because of a missing "else".
8: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), adaptive
filtering. Unused prior to IM-6.7.0-10, was same as 6
9: Z_RLE strategy (or Z_HUFFMAN_ONLY if quality < 10), no PNG filters
Unused prior to IM-6.7.0-10, was same as 6
Note that using the -quality option, not all combinations of
PNG filter type, zlib compression level, and zlib compression
strategy are possible. This will be addressed soon in a
release that accomodates "-define png:compression-strategy", etc.
*/
quality=image_info->quality == UndefinedCompressionQuality ? 75UL :
image_info->quality;
if (quality <= 9)
{
if (mng_info->write_png_compression_strategy == 0)
mng_info->write_png_compression_strategy = Z_HUFFMAN_ONLY+1;
}
else if (mng_info->write_png_compression_level == 0)
{
int
level;
level=(int) MagickMin((ssize_t) quality/10,9);
mng_info->write_png_compression_level = level+1;
}
if (mng_info->write_png_compression_strategy == 0)
{
if ((quality %10) == 8 || (quality %10) == 9)
#ifdef Z_RLE /* Z_RLE was added to zlib-1.2.0 */
mng_info->write_png_compression_strategy=Z_RLE+1;
#else
mng_info->write_png_compression_strategy = Z_DEFAULT_STRATEGY+1;
#endif
}
if (mng_info->write_png_compression_filter == 0)
mng_info->write_png_compression_filter=((int) quality % 10) + 1;
if (logging != MagickFalse)
{
if (mng_info->write_png_compression_level)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression level: %d",
(int) mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_strategy)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Compression strategy: %d",
(int) mng_info->write_png_compression_strategy-1);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up filtering");
if (mng_info->write_png_compression_filter == 6)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: ADAPTIVE");
else if (mng_info->write_png_compression_filter == 0 ||
mng_info->write_png_compression_filter == 1)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: NONE");
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Base filter method: %d",
(int) mng_info->write_png_compression_filter-1);
}
if (mng_info->write_png_compression_level != 0)
png_set_compression_level(ping,mng_info->write_png_compression_level-1);
if (mng_info->write_png_compression_filter == 6)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_GRAY) ||
((int) ping_color_type == PNG_COLOR_TYPE_PALETTE) ||
(quality < 50))
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
}
else if (mng_info->write_png_compression_filter == 7 ||
mng_info->write_png_compression_filter == 10)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_ALL_FILTERS);
else if (mng_info->write_png_compression_filter == 8)
{
#if defined(PNG_MNG_FEATURES_SUPPORTED) && defined(PNG_INTRAPIXEL_DIFFERENCING)
if (mng_info->write_mng)
{
if (((int) ping_color_type == PNG_COLOR_TYPE_RGB) ||
((int) ping_color_type == PNG_COLOR_TYPE_RGBA))
ping_filter_method=PNG_INTRAPIXEL_DIFFERENCING;
}
#endif
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
}
else if (mng_info->write_png_compression_filter == 9)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,PNG_NO_FILTERS);
else if (mng_info->write_png_compression_filter != 0)
png_set_filter(ping,PNG_FILTER_TYPE_BASE,
mng_info->write_png_compression_filter-1);
if (mng_info->write_png_compression_strategy != 0)
png_set_compression_strategy(ping,
mng_info->write_png_compression_strategy-1);
ping_interlace_method=image_info->interlace != NoInterlace;
if (mng_info->write_mng)
png_set_sig_bytes(ping,8);
/* Bail out if cannot meet defined png:bit-depth or png:color-type */
if (mng_info->write_png_colortype != 0)
{
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY)
if (ping_have_color != MagickFalse)
{
ping_color_type = PNG_COLOR_TYPE_RGB;
if (ping_bit_depth < 8)
ping_bit_depth=8;
}
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_GRAY_ALPHA)
if (ping_have_color != MagickFalse)
ping_color_type = PNG_COLOR_TYPE_RGB_ALPHA;
}
if (ping_need_colortype_warning != MagickFalse ||
((mng_info->write_png_depth &&
(int) mng_info->write_png_depth != ping_bit_depth) ||
(mng_info->write_png_colortype &&
((int) mng_info->write_png_colortype-1 != ping_color_type &&
mng_info->write_png_colortype != 7 &&
!(mng_info->write_png_colortype == 5 && ping_color_type == 0)))))
{
if (logging != MagickFalse)
{
if (ping_need_colortype_warning != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Image has transparency but tRNS chunk was excluded");
}
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth=%u, Computed depth=%u",
mng_info->write_png_depth,
ping_bit_depth);
}
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type=%u, Computed color type=%u",
mng_info->write_png_colortype-1,
ping_color_type);
}
}
png_warning(ping,
"Cannot write image with defined png:bit-depth or png:color-type.");
}
if (image_matte != MagickFalse && image->alpha_trait == UndefinedPixelTrait)
{
/* Add an opaque matte channel */
image->alpha_trait = BlendPixelTrait;
(void) SetImageAlpha(image,OpaqueAlpha,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Added an opaque matte channel");
}
if (number_transparent != 0 || number_semitransparent != 0)
{
if (ping_color_type < 4)
{
ping_have_tRNS=MagickTrue;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting ping_have_tRNS=MagickTrue.");
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG header chunks");
png_set_IHDR(ping,ping_info,ping_width,ping_height,
ping_bit_depth,ping_color_type,
ping_interlace_method,ping_compression_method,
ping_filter_method);
if (ping_color_type == 3 && ping_have_PLTE != MagickFalse)
{
png_set_PLTE(ping,ping_info,palette,number_colors);
if (logging != MagickFalse)
{
for (i=0; i< (ssize_t) number_colors; i++)
{
if (i < ping_num_trans)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d), tRNS[%d] = (%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue,
(int) i,
(int) ping_trans_alpha[i]);
else
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PLTE[%d] = (%d,%d,%d)",
(int) i,
(int) palette[i].red,
(int) palette[i].green,
(int) palette[i].blue);
}
}
}
/* Only write the iCCP chunk if we are not writing the sRGB chunk. */
if (ping_exclude_sRGB != MagickFalse ||
(!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if ((ping_exclude_tEXt == MagickFalse ||
ping_exclude_zTXt == MagickFalse) &&
(ping_exclude_iCCP == MagickFalse || ping_exclude_zCCP == MagickFalse))
{
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
#ifdef PNG_WRITE_iCCP_SUPPORTED
if ((LocaleCompare(name,"ICC") == 0) ||
(LocaleCompare(name,"ICM") == 0))
{
ping_have_iCCP = MagickTrue;
if (ping_exclude_iCCP == MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up iCCP chunk");
png_set_iCCP(ping,ping_info,(png_charp) name,0,
#if (PNG_LIBPNG_VER < 10500)
(png_charp) GetStringInfoDatum(profile),
#else
(const png_byte *) GetStringInfoDatum(profile),
#endif
(png_uint_32) GetStringInfoLength(profile));
}
else
{
/* Do not write hex-encoded ICC chunk */
name=GetNextImageProfile(image);
continue;
}
}
#endif /* WRITE_iCCP */
if (LocaleCompare(name,"exif") == 0)
{
/* Do not write hex-encoded ICC chunk; we will
write it later as an eXIf chunk */
name=GetNextImageProfile(image);
continue;
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up zTXt chunk with uuencoded %s profile",
name);
Magick_png_write_raw_profile(image_info,ping,ping_info,
(unsigned char *) name,(unsigned char *) name,
GetStringInfoDatum(profile),
(png_uint_32) GetStringInfoLength(profile));
}
name=GetNextImageProfile(image);
}
}
}
#if defined(PNG_WRITE_sRGB_SUPPORTED)
if ((mng_info->have_write_global_srgb == 0) &&
ping_have_iCCP != MagickTrue &&
(ping_have_sRGB != MagickFalse ||
png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
{
if (ping_exclude_sRGB == MagickFalse)
{
/*
Note image rendering intent.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up sRGB chunk");
(void) png_set_sRGB(ping,ping_info,(
Magick_RenderingIntent_to_PNG_RenderingIntent(
image->rendering_intent)));
ping_have_sRGB = MagickTrue;
}
}
if ((!mng_info->write_mng) || (!png_get_valid(ping,ping_info,PNG_INFO_sRGB)))
#endif
{
if (ping_exclude_gAMA == MagickFalse &&
ping_have_iCCP == MagickFalse &&
ping_have_sRGB == MagickFalse &&
(ping_exclude_sRGB == MagickFalse ||
(image->gamma < .45 || image->gamma > .46)))
{
if ((mng_info->have_write_global_gama == 0) && (image->gamma != 0.0))
{
/*
Note image gamma.
To do: check for cHRM+gAMA == sRGB, and write sRGB instead.
*/
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up gAMA chunk");
png_set_gAMA(ping,ping_info,image->gamma);
}
}
if (ping_exclude_cHRM == MagickFalse && ping_have_sRGB == MagickFalse)
{
if ((mng_info->have_write_global_chrm == 0) &&
(image->chromaticity.red_primary.x != 0.0))
{
/*
Note image chromaticity.
Note: if cHRM+gAMA == sRGB write sRGB instead.
*/
PrimaryInfo
bp,
gp,
rp,
wp;
wp=image->chromaticity.white_point;
rp=image->chromaticity.red_primary;
gp=image->chromaticity.green_primary;
bp=image->chromaticity.blue_primary;
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up cHRM chunk");
png_set_cHRM(ping,ping_info,wp.x,wp.y,rp.x,rp.y,gp.x,gp.y,
bp.x,bp.y);
}
}
}
if (ping_exclude_bKGD == MagickFalse)
{
if (ping_have_bKGD != MagickFalse)
{
png_set_bKGD(ping,ping_info,&ping_background);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up bKGD chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" background color = (%d,%d,%d)",
(int) ping_background.red,
(int) ping_background.green,
(int) ping_background.blue);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" index = %d, gray=%d",
(int) ping_background.index,
(int) ping_background.gray);
}
}
}
if (ping_exclude_pHYs == MagickFalse)
{
if (ping_have_pHYs != MagickFalse)
{
png_set_pHYs(ping,ping_info,
ping_pHYs_x_resolution,
ping_pHYs_y_resolution,
ping_pHYs_unit_type);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up pHYs chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" x_resolution=%lu",
(unsigned long) ping_pHYs_x_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" y_resolution=%lu",
(unsigned long) ping_pHYs_y_resolution);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" unit_type=%lu",
(unsigned long) ping_pHYs_unit_type);
}
}
}
#if defined(PNG_tIME_SUPPORTED)
if (ping_exclude_tIME == MagickFalse)
{
const char
*timestamp;
if (image->taint == MagickFalse)
{
timestamp=GetImageOption(image_info,"png:tIME");
if (timestamp == (const char *) NULL)
timestamp=GetImageProperty(image,"png:tIME",exception);
}
else
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Reset tIME in tainted image");
timestamp=GetImageProperty(image,"date:modify",exception);
}
if (timestamp != (const char *) NULL)
write_tIME_chunk(image,ping,ping_info,timestamp,exception);
}
#endif
if (mng_info->need_blob != MagickFalse)
{
if (OpenBlob(image_info,image,WriteBinaryBlobMode,exception) ==
MagickFalse)
png_error(ping,"WriteBlob Failed");
ping_have_blob=MagickTrue;
}
png_write_info_before_PLTE(ping, ping_info);
if (ping_have_tRNS != MagickFalse && ping_color_type < 4)
{
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Calling png_set_tRNS with num_trans=%d",ping_num_trans);
}
if (ping_color_type == 3)
(void) png_set_tRNS(ping, ping_info,
ping_trans_alpha,
ping_num_trans,
NULL);
else
{
(void) png_set_tRNS(ping, ping_info,
NULL,
0,
&ping_trans_color);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" tRNS color =(%d,%d,%d)",
(int) ping_trans_color.red,
(int) ping_trans_color.green,
(int) ping_trans_color.blue);
}
}
}
/* write any png-chunk-b profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-b",logging);
png_write_info(ping,ping_info);
/* write any PNG-chunk-m profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-m",logging);
ping_wrote_caNv = MagickFalse;
/* write caNv chunk */
if (ping_exclude_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows) ||
image->page.x != 0 || image->page.y != 0)
{
unsigned char
chunk[20];
(void) WriteBlobMSBULong(image,16L); /* data length=8 */
PNGType(chunk,mng_caNv);
LogPNGChunk(logging,mng_caNv,16L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
PNGsLong(chunk+12,(png_int_32) image->page.x);
PNGsLong(chunk+16,(png_int_32) image->page.y);
(void) WriteBlob(image,20,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,20));
ping_wrote_caNv = MagickTrue;
}
}
#if defined(PNG_oFFs_SUPPORTED)
if (ping_exclude_oFFs == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if (image->page.x || image->page.y)
{
png_set_oFFs(ping,ping_info,(png_int_32) image->page.x,
(png_int_32) image->page.y, 0);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up oFFs chunk with x=%d, y=%d, units=0",
(int) image->page.x, (int) image->page.y);
}
}
#endif
/* write vpAg chunk (deprecated, replaced by caNv) */
if (ping_exclude_vpAg == MagickFalse && ping_wrote_caNv == MagickFalse)
{
if ((image->page.width != 0 && image->page.width != image->columns) ||
(image->page.height != 0 && image->page.height != image->rows))
{
unsigned char
chunk[14];
(void) WriteBlobMSBULong(image,9L); /* data length=8 */
PNGType(chunk,mng_vpAg);
LogPNGChunk(logging,mng_vpAg,9L);
PNGLong(chunk+4,(png_uint_32) image->page.width);
PNGLong(chunk+8,(png_uint_32) image->page.height);
chunk[12]=0; /* unit = pixels */
(void) WriteBlob(image,13,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,13));
}
}
#if (PNG_LIBPNG_VER == 10206)
/* avoid libpng-1.2.6 bug by setting PNG_HAVE_IDAT flag */
#define PNG_HAVE_IDAT 0x04
ping->mode |= PNG_HAVE_IDAT;
#undef PNG_HAVE_IDAT
#endif
png_set_packing(ping);
/*
Allocate memory.
*/
rowbytes=image->columns;
if (image_depth > 8)
rowbytes*=2;
switch (ping_color_type)
{
case PNG_COLOR_TYPE_RGB:
rowbytes*=3;
break;
case PNG_COLOR_TYPE_GRAY_ALPHA:
rowbytes*=2;
break;
case PNG_COLOR_TYPE_RGBA:
rowbytes*=4;
break;
default:
break;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Allocating %.20g bytes of memory for pixels",(double) rowbytes);
}
pixel_info=AcquireVirtualMemory(rowbytes,sizeof(*ping_pixels));
if (pixel_info == (MemoryInfo *) NULL)
png_error(ping,"Allocation of memory for pixels failed");
ping_pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info);
/*
Initialize image scanlines.
*/
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
png_error(ping,"Memory allocation for quantum_info failed");
quantum_info->format=UndefinedQuantumFormat;
SetQuantumDepth(image,quantum_info,image_depth);
(void) SetQuantumEndian(image,quantum_info,MSBEndian);
num_passes=png_set_interlace_handling(ping);
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) &&
(mng_info->IsPalette ||
(image_info->type == BilevelType)) &&
image_matte == MagickFalse &&
ping_have_non_bw == MagickFalse)
{
/* Palette, Bilevel, or Opaque Monochrome */
register const Quantum
*p;
SetQuantumDepth(image,quantum_info,8);
for (pass=0; pass < num_passes; pass++)
{
/*
Convert PseudoClass image to a PNG monochrome image.
*/
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (0)");
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (mng_info->IsPalette)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
if (mng_info->write_png_colortype-1 == PNG_COLOR_TYPE_PALETTE &&
mng_info->write_png_depth &&
mng_info->write_png_depth != old_bit_depth)
{
/* Undo pixel scaling */
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) (*(ping_pixels+i)
>> (8-old_bit_depth));
}
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
}
if (mng_info->write_png_colortype-1 != PNG_COLOR_TYPE_PALETTE)
for (i=0; i < (ssize_t) image->columns; i++)
*(ping_pixels+i)=(unsigned char) ((*(ping_pixels+i) > 127) ?
255 : 0);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (1)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else /* Not Palette, Bilevel, or Opaque Monochrome */
{
if ((!mng_info->write_png8 && !mng_info->write_png24 &&
!mng_info->write_png48 && !mng_info->write_png64 &&
!mng_info->write_png32) && (image_matte != MagickFalse ||
(ping_bit_depth >= MAGICKCORE_QUANTUM_DEPTH)) &&
(mng_info->IsPalette) && ping_have_color == MagickFalse)
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (mng_info->IsPalette)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY PNG pixels (2)");
}
else /* PNG_COLOR_TYPE_GRAY_ALPHA */
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (2)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,exception);
}
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (2)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
else
{
register const Quantum
*p;
for (pass=0; pass < num_passes; pass++)
{
if ((image_depth > 8) ||
mng_info->write_png24 ||
mng_info->write_png32 ||
mng_info->write_png48 ||
mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
{
for (y=0; y < (ssize_t) image->rows; y++)
{
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
if (image->storage_class == DirectClass)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RedQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (3)");
}
else if (image_matte != MagickFalse)
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBAQuantum,ping_pixels,exception);
else
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,RGBQuantum,ping_pixels,exception);
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of pixels (3)");
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
else
/* not ((image_depth > 8) ||
mng_info->write_png24 || mng_info->write_png32 ||
mng_info->write_png48 || mng_info->write_png64 ||
(!mng_info->write_png8 && !mng_info->IsPalette))
*/
{
if ((ping_color_type != PNG_COLOR_TYPE_GRAY) &&
(ping_color_type != PNG_COLOR_TYPE_GRAY_ALPHA))
{
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is not GRAY or GRAY_ALPHA",pass);
SetQuantumDepth(image,quantum_info,8);
image_depth=8;
}
for (y=0; y < (ssize_t) image->rows; y++)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" pass %d, Image Is RGB, 16-bit GRAY, or GRAY_ALPHA",
pass);
p=GetVirtualPixels(image,0,y,image->columns,1, exception);
if (p == (const Quantum *) NULL)
break;
if (ping_color_type == PNG_COLOR_TYPE_GRAY)
{
SetQuantumDepth(image,quantum_info,image->depth);
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayQuantum,ping_pixels,exception);
}
else if (ping_color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
{
if (logging != MagickFalse && y == 0)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing GRAY_ALPHA PNG pixels (4)");
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,GrayAlphaQuantum,ping_pixels,
exception);
}
else
{
(void) ExportQuantumPixels(image,(CacheView *) NULL,
quantum_info,IndexQuantum,ping_pixels,exception);
if (logging != MagickFalse && y <= 2)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing row of non-gray pixels (4)");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" ping_pixels[0]=%d,ping_pixels[1]=%d",
(int)ping_pixels[0],(int)ping_pixels[1]);
}
}
png_write_row(ping,ping_pixels);
status=SetImageProgress(image,SaveImageTag,
(MagickOffsetType) (pass * image->rows + y),
num_passes * image->rows);
if (status == MagickFalse)
break;
}
}
}
}
}
if (quantum_info != (QuantumInfo *) NULL)
quantum_info=DestroyQuantumInfo(quantum_info);
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Wrote PNG image data");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Width: %.20g",(double) ping_width);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Height: %.20g",(double) ping_height);
if (mng_info->write_png_depth)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:bit-depth: %d",mng_info->write_png_depth);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG bit-depth written: %d",ping_bit_depth);
if (mng_info->write_png_colortype)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Defined png:color-type: %d",mng_info->write_png_colortype-1);
}
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG color-type written: %d",ping_color_type);
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" PNG Interlace method: %d",ping_interlace_method);
}
/*
Generate text chunks after IDAT.
*/
if (ping_exclude_tEXt == MagickFalse || ping_exclude_zTXt == MagickFalse)
{
ResetImagePropertyIterator(image);
property=GetNextImageProperty(image);
while (property != (const char *) NULL)
{
png_textp
text;
value=GetImageProperty(image,property,exception);
/* Don't write any "png:" or "jpeg:" properties; those are just for
* "identify" or for passing through to another JPEG
*/
if ((LocaleNCompare(property,"png:",4) != 0 &&
LocaleNCompare(property,"jpeg:",5) != 0) &&
/* Suppress density and units if we wrote a pHYs chunk */
(ping_exclude_pHYs != MagickFalse ||
LocaleCompare(property,"density") != 0 ||
LocaleCompare(property,"units") != 0) &&
/* Suppress the IM-generated Date:create and Date:modify */
(ping_exclude_date == MagickFalse ||
LocaleNCompare(property, "Date:",5) != 0))
{
if (value != (const char *) NULL)
{
#if PNG_LIBPNG_VER >= 10400
text=(png_textp) png_malloc(ping,
(png_alloc_size_t) sizeof(png_text));
#else
text=(png_textp) png_malloc(ping,(png_size_t) sizeof(png_text));
#endif
text[0].key=(char *) property;
text[0].text=(char *) value;
text[0].text_length=strlen(value);
if (ping_exclude_tEXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_zTXt;
else if (ping_exclude_zTXt != MagickFalse)
text[0].compression=PNG_TEXT_COMPRESSION_NONE;
else
{
text[0].compression=image_info->compression == NoCompression ||
(image_info->compression == UndefinedCompression &&
text[0].text_length < 128) ? PNG_TEXT_COMPRESSION_NONE :
PNG_TEXT_COMPRESSION_zTXt ;
}
if (logging != MagickFalse)
{
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Setting up text chunk");
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" keyword: '%s'",text[0].key);
}
png_set_text(ping,ping_info,text,1);
png_free(ping,text);
}
}
property=GetNextImageProperty(image);
}
}
/* write any PNG-chunk-e profiles */
(void) Magick_png_write_chunk_from_profile(image,"PNG-chunk-e",logging);
/* write exIf profile */
if (ping_have_eXIf != MagickFalse && ping_exclude_eXIf == MagickFalse)
{
char
*name;
ResetImageProfileIterator(image);
for (name=GetNextImageProfile(image); name != (const char *) NULL; )
{
if (LocaleCompare(name,"exif") == 0)
{
const StringInfo
*profile;
profile=GetImageProfile(image,name);
if (profile != (StringInfo *) NULL)
{
png_uint_32
length;
unsigned char
chunk[4],
*data;
StringInfo
*ping_profile;
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Have eXIf profile");
ping_profile=CloneStringInfo(profile);
data=GetStringInfoDatum(ping_profile),
length=(png_uint_32) GetStringInfoLength(ping_profile);
PNGType(chunk,mng_eXIf);
if (length < 7)
{
ping_profile=DestroyStringInfo(ping_profile);
break; /* otherwise crashes */
}
/* skip the "Exif\0\0" JFIF Exif Header ID */
length -= 6;
LogPNGChunk(logging,chunk,length);
(void) WriteBlobMSBULong(image,length);
(void) WriteBlob(image,4,chunk);
(void) WriteBlob(image,length,data+6);
(void) WriteBlobMSBULong(image,crc32(crc32(0,chunk,4),
data+6, (uInt) length));
ping_profile=DestroyStringInfo(ping_profile);
break;
}
}
name=GetNextImageProfile(image);
}
}
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" Writing PNG end info");
png_write_end(ping,ping_info);
if (mng_info->need_fram && (int) image->dispose == BackgroundDispose)
{
if (mng_info->page.x || mng_info->page.y ||
(ping_width != mng_info->page.width) ||
(ping_height != mng_info->page.height))
{
unsigned char
chunk[32];
/*
Write FRAM 4 with clipping boundaries followed by FRAM 1.
*/
(void) WriteBlobMSBULong(image,27L); /* data length=27 */
PNGType(chunk,mng_FRAM);
LogPNGChunk(logging,mng_FRAM,27L);
chunk[4]=4;
chunk[5]=0; /* frame name separator (no name) */
chunk[6]=1; /* flag for changing delay, for next frame only */
chunk[7]=0; /* flag for changing frame timeout */
chunk[8]=1; /* flag for changing frame clipping for next frame */
chunk[9]=0; /* flag for changing frame sync_id */
PNGLong(chunk+10,(png_uint_32) (0L)); /* temporary 0 delay */
chunk[14]=0; /* clipping boundaries delta type */
PNGLong(chunk+15,(png_uint_32) (mng_info->page.x)); /* left cb */
PNGLong(chunk+19,
(png_uint_32) (mng_info->page.x + ping_width));
PNGLong(chunk+23,(png_uint_32) (mng_info->page.y)); /* top cb */
PNGLong(chunk+27,
(png_uint_32) (mng_info->page.y + ping_height));
(void) WriteBlob(image,31,chunk);
(void) WriteBlobMSBULong(image,crc32(0,chunk,31));
mng_info->old_framing_mode=4;
mng_info->framing_mode=1;
}
else
mng_info->framing_mode=3;
}
if (mng_info->write_mng && !mng_info->need_fram &&
((int) image->dispose == 3))
png_error(ping, "Cannot convert GIF with disposal method 3 to MNG-LC");
/*
Free PNG resources.
*/
png_destroy_write_struct(&ping,&ping_info);
pixel_info=RelinquishVirtualMemory(pixel_info);
if (ping_have_blob != MagickFalse)
(void) CloseBlob(image);
image_info=DestroyImageInfo(image_info);
image=DestroyImage(image);
/* Store bit depth actually written */
s[0]=(char) ping_bit_depth;
s[1]='\0';
(void) SetImageProperty(IMimage,"png:bit-depth-written",s,exception);
if (logging != MagickFalse)
(void) LogMagickEvent(CoderEvent,GetMagickModule(),
" exit WriteOnePNGImage()");
#ifdef IMPNG_SETJMP_NOT_THREAD_SAFE
UnlockSemaphoreInfo(ping_semaphore);
#endif
/* } for navigation to beginning of SETJMP-protected block. Revert to
* Throwing an Exception when an error occurs.
*/
return(MagickTrue);
/* End write one PNG image */
} | {
"deleted": [
{
"line_no": 153,
"char_start": 2509,
"char_end": 2582,
"line": " ThrowWriterException(ResourceLimitError, \"MemoryAllocationFailed\");\n"
}
],
"added": [
{
"line_no": 151,
"char_start": 2412,
"char_end": 2443,
"line": " if (image == (Image *) NULL)\n"
},
{
"line_no": 152,
"char_start": 2443,
"char_end": 2468,
"line": " return(MagickFalse);\n"
},
{
"line_no": 155,
"char_start": 2565,
"char_end": 2637,
"line": " ThrowWriterException(ResourceLimitError, \"MemoryAllocationFailed\");\n"
}
]
} | {
"deleted": [
{
"char_start": 2509,
"char_end": 2510,
"chars": " "
}
],
"added": [
{
"char_start": 2415,
"char_end": 2471,
"chars": "f (image == (Image *) NULL)\n return(MagickFalse);\n i"
}
]
} | github.com/ImageMagick/ImageMagick/commit/816ecab6c532ae086ff4186b3eaf4aa7092d536f | coders/png.c | cwe-476 |
ReadPSDChannel | static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
mask->matte=MagickFalse;
channel_image=mask;
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
} | static MagickBooleanType ReadPSDChannel(Image *image,
const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info,
const size_t channel,const PSDCompressionType compression,
ExceptionInfo *exception)
{
Image
*channel_image,
*mask;
MagickOffsetType
offset;
MagickBooleanType
status;
channel_image=image;
mask=(Image *) NULL;
if (layer_info->channel_info[channel].type < -1)
{
const char
*option;
/*
Ignore mask that is not a user supplied layer mask, if the mask is
disabled or if the flags have unsupported values.
*/
option=GetImageOption(image_info,"psd:preserve-opacity-mask");
if ((layer_info->channel_info[channel].type != -2) ||
(layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) &&
(IsStringTrue(option) == MagickFalse)))
{
SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR);
return(MagickTrue);
}
mask=CloneImage(image,layer_info->mask.page.width,
layer_info->mask.page.height,MagickFalse,exception);
if (mask != (Image *) NULL)
{
mask->matte=MagickFalse;
channel_image=mask;
}
}
offset=TellBlob(image);
status=MagickTrue;
switch(compression)
{
case Raw:
status=ReadPSDChannelRaw(channel_image,psd_info->channels,
layer_info->channel_info[channel].type,exception);
break;
case RLE:
{
MagickOffsetType
*sizes;
sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows);
if (sizes == (MagickOffsetType *) NULL)
ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed",
image->filename);
status=ReadPSDChannelRLE(channel_image,psd_info,
layer_info->channel_info[channel].type,sizes,exception);
sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes);
}
break;
case ZipWithPrediction:
case ZipWithoutPrediction:
#ifdef MAGICKCORE_ZLIB_DELEGATE
status=ReadPSDChannelZip(channel_image,layer_info->channels,
layer_info->channel_info[channel].type,compression,
layer_info->channel_info[channel].size-2,exception);
#else
(void) ThrowMagickException(exception,GetMagickModule(),
MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn",
"'%s' (ZLIB)",image->filename);
#endif
break;
default:
(void) ThrowMagickException(exception,GetMagickModule(),TypeWarning,
"CompressionNotSupported","'%.20g'",(double) compression);
break;
}
SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET);
if (status == MagickFalse)
{
if (mask != (Image *) NULL)
DestroyImage(mask);
ThrowBinaryException(CoderError,"UnableToDecompressImage",
image->filename);
}
layer_info->mask.image=mask;
return(status);
} | {
"deleted": [
{
"line_no": 36,
"char_start": 1110,
"char_end": 1141,
"line": " mask->matte=MagickFalse;\n"
},
{
"line_no": 37,
"char_start": 1141,
"char_end": 1167,
"line": " channel_image=mask;\n"
}
],
"added": [
{
"line_no": 36,
"char_start": 1110,
"char_end": 1144,
"line": " if (mask != (Image *) NULL)\n"
},
{
"line_no": 37,
"char_start": 1144,
"char_end": 1154,
"line": " {\n"
},
{
"line_no": 38,
"char_start": 1154,
"char_end": 1189,
"line": " mask->matte=MagickFalse;\n"
},
{
"line_no": 39,
"char_start": 1189,
"char_end": 1219,
"line": " channel_image=mask;\n"
},
{
"line_no": 40,
"char_start": 1219,
"char_end": 1229,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1116,
"char_end": 1164,
"chars": "if (mask != (Image *) NULL)\n {\n "
},
{
"char_start": 1195,
"char_end": 1199,
"chars": " "
},
{
"char_start": 1218,
"char_end": 1228,
"chars": "\n }"
}
]
} | github.com/ImageMagick/ImageMagick/commit/7f2dc7a1afc067d0c89f12c82bcdec0445fb1b94 | coders/psd.c | cwe-476 |
keyctl_read_key | long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
} | long keyctl_read_key(key_serial_t keyid, char __user *buffer, size_t buflen)
{
struct key *key;
key_ref_t key_ref;
long ret;
/* find the key first */
key_ref = lookup_user_key(keyid, 0, 0);
if (IS_ERR(key_ref)) {
ret = -ENOKEY;
goto error;
}
key = key_ref_to_ptr(key_ref);
if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {
ret = -ENOKEY;
goto error2;
}
/* see if we can read it directly */
ret = key_permission(key_ref, KEY_NEED_READ);
if (ret == 0)
goto can_read_key;
if (ret != -EACCES)
goto error2;
/* we can't; see if it's searchable from this process's keyrings
* - we automatically take account of the fact that it may be
* dangling off an instantiation key
*/
if (!is_key_possessed(key_ref)) {
ret = -EACCES;
goto error2;
}
/* the key is probably readable - now try to read it */
can_read_key:
ret = -EOPNOTSUPP;
if (key->type->read) {
/* Read the data with the semaphore held (since we might sleep)
* to protect against the key being updated or revoked.
*/
down_read(&key->sem);
ret = key_validate(key);
if (ret == 0)
ret = key->type->read(key, buffer, buflen);
up_read(&key->sem);
}
error2:
key_put(key);
error:
return ret;
} | {
"deleted": [],
"added": [
{
"line_no": 16,
"char_start": 288,
"char_end": 337,
"line": "\tif (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n"
},
{
"line_no": 17,
"char_start": 337,
"char_end": 354,
"line": "\t\tret = -ENOKEY;\n"
},
{
"line_no": 18,
"char_start": 354,
"char_end": 369,
"line": "\t\tgoto error2;\n"
},
{
"line_no": 19,
"char_start": 369,
"char_end": 372,
"line": "\t}\n"
},
{
"line_no": 20,
"char_start": 372,
"char_end": 373,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 289,
"char_end": 374,
"chars": "if (test_bit(KEY_FLAG_NEGATIVE, &key->flags)) {\n\t\tret = -ENOKEY;\n\t\tgoto error2;\n\t}\n\n\t"
}
]
} | github.com/torvalds/linux/commit/37863c43b2c6464f252862bf2e9768264e961678 | security/keys/keyctl.c | cwe-476 |
ExprResolveLhs | ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return true;
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
} | ExprResolveLhs(struct xkb_context *ctx, const ExprDef *expr,
const char **elem_rtrn, const char **field_rtrn,
ExprDef **index_rtrn)
{
switch (expr->expr.op) {
case EXPR_IDENT:
*elem_rtrn = NULL;
*field_rtrn = xkb_atom_text(ctx, expr->ident.ident);
*index_rtrn = NULL;
return (*field_rtrn != NULL);
case EXPR_FIELD_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->field_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->field_ref.field);
*index_rtrn = NULL;
return (*elem_rtrn != NULL && *field_rtrn != NULL);
case EXPR_ARRAY_REF:
*elem_rtrn = xkb_atom_text(ctx, expr->array_ref.element);
*field_rtrn = xkb_atom_text(ctx, expr->array_ref.field);
*index_rtrn = expr->array_ref.entry;
if (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)
return false;
if (*field_rtrn == NULL)
return false;
return true;
default:
break;
}
log_wsgo(ctx, "Unexpected operator %d in ResolveLhs\n", expr->expr.op);
return false;
} | {
"deleted": [
{
"line_no": 15,
"char_start": 552,
"char_end": 573,
"line": " return true;\n"
}
],
"added": [
{
"line_no": 15,
"char_start": 552,
"char_end": 612,
"line": " return (*elem_rtrn != NULL && *field_rtrn != NULL);\n"
},
{
"line_no": 20,
"char_start": 813,
"char_end": 882,
"line": "\tif (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)\n"
},
{
"line_no": 21,
"char_start": 882,
"char_end": 898,
"line": "\t\treturn false;\n"
},
{
"line_no": 22,
"char_start": 898,
"char_end": 924,
"line": "\tif (*field_rtrn == NULL)\n"
},
{
"line_no": 23,
"char_start": 924,
"char_end": 940,
"line": "\t\treturn false;\n"
}
]
} | {
"deleted": [
{
"char_start": 569,
"char_end": 570,
"chars": "u"
}
],
"added": [
{
"char_start": 567,
"char_end": 575,
"chars": "(*elem_r"
},
{
"char_start": 577,
"char_end": 593,
"chars": "n != NULL && *fi"
},
{
"char_start": 594,
"char_end": 610,
"chars": "ld_rtrn != NULL)"
},
{
"char_start": 811,
"char_end": 938,
"chars": ";\n\tif (expr->array_ref.element != XKB_ATOM_NONE && *elem_rtrn == NULL)\n\t\treturn false;\n\tif (*field_rtrn == NULL)\n\t\treturn false"
}
]
} | github.com/xkbcommon/libxkbcommon/commit/bb4909d2d8fa6b08155e449986a478101e2b2634 | src/xkbcomp/expr.c | cwe-476 |
tar_directory_for_file | tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)
{
const char *s = name;
while (1) {
const char *s0 = s;
char *dirname;
/* Find a directory component, if any. */
while (1) {
if (*s == 0) {
if (last && s != s0)
break;
else
return dir;
}
/* This is deliberately slash-only. */
if (*s == '/')
break;
s++;
}
dirname = g_strndup (s0, s - s0);
while (*s == '/')
s++;
if (strcmp (dirname, ".") != 0) {
GsfInput *subdir =
gsf_infile_child_by_name (GSF_INFILE (dir),
dirname);
if (subdir) {
/* Undo the ref. */
g_object_unref (subdir);
dir = GSF_INFILE_TAR (subdir);
} else
dir = tar_create_dir (dir, dirname);
}
g_free (dirname);
}
} | tar_directory_for_file (GsfInfileTar *dir, const char *name, gboolean last)
{
const char *s = name;
while (1) {
const char *s0 = s;
char *dirname;
/* Find a directory component, if any. */
while (1) {
if (*s == 0) {
if (last && s != s0)
break;
else
return dir;
}
/* This is deliberately slash-only. */
if (*s == '/')
break;
s++;
}
dirname = g_strndup (s0, s - s0);
while (*s == '/')
s++;
if (strcmp (dirname, ".") != 0) {
GsfInput *subdir =
gsf_infile_child_by_name (GSF_INFILE (dir),
dirname);
if (subdir) {
dir = GSF_IS_INFILE_TAR (subdir)
? GSF_INFILE_TAR (subdir)
: dir;
/* Undo the ref. */
g_object_unref (subdir);
} else
dir = tar_create_dir (dir, dirname);
}
g_free (dirname);
}
} | {
"deleted": [
{
"line_no": 34,
"char_start": 645,
"char_end": 680,
"line": "\t\t\t\tdir = GSF_INFILE_TAR (subdir);\n"
}
],
"added": [
{
"line_no": 32,
"char_start": 592,
"char_end": 629,
"line": "\t\t\t\tdir = GSF_IS_INFILE_TAR (subdir)\n"
},
{
"line_no": 33,
"char_start": 629,
"char_end": 660,
"line": "\t\t\t\t\t? GSF_INFILE_TAR (subdir)\n"
},
{
"line_no": 34,
"char_start": 660,
"char_end": 672,
"line": "\t\t\t\t\t: dir;\n"
}
]
} | {
"deleted": [
{
"char_start": 634,
"char_end": 669,
"chars": " (subdir);\n\t\t\t\tdir = GSF_INFILE_TAR"
}
],
"added": [
{
"char_start": 596,
"char_end": 676,
"chars": "dir = GSF_IS_INFILE_TAR (subdir)\n\t\t\t\t\t? GSF_INFILE_TAR (subdir)\n\t\t\t\t\t: dir;\n\t\t\t\t"
}
]
} | github.com/GNOME/libgsf/commit/95a8351a75758cf10b3bf6abae0b6b461f90d9e5 | gsf/gsf-infile-tar.c | cwe-476 |
crypto_skcipher_init_tfm | static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
return crypto_init_skcipher_ops_blkcipher(tfm);
if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||
tfm->__crt_alg->cra_type == &crypto_givcipher_type)
return crypto_init_skcipher_ops_ablkcipher(tfm);
skcipher->setkey = alg->setkey;
skcipher->encrypt = alg->encrypt;
skcipher->decrypt = alg->decrypt;
skcipher->ivsize = alg->ivsize;
skcipher->keysize = alg->max_keysize;
if (alg->exit)
skcipher->base.exit = crypto_skcipher_exit_tfm;
if (alg->init)
return alg->init(skcipher);
return 0;
} | static int crypto_skcipher_init_tfm(struct crypto_tfm *tfm)
{
struct crypto_skcipher *skcipher = __crypto_skcipher_cast(tfm);
struct skcipher_alg *alg = crypto_skcipher_alg(skcipher);
if (tfm->__crt_alg->cra_type == &crypto_blkcipher_type)
return crypto_init_skcipher_ops_blkcipher(tfm);
if (tfm->__crt_alg->cra_type == &crypto_ablkcipher_type ||
tfm->__crt_alg->cra_type == &crypto_givcipher_type)
return crypto_init_skcipher_ops_ablkcipher(tfm);
skcipher->setkey = skcipher_setkey;
skcipher->encrypt = alg->encrypt;
skcipher->decrypt = alg->decrypt;
skcipher->ivsize = alg->ivsize;
skcipher->keysize = alg->max_keysize;
if (alg->exit)
skcipher->base.exit = crypto_skcipher_exit_tfm;
if (alg->init)
return alg->init(skcipher);
return 0;
} | {
"deleted": [
{
"line_no": 13,
"char_start": 464,
"char_end": 497,
"line": "\tskcipher->setkey = alg->setkey;\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 464,
"char_end": 501,
"line": "\tskcipher->setkey = skcipher_setkey;\n"
}
]
} | {
"deleted": [
{
"char_start": 484,
"char_end": 489,
"chars": "alg->"
}
],
"added": [
{
"char_start": 484,
"char_end": 493,
"chars": "skcipher_"
}
]
} | github.com/torvalds/linux/commit/9933e113c2e87a9f46a40fde8dafbf801dca1ab9 | crypto/skcipher.c | cwe-476 |
fm10k_init_module | static int __init fm10k_init_module(void)
{
pr_info("%s - version %s\n", fm10k_driver_string, fm10k_driver_version);
pr_info("%s\n", fm10k_copyright);
/* create driver workqueue */
fm10k_workqueue = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0,
fm10k_driver_name);
fm10k_dbg_init();
return fm10k_register_pci_driver();
} | static int __init fm10k_init_module(void)
{
pr_info("%s - version %s\n", fm10k_driver_string, fm10k_driver_version);
pr_info("%s\n", fm10k_copyright);
/* create driver workqueue */
fm10k_workqueue = alloc_workqueue("%s", WQ_MEM_RECLAIM, 0,
fm10k_driver_name);
if (!fm10k_workqueue)
return -ENOMEM;
fm10k_dbg_init();
return fm10k_register_pci_driver();
} | {
"deleted": [],
"added": [
{
"line_no": 9,
"char_start": 272,
"char_end": 295,
"line": "\tif (!fm10k_workqueue)\n"
},
{
"line_no": 10,
"char_start": 295,
"char_end": 313,
"line": "\t\treturn -ENOMEM;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 272,
"char_end": 313,
"chars": "\tif (!fm10k_workqueue)\n\t\treturn -ENOMEM;\n"
}
]
} | github.com/torvalds/linux/commit/01ca667133d019edc9f0a1f70a272447c84ec41f | drivers/net/ethernet/intel/fm10k/fm10k_main.c | cwe-476 |
parse_class | static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32(p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
// TODO: this is quite ugly
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
// TODO: move to func, def or inline
// class_data_offset => [class_offset, class_defs_off+class_defs_size*32]
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
//XXX check for NULL!!
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
// TODO:!!!!
// FIX: FREE BEFORE ALLOCATE!!!
//free (class_name);
} | static void parse_class(RBinFile *binfile, RBinDexObj *bin, RBinDexClass *c,
int class_index, int *methods, int *sym_count) {
struct r_bin_t *rbin = binfile->rbin;
char *class_name;
int z;
const ut8 *p, *p_end;
if (!c) {
return;
}
class_name = dex_class_name (bin, c);
class_name = r_str_replace (class_name, ";", "", 0); //TODO: move to func
if (!class_name || !*class_name) {
return;
}
RBinClass *cls = R_NEW0 (RBinClass);
if (!cls) {
return;
}
cls->name = class_name;
cls->index = class_index;
cls->addr = bin->header.class_offset + class_index * DEX_CLASS_SIZE;
cls->methods = r_list_new ();
if (!cls->methods) {
free (cls);
return;
}
cls->fields = r_list_new ();
if (!cls->fields) {
r_list_free (cls->methods);
free (cls);
return;
}
r_list_append (bin->classes_list, cls);
if (dexdump) {
rbin->cb_printf (" Class descriptor : '%s;'\n", class_name);
rbin->cb_printf (
" Access flags : 0x%04x (%s)\n", c->access_flags,
createAccessFlagStr (c->access_flags, kAccessForClass));
rbin->cb_printf (" Superclass : '%s'\n",
dex_class_super_name (bin, c));
rbin->cb_printf (" Interfaces -\n");
}
if (c->interfaces_offset > 0 &&
bin->header.data_offset < c->interfaces_offset &&
c->interfaces_offset <
bin->header.data_offset + bin->header.data_size) {
p = r_buf_get_at (binfile->buf, c->interfaces_offset, NULL);
int types_list_size = r_read_le32 (p);
if (types_list_size < 0 || types_list_size >= bin->header.types_size ) {
return;
}
for (z = 0; z < types_list_size; z++) {
int t = r_read_le16 (p + 4 + z * 2);
if (t > 0 && t < bin->header.types_size ) {
int tid = bin->types[t].descriptor_id;
if (dexdump) {
rbin->cb_printf (
" #%d : '%s'\n",
z, getstr (bin, tid));
}
}
}
}
// TODO: this is quite ugly
if (!c || !c->class_data_offset) {
if (dexdump) {
rbin->cb_printf (
" Static fields -\n Instance fields "
"-\n Direct methods -\n Virtual methods "
"-\n");
}
} else {
// TODO: move to func, def or inline
// class_data_offset => [class_offset, class_defs_off+class_defs_size*32]
if (bin->header.class_offset > c->class_data_offset ||
c->class_data_offset <
bin->header.class_offset +
bin->header.class_size * DEX_CLASS_SIZE) {
return;
}
p = r_buf_get_at (binfile->buf, c->class_data_offset, NULL);
p_end = p + binfile->buf->length - c->class_data_offset;
//XXX check for NULL!!
c->class_data = (struct dex_class_data_item_t *)malloc (
sizeof (struct dex_class_data_item_t));
p = r_uleb128 (p, p_end - p, &c->class_data->static_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->instance_fields_size);
p = r_uleb128 (p, p_end - p, &c->class_data->direct_methods_size);
p = r_uleb128 (p, p_end - p, &c->class_data->virtual_methods_size);
if (dexdump) {
rbin->cb_printf (" Static fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->static_fields_size, true);
if (dexdump) {
rbin->cb_printf (" Instance fields -\n");
}
p = parse_dex_class_fields (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->instance_fields_size, false);
if (dexdump) {
rbin->cb_printf (" Direct methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->direct_methods_size, methods, true);
if (dexdump) {
rbin->cb_printf (" Virtual methods -\n");
}
p = parse_dex_class_method (
binfile, bin, c, cls, p, p_end, sym_count,
c->class_data->virtual_methods_size, methods, false);
}
if (dexdump) {
char *source_file = getstr (bin, c->source_file);
if (!source_file) {
rbin->cb_printf (
" source_file_idx : %d (unknown)\n\n",
c->source_file);
} else {
rbin->cb_printf (" source_file_idx : %d (%s)\n\n",
c->source_file, source_file);
}
}
// TODO:!!!!
// FIX: FREE BEFORE ALLOCATE!!!
//free (class_name);
} | {
"deleted": [
{
"line_no": 54,
"char_start": 1421,
"char_end": 1461,
"line": "\t\tint types_list_size = r_read_le32(p);\n"
}
],
"added": [
{
"line_no": 54,
"char_start": 1421,
"char_end": 1462,
"line": "\t\tint types_list_size = r_read_le32 (p);\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1456,
"char_end": 1457,
"chars": " "
}
]
} | github.com/radare/radare2/commit/1ea23bd6040441a21fbcfba69dce9a01af03f989 | libr/bin/p/bin_dex.c | cwe-476 |
lexer_process_char_literal | lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */ | lexer_process_char_literal (parser_context_t *context_p, /**< context */
const uint8_t *char_p, /**< characters */
size_t length, /**< length of string */
uint8_t literal_type, /**< final literal type */
bool has_escape) /**< has escape sequences */
{
parser_list_iterator_t literal_iterator;
lexer_literal_t *literal_p;
uint32_t literal_index = 0;
JERRY_ASSERT (literal_type == LEXER_IDENT_LITERAL
|| literal_type == LEXER_STRING_LITERAL);
JERRY_ASSERT (literal_type != LEXER_IDENT_LITERAL || length <= PARSER_MAXIMUM_IDENT_LENGTH);
JERRY_ASSERT (literal_type != LEXER_STRING_LITERAL || length <= PARSER_MAXIMUM_STRING_LENGTH);
parser_list_iterator_init (&context_p->literal_pool, &literal_iterator);
while ((literal_p = (lexer_literal_t *) parser_list_iterator_next (&literal_iterator)) != NULL)
{
if (literal_p->type == literal_type
&& literal_p->prop.length == length
&& memcmp (literal_p->u.char_p, char_p, length) == 0)
{
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
literal_p->status_flags = (uint8_t) (literal_p->status_flags & ~LEXER_FLAG_UNUSED_IDENT);
return;
}
literal_index++;
}
JERRY_ASSERT (literal_index == context_p->literal_count);
if (literal_index >= PARSER_MAXIMUM_NUMBER_OF_LITERALS)
{
parser_raise_error (context_p, PARSER_ERR_LITERAL_LIMIT_REACHED);
}
if (length == 0)
{
has_escape = false;
}
literal_p = (lexer_literal_t *) parser_list_append (context_p, &context_p->literal_pool);
literal_p->prop.length = (uint16_t) length;
literal_p->type = literal_type;
literal_p->status_flags = has_escape ? 0 : LEXER_FLAG_SOURCE_PTR;
if (has_escape)
{
literal_p->u.char_p = (uint8_t *) jmem_heap_alloc_block (length);
memcpy ((uint8_t *) literal_p->u.char_p, char_p, length);
}
else
{
literal_p->u.char_p = char_p;
}
context_p->lit_object.literal_p = literal_p;
context_p->lit_object.index = (uint16_t) literal_index;
context_p->literal_count++;
} /* lexer_process_char_literal */ | {
"deleted": [],
"added": [
{
"line_no": 41,
"char_start": 1556,
"char_end": 1575,
"line": " if (length == 0)\n"
},
{
"line_no": 42,
"char_start": 1575,
"char_end": 1579,
"line": " {\n"
},
{
"line_no": 43,
"char_start": 1579,
"char_end": 1603,
"line": " has_escape = false;\n"
},
{
"line_no": 44,
"char_start": 1603,
"char_end": 1607,
"line": " }\n"
},
{
"line_no": 45,
"char_start": 1607,
"char_end": 1608,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1558,
"char_end": 1610,
"chars": "if (length == 0)\n {\n has_escape = false;\n }\n\n "
}
]
} | github.com/jerryscript-project/jerryscript/commit/e58f2880df608652aff7fd35c45b242467ec0e79 | jerry-core/parser/js/js-lexer.c | cwe-476 |
mrb_obj_clone | mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags = mrb_obj_ptr(self)->flags;
return clone;
} | mrb_obj_clone(mrb_state *mrb, mrb_value self)
{
struct RObject *p;
mrb_value clone;
if (mrb_immediate_p(self)) {
mrb_raisef(mrb, E_TYPE_ERROR, "can't clone %S", self);
}
if (mrb_type(self) == MRB_TT_SCLASS) {
mrb_raise(mrb, E_TYPE_ERROR, "can't clone singleton class");
}
p = (struct RObject*)mrb_obj_alloc(mrb, mrb_type(self), mrb_obj_class(mrb, self));
p->c = mrb_singleton_class_clone(mrb, self);
mrb_field_write_barrier(mrb, (struct RBasic*)p, (struct RBasic*)p->c);
clone = mrb_obj_value(p);
init_copy(mrb, clone, self);
p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;
return clone;
} | {
"deleted": [
{
"line_no": 17,
"char_start": 557,
"char_end": 596,
"line": " p->flags = mrb_obj_ptr(self)->flags;\n"
}
],
"added": [
{
"line_no": 17,
"char_start": 557,
"char_end": 618,
"line": " p->flags |= mrb_obj_ptr(self)->flags & MRB_FLAG_IS_FROZEN;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 568,
"char_end": 569,
"chars": "|"
},
{
"char_start": 595,
"char_end": 616,
"chars": " & MRB_FLAG_IS_FROZEN"
}
]
} | github.com/mruby/mruby/commit/55edae0226409de25e59922807cb09acb45731a2 | src/kernel.c | cwe-476 |
big_key_init | static int __init big_key_init(void)
{
return register_key_type(&key_type_big_key);
} | static int __init big_key_init(void)
{
struct crypto_skcipher *cipher;
struct crypto_rng *rng;
int ret;
rng = crypto_alloc_rng(big_key_rng_name, 0, 0);
if (IS_ERR(rng)) {
pr_err("Can't alloc rng: %ld\n", PTR_ERR(rng));
return PTR_ERR(rng);
}
big_key_rng = rng;
/* seed RNG */
ret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng));
if (ret) {
pr_err("Can't reset rng: %d\n", ret);
goto error_rng;
}
/* init block cipher */
cipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC);
if (IS_ERR(cipher)) {
ret = PTR_ERR(cipher);
pr_err("Can't alloc crypto: %d\n", ret);
goto error_rng;
}
big_key_skcipher = cipher;
ret = register_key_type(&key_type_big_key);
if (ret < 0) {
pr_err("Can't register type: %d\n", ret);
goto error_cipher;
}
return 0;
error_cipher:
crypto_free_skcipher(big_key_skcipher);
error_rng:
crypto_free_rng(big_key_rng);
return ret;
} | {
"deleted": [
{
"line_no": 3,
"char_start": 39,
"char_end": 85,
"line": "\treturn register_key_type(&key_type_big_key);\n"
},
{
"line_no": 4,
"char_start": 85,
"char_end": 86,
"line": "}\n"
}
],
"added": []
} | {
"deleted": [],
"added": [
{
"char_start": 40,
"char_end": 42,
"chars": "st"
},
{
"char_start": 43,
"char_end": 68,
"chars": "uct crypto_skcipher *ciph"
},
{
"char_start": 69,
"char_end": 74,
"chars": "r;\n\ts"
},
{
"char_start": 75,
"char_end": 76,
"chars": "r"
},
{
"char_start": 77,
"char_end": 87,
"chars": "ct crypto_"
},
{
"char_start": 89,
"char_end": 672,
"chars": "g *rng;\n\tint ret;\n\n\trng = crypto_alloc_rng(big_key_rng_name, 0, 0);\n\tif (IS_ERR(rng)) {\n\t\tpr_err(\"Can't alloc rng: %ld\\n\", PTR_ERR(rng));\n\t\treturn PTR_ERR(rng);\n\t}\n\n\tbig_key_rng = rng;\n\n\t/* seed RNG */\n\tret = crypto_rng_reset(rng, NULL, crypto_rng_seedsize(rng));\n\tif (ret) {\n\t\tpr_err(\"Can't reset rng: %d\\n\", ret);\n\t\tgoto error_rng;\n\t}\n\n\t/* init block cipher */\n\tcipher = crypto_alloc_skcipher(big_key_alg_name, 0, CRYPTO_ALG_ASYNC);\n\tif (IS_ERR(cipher)) {\n\t\tret = PTR_ERR(cipher);\n\t\tpr_err(\"Can't alloc crypto: %d\\n\", ret);\n\t\tgoto error_rng;\n\t}\n\n\tbig_key_skcipher = cipher;\n\n\tret ="
},
{
"char_start": 709,
"char_end": 916,
"chars": ";\n\tif (ret < 0) {\n\t\tpr_err(\"Can't register type: %d\\n\", ret);\n\t\tgoto error_cipher;\n\t}\n\n\treturn 0;\n\nerror_cipher:\n\tcrypto_free_skcipher(big_key_skcipher);\nerror_rng:\n\tcrypto_free_rng(big_key_rng);\n\treturn ret"
}
]
} | github.com/torvalds/linux/commit/7df3e59c3d1df4f87fe874c7956ef7a3d2f4d5fb | security/keys/big_key.c | cwe-476 |
flattenSubquery | static int flattenSubquery(
Parse *pParse, /* Parsing context */
Select *p, /* The parent or outer SELECT statement */
int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
int isAgg /* True if outer SELECT uses aggregate functions */
){
const char *zSavedAuthContext = pParse->zAuthContext;
Select *pParent; /* Current UNION ALL term of the other query */
Select *pSub; /* The inner query or "subquery" */
Select *pSub1; /* Pointer to the rightmost select in sub-query */
SrcList *pSrc; /* The FROM clause of the outer query */
SrcList *pSubSrc; /* The FROM clause of the subquery */
int iParent; /* VDBE cursor number of the pSub result set temp table */
int iNewParent = -1;/* Replacement table for iParent */
int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
int i; /* Loop counter */
Expr *pWhere; /* The WHERE clause */
struct SrcList_item *pSubitem; /* The subquery */
sqlite3 *db = pParse->db;
/* Check to see if flattening is permitted. Return 0 if not.
*/
assert( p!=0 );
assert( p->pPrior==0 );
if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
pSrc = p->pSrc;
assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
pSubitem = &pSrc->a[iFrom];
iParent = pSubitem->iCursor;
pSub = pSubitem->pSelect;
assert( pSub!=0 );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
#endif
pSubSrc = pSub->pSrc;
assert( pSubSrc );
/* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
** because they could be computed at compile-time. But when LIMIT and OFFSET
** became arbitrary expressions, we were forced to add restrictions (13)
** and (14). */
if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
return 0; /* Restriction (15) */
}
if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
return 0; /* Restrictions (8)(9) */
}
if( p->pOrderBy && pSub->pOrderBy ){
return 0; /* Restriction (11) */
}
if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
return 0; /* Restriction (21) */
}
if( pSub->selFlags & (SF_Recursive) ){
return 0; /* Restrictions (22) */
}
/*
** If the subquery is the right operand of a LEFT JOIN, then the
** subquery may not be a join itself (3a). Example of why this is not
** allowed:
**
** t1 LEFT OUTER JOIN (t2 JOIN t3)
**
** If we flatten the above, we would get
**
** (t1 LEFT OUTER JOIN t2) JOIN t3
**
** which is not at all the same thing.
**
** If the subquery is the right operand of a LEFT JOIN, then the outer
** query cannot be an aggregate. (3c) This is an artifact of the way
** aggregates are processed - there is no mechanism to determine if
** the LEFT JOIN table should be all-NULL.
**
** See also tickets #306, #350, and #3300.
*/
if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
isLeftJoin = 1;
if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){
/* (3a) (3c) (3b) */
return 0;
}
}
#ifdef SQLITE_EXTRA_IFNULLROW
else if( iFrom>0 && !isAgg ){
/* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
** every reference to any result column from subquery in a join, even
** though they are not necessary. This will stress-test the OP_IfNullRow
** opcode. */
isLeftJoin = -1;
}
#endif
/* Restriction (17): If the sub-query is a compound SELECT, then it must
** use only the UNION ALL operator. And none of the simple select queries
** that make up the compound SELECT are allowed to be aggregate or distinct
** queries.
*/
if( pSub->pPrior ){
if( pSub->pOrderBy ){
return 0; /* Restriction (20) */
}
if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
return 0; /* (17d1), (17d2), or (17d3) */
}
for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
assert( pSub->pSrc!=0 );
assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
|| (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
|| pSub1->pSrc->nSrc<1 /* (17c) */
){
return 0;
}
testcase( pSub1->pSrc->nSrc>1 );
}
/* Restriction (18). */
if( p->pOrderBy ){
int ii;
for(ii=0; ii<p->pOrderBy->nExpr; ii++){
if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
}
}
}
/* Ex-restriction (23):
** The only way that the recursive part of a CTE can contain a compound
** subquery is for the subquery to be one term of a join. But if the
** subquery is a join, then the flattening has already been stopped by
** restriction (17d3)
*/
assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
/***** If we reach this point, flattening is permitted. *****/
SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
pSub->selId, pSub, iFrom));
/* Authorize the subquery */
pParse->zAuthContext = pSubitem->zName;
TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
testcase( i==SQLITE_DENY );
pParse->zAuthContext = zSavedAuthContext;
/* If the sub-query is a compound SELECT statement, then (by restrictions
** 17 and 18 above) it must be a UNION ALL and the parent query must
** be of the form:
**
** SELECT <expr-list> FROM (<sub-query>) <where-clause>
**
** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
** OFFSET clauses and joins them to the left-hand-side of the original
** using UNION ALL operators. In this case N is the number of simple
** select statements in the compound sub-query.
**
** Example:
**
** SELECT a+1 FROM (
** SELECT x FROM tab
** UNION ALL
** SELECT y FROM tab
** UNION ALL
** SELECT abs(z*2) FROM tab2
** ) WHERE a!=5 ORDER BY 1
**
** Transformed into:
**
** SELECT x+1 FROM tab WHERE x+1!=5
** UNION ALL
** SELECT y+1 FROM tab WHERE y+1!=5
** UNION ALL
** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
** ORDER BY 1
**
** We call this the "compound-subquery flattening".
*/
for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
Select *pNew;
ExprList *pOrderBy = p->pOrderBy;
Expr *pLimit = p->pLimit;
Select *pPrior = p->pPrior;
p->pOrderBy = 0;
p->pSrc = 0;
p->pPrior = 0;
p->pLimit = 0;
pNew = sqlite3SelectDup(db, p, 0);
p->pLimit = pLimit;
p->pOrderBy = pOrderBy;
p->pSrc = pSrc;
p->op = TK_ALL;
if( pNew==0 ){
p->pPrior = pPrior;
}else{
pNew->pPrior = pPrior;
if( pPrior ) pPrior->pNext = pNew;
pNew->pNext = p;
p->pPrior = pNew;
SELECTTRACE(2,pParse,p,("compound-subquery flattener"
" creates %u as peer\n",pNew->selId));
}
if( db->mallocFailed ) return 1;
}
/* Begin flattening the iFrom-th entry of the FROM clause
** in the outer query.
*/
pSub = pSub1 = pSubitem->pSelect;
/* Delete the transient table structure associated with the
** subquery
*/
sqlite3DbFree(db, pSubitem->zDatabase);
sqlite3DbFree(db, pSubitem->zName);
sqlite3DbFree(db, pSubitem->zAlias);
pSubitem->zDatabase = 0;
pSubitem->zName = 0;
pSubitem->zAlias = 0;
pSubitem->pSelect = 0;
/* Defer deleting the Table object associated with the
** subquery until code generation is
** complete, since there may still exist Expr.pTab entries that
** refer to the subquery even after flattening. Ticket #3346.
**
** pSubitem->pTab is always non-NULL by test restrictions and tests above.
*/
if( ALWAYS(pSubitem->pTab!=0) ){
Table *pTabToDel = pSubitem->pTab;
if( pTabToDel->nTabRef==1 ){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pTabToDel->pNextZombie = pToplevel->pZombieTab;
pToplevel->pZombieTab = pTabToDel;
}else{
pTabToDel->nTabRef--;
}
pSubitem->pTab = 0;
}
/* The following loop runs once for each term in a compound-subquery
** flattening (as described above). If we are doing a different kind
** of flattening - a flattening other than a compound-subquery flattening -
** then this loop only runs once.
**
** This loop moves all of the FROM elements of the subquery into the
** the FROM clause of the outer query. Before doing this, remember
** the cursor number for the original outer query FROM element in
** iParent. The iParent cursor will never be used. Subsequent code
** will scan expressions looking for iParent references and replace
** those references with expressions that resolve to the subquery FROM
** elements we are now copying in.
*/
for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
int nSubSrc;
u8 jointype = 0;
assert( pSub!=0 );
pSubSrc = pSub->pSrc; /* FROM clause of subquery */
nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
pSrc = pParent->pSrc; /* FROM clause of the outer query */
if( pSrc ){
assert( pParent==p ); /* First time through the loop */
jointype = pSubitem->fg.jointype;
}else{
assert( pParent!=p ); /* 2nd and subsequent times through the loop */
pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* The subquery uses a single slot of the FROM clause of the outer
** query. If the subquery has more than one element in its FROM clause,
** then expand the outer query to make space for it to hold all elements
** of the subquery.
**
** Example:
**
** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
**
** The outer query has 3 slots in its FROM clause. One slot of the
** outer query (the middle slot) is used by the subquery. The next
** block of code will expand the outer query FROM clause to 4 slots.
** The middle slot is expanded to two slots in order to make space
** for the two elements in the FROM clause of the subquery.
*/
if( nSubSrc>1 ){
pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* Transfer the FROM clause terms from the subquery into the
** outer query.
*/
for(i=0; i<nSubSrc; i++){
sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
pSrc->a[i+iFrom] = pSubSrc->a[i];
iNewParent = pSubSrc->a[i].iCursor;
memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
}
pSrc->a[iFrom].fg.jointype = jointype;
/* Now begin substituting subquery result set expressions for
** references to the iParent in the outer query.
**
** Example:
**
** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
** \ \_____________ subquery __________/ /
** \_____________________ outer query ______________________________/
**
** We look at every expression in the outer query and every place we see
** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
*/
if( pSub->pOrderBy ){
/* At this point, any non-zero iOrderByCol values indicate that the
** ORDER BY column expression is identical to the iOrderByCol'th
** expression returned by SELECT statement pSub. Since these values
** do not necessarily correspond to columns in SELECT statement pParent,
** zero them before transfering the ORDER BY clause.
**
** Not doing this may cause an error if a subsequent call to this
** function attempts to flatten a compound sub-query into pParent
** (the only way this can happen is if the compound sub-query is
** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
ExprList *pOrderBy = pSub->pOrderBy;
for(i=0; i<pOrderBy->nExpr; i++){
pOrderBy->a[i].u.x.iOrderByCol = 0;
}
assert( pParent->pOrderBy==0 );
pParent->pOrderBy = pOrderBy;
pSub->pOrderBy = 0;
}
pWhere = pSub->pWhere;
pSub->pWhere = 0;
if( isLeftJoin>0 ){
sqlite3SetJoinExpr(pWhere, iNewParent);
}
pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
if( db->mallocFailed==0 ){
SubstContext x;
x.pParse = pParse;
x.iTable = iParent;
x.iNewTable = iNewParent;
x.isLeftJoin = isLeftJoin;
x.pEList = pSub->pEList;
substSelect(&x, pParent, 0);
}
/* The flattened query is a compound if either the inner or the
** outer query is a compound. */
pParent->selFlags |= pSub->selFlags & SF_Compound;
assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
/*
** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
**
** One is tempted to try to add a and b to combine the limits. But this
** does not work if either limit is negative.
*/
if( pSub->pLimit ){
pParent->pLimit = pSub->pLimit;
pSub->pLimit = 0;
}
}
/* Finially, delete what is left of the subquery and return
** success.
*/
sqlite3SelectDelete(db, pSub1);
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
} | static int flattenSubquery(
Parse *pParse, /* Parsing context */
Select *p, /* The parent or outer SELECT statement */
int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
int isAgg /* True if outer SELECT uses aggregate functions */
){
const char *zSavedAuthContext = pParse->zAuthContext;
Select *pParent; /* Current UNION ALL term of the other query */
Select *pSub; /* The inner query or "subquery" */
Select *pSub1; /* Pointer to the rightmost select in sub-query */
SrcList *pSrc; /* The FROM clause of the outer query */
SrcList *pSubSrc; /* The FROM clause of the subquery */
int iParent; /* VDBE cursor number of the pSub result set temp table */
int iNewParent = -1;/* Replacement table for iParent */
int isLeftJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
int i; /* Loop counter */
Expr *pWhere; /* The WHERE clause */
struct SrcList_item *pSubitem; /* The subquery */
sqlite3 *db = pParse->db;
/* Check to see if flattening is permitted. Return 0 if not.
*/
assert( p!=0 );
assert( p->pPrior==0 );
if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
pSrc = p->pSrc;
assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
pSubitem = &pSrc->a[iFrom];
iParent = pSubitem->iCursor;
pSub = pSubitem->pSelect;
assert( pSub!=0 );
#ifndef SQLITE_OMIT_WINDOWFUNC
if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
#endif
pSubSrc = pSub->pSrc;
assert( pSubSrc );
/* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
** because they could be computed at compile-time. But when LIMIT and OFFSET
** became arbitrary expressions, we were forced to add restrictions (13)
** and (14). */
if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
return 0; /* Restriction (15) */
}
if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
return 0; /* Restrictions (8)(9) */
}
if( p->pOrderBy && pSub->pOrderBy ){
return 0; /* Restriction (11) */
}
if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
return 0; /* Restriction (21) */
}
if( pSub->selFlags & (SF_Recursive) ){
return 0; /* Restrictions (22) */
}
/*
** If the subquery is the right operand of a LEFT JOIN, then the
** subquery may not be a join itself (3a). Example of why this is not
** allowed:
**
** t1 LEFT OUTER JOIN (t2 JOIN t3)
**
** If we flatten the above, we would get
**
** (t1 LEFT OUTER JOIN t2) JOIN t3
**
** which is not at all the same thing.
**
** If the subquery is the right operand of a LEFT JOIN, then the outer
** query cannot be an aggregate. (3c) This is an artifact of the way
** aggregates are processed - there is no mechanism to determine if
** the LEFT JOIN table should be all-NULL.
**
** See also tickets #306, #350, and #3300.
*/
if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
isLeftJoin = 1;
if( pSubSrc->nSrc>1 /* (3a) */
|| isAgg /* (3b) */
|| IsVirtual(pSubSrc->a[0].pTab) /* (3c) */
|| (p->selFlags & SF_Distinct)!=0 /* (3d) */
){
return 0;
}
}
#ifdef SQLITE_EXTRA_IFNULLROW
else if( iFrom>0 && !isAgg ){
/* Setting isLeftJoin to -1 causes OP_IfNullRow opcodes to be generated for
** every reference to any result column from subquery in a join, even
** though they are not necessary. This will stress-test the OP_IfNullRow
** opcode. */
isLeftJoin = -1;
}
#endif
/* Restriction (17): If the sub-query is a compound SELECT, then it must
** use only the UNION ALL operator. And none of the simple select queries
** that make up the compound SELECT are allowed to be aggregate or distinct
** queries.
*/
if( pSub->pPrior ){
if( pSub->pOrderBy ){
return 0; /* Restriction (20) */
}
if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
return 0; /* (17d1), (17d2), or (17d3) */
}
for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
assert( pSub->pSrc!=0 );
assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
|| (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
|| pSub1->pSrc->nSrc<1 /* (17c) */
){
return 0;
}
testcase( pSub1->pSrc->nSrc>1 );
}
/* Restriction (18). */
if( p->pOrderBy ){
int ii;
for(ii=0; ii<p->pOrderBy->nExpr; ii++){
if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
}
}
}
/* Ex-restriction (23):
** The only way that the recursive part of a CTE can contain a compound
** subquery is for the subquery to be one term of a join. But if the
** subquery is a join, then the flattening has already been stopped by
** restriction (17d3)
*/
assert( (p->selFlags & SF_Recursive)==0 || pSub->pPrior==0 );
/***** If we reach this point, flattening is permitted. *****/
SELECTTRACE(1,pParse,p,("flatten %u.%p from term %d\n",
pSub->selId, pSub, iFrom));
/* Authorize the subquery */
pParse->zAuthContext = pSubitem->zName;
TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
testcase( i==SQLITE_DENY );
pParse->zAuthContext = zSavedAuthContext;
/* If the sub-query is a compound SELECT statement, then (by restrictions
** 17 and 18 above) it must be a UNION ALL and the parent query must
** be of the form:
**
** SELECT <expr-list> FROM (<sub-query>) <where-clause>
**
** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
** OFFSET clauses and joins them to the left-hand-side of the original
** using UNION ALL operators. In this case N is the number of simple
** select statements in the compound sub-query.
**
** Example:
**
** SELECT a+1 FROM (
** SELECT x FROM tab
** UNION ALL
** SELECT y FROM tab
** UNION ALL
** SELECT abs(z*2) FROM tab2
** ) WHERE a!=5 ORDER BY 1
**
** Transformed into:
**
** SELECT x+1 FROM tab WHERE x+1!=5
** UNION ALL
** SELECT y+1 FROM tab WHERE y+1!=5
** UNION ALL
** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
** ORDER BY 1
**
** We call this the "compound-subquery flattening".
*/
for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
Select *pNew;
ExprList *pOrderBy = p->pOrderBy;
Expr *pLimit = p->pLimit;
Select *pPrior = p->pPrior;
p->pOrderBy = 0;
p->pSrc = 0;
p->pPrior = 0;
p->pLimit = 0;
pNew = sqlite3SelectDup(db, p, 0);
p->pLimit = pLimit;
p->pOrderBy = pOrderBy;
p->pSrc = pSrc;
p->op = TK_ALL;
if( pNew==0 ){
p->pPrior = pPrior;
}else{
pNew->pPrior = pPrior;
if( pPrior ) pPrior->pNext = pNew;
pNew->pNext = p;
p->pPrior = pNew;
SELECTTRACE(2,pParse,p,("compound-subquery flattener"
" creates %u as peer\n",pNew->selId));
}
if( db->mallocFailed ) return 1;
}
/* Begin flattening the iFrom-th entry of the FROM clause
** in the outer query.
*/
pSub = pSub1 = pSubitem->pSelect;
/* Delete the transient table structure associated with the
** subquery
*/
sqlite3DbFree(db, pSubitem->zDatabase);
sqlite3DbFree(db, pSubitem->zName);
sqlite3DbFree(db, pSubitem->zAlias);
pSubitem->zDatabase = 0;
pSubitem->zName = 0;
pSubitem->zAlias = 0;
pSubitem->pSelect = 0;
/* Defer deleting the Table object associated with the
** subquery until code generation is
** complete, since there may still exist Expr.pTab entries that
** refer to the subquery even after flattening. Ticket #3346.
**
** pSubitem->pTab is always non-NULL by test restrictions and tests above.
*/
if( ALWAYS(pSubitem->pTab!=0) ){
Table *pTabToDel = pSubitem->pTab;
if( pTabToDel->nTabRef==1 ){
Parse *pToplevel = sqlite3ParseToplevel(pParse);
pTabToDel->pNextZombie = pToplevel->pZombieTab;
pToplevel->pZombieTab = pTabToDel;
}else{
pTabToDel->nTabRef--;
}
pSubitem->pTab = 0;
}
/* The following loop runs once for each term in a compound-subquery
** flattening (as described above). If we are doing a different kind
** of flattening - a flattening other than a compound-subquery flattening -
** then this loop only runs once.
**
** This loop moves all of the FROM elements of the subquery into the
** the FROM clause of the outer query. Before doing this, remember
** the cursor number for the original outer query FROM element in
** iParent. The iParent cursor will never be used. Subsequent code
** will scan expressions looking for iParent references and replace
** those references with expressions that resolve to the subquery FROM
** elements we are now copying in.
*/
for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
int nSubSrc;
u8 jointype = 0;
assert( pSub!=0 );
pSubSrc = pSub->pSrc; /* FROM clause of subquery */
nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
pSrc = pParent->pSrc; /* FROM clause of the outer query */
if( pSrc ){
assert( pParent==p ); /* First time through the loop */
jointype = pSubitem->fg.jointype;
}else{
assert( pParent!=p ); /* 2nd and subsequent times through the loop */
pSrc = sqlite3SrcListAppend(pParse, 0, 0, 0);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* The subquery uses a single slot of the FROM clause of the outer
** query. If the subquery has more than one element in its FROM clause,
** then expand the outer query to make space for it to hold all elements
** of the subquery.
**
** Example:
**
** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
**
** The outer query has 3 slots in its FROM clause. One slot of the
** outer query (the middle slot) is used by the subquery. The next
** block of code will expand the outer query FROM clause to 4 slots.
** The middle slot is expanded to two slots in order to make space
** for the two elements in the FROM clause of the subquery.
*/
if( nSubSrc>1 ){
pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
if( pSrc==0 ) break;
pParent->pSrc = pSrc;
}
/* Transfer the FROM clause terms from the subquery into the
** outer query.
*/
for(i=0; i<nSubSrc; i++){
sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
pSrc->a[i+iFrom] = pSubSrc->a[i];
iNewParent = pSubSrc->a[i].iCursor;
memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
}
pSrc->a[iFrom].fg.jointype = jointype;
/* Now begin substituting subquery result set expressions for
** references to the iParent in the outer query.
**
** Example:
**
** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
** \ \_____________ subquery __________/ /
** \_____________________ outer query ______________________________/
**
** We look at every expression in the outer query and every place we see
** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
*/
if( pSub->pOrderBy ){
/* At this point, any non-zero iOrderByCol values indicate that the
** ORDER BY column expression is identical to the iOrderByCol'th
** expression returned by SELECT statement pSub. Since these values
** do not necessarily correspond to columns in SELECT statement pParent,
** zero them before transfering the ORDER BY clause.
**
** Not doing this may cause an error if a subsequent call to this
** function attempts to flatten a compound sub-query into pParent
** (the only way this can happen is if the compound sub-query is
** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
ExprList *pOrderBy = pSub->pOrderBy;
for(i=0; i<pOrderBy->nExpr; i++){
pOrderBy->a[i].u.x.iOrderByCol = 0;
}
assert( pParent->pOrderBy==0 );
pParent->pOrderBy = pOrderBy;
pSub->pOrderBy = 0;
}
pWhere = pSub->pWhere;
pSub->pWhere = 0;
if( isLeftJoin>0 ){
sqlite3SetJoinExpr(pWhere, iNewParent);
}
pParent->pWhere = sqlite3ExprAnd(pParse, pWhere, pParent->pWhere);
if( db->mallocFailed==0 ){
SubstContext x;
x.pParse = pParse;
x.iTable = iParent;
x.iNewTable = iNewParent;
x.isLeftJoin = isLeftJoin;
x.pEList = pSub->pEList;
substSelect(&x, pParent, 0);
}
/* The flattened query is a compound if either the inner or the
** outer query is a compound. */
pParent->selFlags |= pSub->selFlags & SF_Compound;
assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
/*
** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
**
** One is tempted to try to add a and b to combine the limits. But this
** does not work if either limit is negative.
*/
if( pSub->pLimit ){
pParent->pLimit = pSub->pLimit;
pSub->pLimit = 0;
}
}
/* Finially, delete what is left of the subquery and return
** success.
*/
sqlite3SelectDelete(db, pSub1);
#if SELECTTRACE_ENABLED
if( sqlite3SelectTrace & 0x100 ){
SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
sqlite3TreeViewSelect(0, p, 0);
}
#endif
return 1;
} | {
"deleted": [
{
"line_no": 88,
"char_start": 3695,
"char_end": 3764,
"line": " if( pSubSrc->nSrc>1 || isAgg || IsVirtual(pSubSrc->a[0].pTab) ){\n"
},
{
"line_no": 89,
"char_start": 3764,
"char_end": 3808,
"line": " /* (3a) (3c) (3b) */\n"
}
],
"added": [
{
"line_no": 88,
"char_start": 3695,
"char_end": 3748,
"line": " if( pSubSrc->nSrc>1 /* (3a) */\n"
},
{
"line_no": 89,
"char_start": 3748,
"char_end": 3801,
"line": " || isAgg /* (3b) */\n"
},
{
"line_no": 90,
"char_start": 3801,
"char_end": 3854,
"line": " || IsVirtual(pSubSrc->a[0].pTab) /* (3c) */\n"
},
{
"line_no": 91,
"char_start": 3854,
"char_end": 3907,
"line": " || (p->selFlags & SF_Distinct)!=0 /* (3d) */\n"
},
{
"line_no": 92,
"char_start": 3907,
"char_end": 3914,
"line": " ){\n"
}
]
} | {
"deleted": [
{
"char_start": 3761,
"char_end": 3766,
"chars": "){\n "
},
{
"char_start": 3772,
"char_end": 3773,
"chars": " "
},
{
"char_start": 3776,
"char_end": 3777,
"chars": "a"
},
{
"char_start": 3793,
"char_end": 3794,
"chars": "c"
},
{
"char_start": 3800,
"char_end": 3803,
"chars": "(3b"
},
{
"char_start": 3804,
"char_end": 3807,
"chars": " */"
}
],
"added": [
{
"char_start": 3719,
"char_end": 3753,
"chars": " /* (3a) */\n "
},
{
"char_start": 3762,
"char_end": 3806,
"chars": " /* (3b) */\n "
},
{
"char_start": 3848,
"char_end": 3849,
"chars": "c"
},
{
"char_start": 3851,
"char_end": 3854,
"chars": "*/\n"
},
{
"char_start": 3859,
"char_end": 3861,
"chars": "||"
},
{
"char_start": 3862,
"char_end": 3874,
"chars": "(p->selFlags"
},
{
"char_start": 3875,
"char_end": 3876,
"chars": "&"
},
{
"char_start": 3877,
"char_end": 3886,
"chars": "SF_Distin"
},
{
"char_start": 3887,
"char_end": 3888,
"chars": "t"
},
{
"char_start": 3889,
"char_end": 3892,
"chars": "!=0"
},
{
"char_start": 3896,
"char_end": 3898,
"chars": "/*"
},
{
"char_start": 3901,
"char_end": 3902,
"chars": "d"
},
{
"char_start": 3906,
"char_end": 3913,
"chars": "\n ){"
}
]
} | github.com/sqlite/sqlite/commit/396afe6f6aa90a31303c183e11b2b2d4b7956b35 | src/select.c | cwe-476 |
CompileKeymap | CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)
{
bool ok;
XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
enum xkb_file_type type;
struct xkb_context *ctx = keymap->ctx;
/* Collect section files and check for duplicates. */
for (file = (XkbFile *) file->defs; file;
file = (XkbFile *) file->common.next) {
if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
file->file_type > LAST_KEYMAP_FILE_TYPE) {
log_err(ctx, "Cannot define %s in a keymap file\n",
xkb_file_type_to_string(file->file_type));
continue;
}
if (files[file->file_type]) {
log_err(ctx,
"More than one %s section in keymap file; "
"All sections after the first ignored\n",
xkb_file_type_to_string(file->file_type));
continue;
}
files[file->file_type] = file;
}
/*
* Check that all required section were provided.
* Report everything before failing.
*/
ok = true;
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
if (files[type] == NULL) {
log_err(ctx, "Required section %s missing from keymap\n",
xkb_file_type_to_string(type));
ok = false;
}
}
if (!ok)
return false;
/* Compile sections. */
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
log_dbg(ctx, "Compiling %s \"%s\"\n",
xkb_file_type_to_string(type), files[type]->name);
ok = compile_file_fns[type](files[type], keymap, merge);
if (!ok) {
log_err(ctx, "Failed to compile %s\n",
xkb_file_type_to_string(type));
return false;
}
}
return UpdateDerivedKeymapFields(keymap);
} | CompileKeymap(XkbFile *file, struct xkb_keymap *keymap, enum merge_mode merge)
{
bool ok;
XkbFile *files[LAST_KEYMAP_FILE_TYPE + 1] = { NULL };
enum xkb_file_type type;
struct xkb_context *ctx = keymap->ctx;
/* Collect section files and check for duplicates. */
for (file = (XkbFile *) file->defs; file;
file = (XkbFile *) file->common.next) {
if (file->file_type < FIRST_KEYMAP_FILE_TYPE ||
file->file_type > LAST_KEYMAP_FILE_TYPE) {
if (file->file_type == FILE_TYPE_GEOMETRY) {
log_vrb(ctx, 1,
"Geometry sections are not supported; ignoring\n");
} else {
log_err(ctx, "Cannot define %s in a keymap file\n",
xkb_file_type_to_string(file->file_type));
}
continue;
}
if (files[file->file_type]) {
log_err(ctx,
"More than one %s section in keymap file; "
"All sections after the first ignored\n",
xkb_file_type_to_string(file->file_type));
continue;
}
files[file->file_type] = file;
}
/*
* Check that all required section were provided.
* Report everything before failing.
*/
ok = true;
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
if (files[type] == NULL) {
log_err(ctx, "Required section %s missing from keymap\n",
xkb_file_type_to_string(type));
ok = false;
}
}
if (!ok)
return false;
/* Compile sections. */
for (type = FIRST_KEYMAP_FILE_TYPE;
type <= LAST_KEYMAP_FILE_TYPE;
type++) {
log_dbg(ctx, "Compiling %s \"%s\"\n",
xkb_file_type_to_string(type), files[type]->name);
ok = compile_file_fns[type](files[type], keymap, merge);
if (!ok) {
log_err(ctx, "Failed to compile %s\n",
xkb_file_type_to_string(type));
return false;
}
}
return UpdateDerivedKeymapFields(keymap);
} | {
"deleted": [
{
"line_no": 13,
"char_start": 489,
"char_end": 553,
"line": " log_err(ctx, \"Cannot define %s in a keymap file\\n\",\n"
},
{
"line_no": 14,
"char_start": 553,
"char_end": 616,
"line": " xkb_file_type_to_string(file->file_type));\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 489,
"char_end": 546,
"line": " if (file->file_type == FILE_TYPE_GEOMETRY) {\n"
},
{
"line_no": 14,
"char_start": 546,
"char_end": 578,
"line": " log_vrb(ctx, 1,\n"
},
{
"line_no": 15,
"char_start": 578,
"char_end": 654,
"line": " \"Geometry sections are not supported; ignoring\\n\");\n"
},
{
"line_no": 16,
"char_start": 654,
"char_end": 675,
"line": " } else {\n"
},
{
"line_no": 17,
"char_start": 675,
"char_end": 743,
"line": " log_err(ctx, \"Cannot define %s in a keymap file\\n\",\n"
},
{
"line_no": 18,
"char_start": 743,
"char_end": 810,
"line": " xkb_file_type_to_string(file->file_type));\n"
},
{
"line_no": 19,
"char_start": 810,
"char_end": 824,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 501,
"char_end": 691,
"chars": "if (file->file_type == FILE_TYPE_GEOMETRY) {\n log_vrb(ctx, 1,\n \"Geometry sections are not supported; ignoring\\n\");\n } else {\n "
},
{
"char_start": 763,
"char_end": 767,
"chars": " "
},
{
"char_start": 809,
"char_end": 823,
"chars": "\n }"
}
]
} | github.com/xkbcommon/libxkbcommon/commit/917636b1d0d70205a13f89062b95e3a0fc31d4ff | src/xkbcomp/keymap.c | cwe-476 |
avpriv_ac3_parse_header | int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
init_get_bits8(&gb, buf, size);
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
} | int avpriv_ac3_parse_header(AC3HeaderInfo **phdr, const uint8_t *buf,
size_t size)
{
GetBitContext gb;
AC3HeaderInfo *hdr;
int err;
if (!*phdr)
*phdr = av_mallocz(sizeof(AC3HeaderInfo));
if (!*phdr)
return AVERROR(ENOMEM);
hdr = *phdr;
err = init_get_bits8(&gb, buf, size);
if (err < 0)
return AVERROR_INVALIDDATA;
err = ff_ac3_parse_header(&gb, hdr);
if (err < 0)
return AVERROR_INVALIDDATA;
return get_bits_count(&gb);
} | {
"deleted": [
{
"line_no": 14,
"char_start": 306,
"char_end": 342,
"line": " init_get_bits8(&gb, buf, size);\n"
}
],
"added": [
{
"line_no": 14,
"char_start": 306,
"char_end": 348,
"line": " err = init_get_bits8(&gb, buf, size);\n"
},
{
"line_no": 15,
"char_start": 348,
"char_end": 365,
"line": " if (err < 0)\n"
},
{
"line_no": 16,
"char_start": 365,
"char_end": 401,
"line": " return AVERROR_INVALIDDATA;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 310,
"char_end": 316,
"chars": "err = "
},
{
"char_start": 346,
"char_end": 399,
"chars": ";\n if (err < 0)\n return AVERROR_INVALIDDATA"
}
]
} | github.com/FFmpeg/FFmpeg/commit/00e8181bd97c834fe60751b0c511d4bb97875f78 | libavcodec/ac3_parser.c | cwe-476 |
mailimf_group_parse | static int mailimf_group_parse(const char * message, size_t length,
size_t * indx,
struct mailimf_group ** result)
{
size_t cur_token;
char * display_name;
struct mailimf_mailbox_list * mailbox_list;
struct mailimf_group * group;
int r;
int res;
cur_token = * indx;
mailbox_list = NULL;
r = mailimf_display_name_parse(message, length, &cur_token, &display_name);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto err;
}
r = mailimf_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_display_name;
}
r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list);
switch (r) {
case MAILIMF_NO_ERROR:
break;
case MAILIMF_ERROR_PARSE:
r = mailimf_cfws_parse(message, length, &cur_token);
if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) {
res = r;
goto free_display_name;
}
break;
default:
res = r;
goto free_display_name;
}
r = mailimf_semi_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_mailbox_list;
}
group = mailimf_group_new(display_name, mailbox_list);
if (group == NULL) {
res = MAILIMF_ERROR_MEMORY;
goto free_mailbox_list;
}
* indx = cur_token;
* result = group;
return MAILIMF_NO_ERROR;
free_mailbox_list:
if (mailbox_list != NULL) {
mailimf_mailbox_list_free(mailbox_list);
}
free_display_name:
mailimf_display_name_free(display_name);
err:
return res;
} | static int mailimf_group_parse(const char * message, size_t length,
size_t * indx,
struct mailimf_group ** result)
{
size_t cur_token;
char * display_name;
struct mailimf_mailbox_list * mailbox_list;
struct mailimf_group * group;
int r;
int res;
clist * list;
cur_token = * indx;
mailbox_list = NULL;
r = mailimf_display_name_parse(message, length, &cur_token, &display_name);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto err;
}
r = mailimf_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_display_name;
}
r = mailimf_mailbox_list_parse(message, length, &cur_token, &mailbox_list);
switch (r) {
case MAILIMF_NO_ERROR:
break;
case MAILIMF_ERROR_PARSE:
r = mailimf_cfws_parse(message, length, &cur_token);
if ((r != MAILIMF_NO_ERROR) && (r != MAILIMF_ERROR_PARSE)) {
res = r;
goto free_display_name;
}
list = clist_new();
if (list == NULL) {
res = MAILIMF_ERROR_MEMORY;
goto free_display_name;
}
mailbox_list = mailimf_mailbox_list_new(list);
if (mailbox_list == NULL) {
res = MAILIMF_ERROR_MEMORY;
clist_free(list);
goto free_display_name;
}
break;
default:
res = r;
goto free_display_name;
}
r = mailimf_semi_colon_parse(message, length, &cur_token);
if (r != MAILIMF_NO_ERROR) {
res = r;
goto free_mailbox_list;
}
group = mailimf_group_new(display_name, mailbox_list);
if (group == NULL) {
res = MAILIMF_ERROR_MEMORY;
goto free_mailbox_list;
}
* indx = cur_token;
* result = group;
return MAILIMF_NO_ERROR;
free_mailbox_list:
if (mailbox_list != NULL) {
mailimf_mailbox_list_free(mailbox_list);
}
free_display_name:
mailimf_display_name_free(display_name);
err:
return res;
} | {
"deleted": [],
"added": [
{
"line_no": 11,
"char_start": 278,
"char_end": 294,
"line": " clist * list;\n"
},
{
"line_no": 39,
"char_start": 946,
"char_end": 970,
"line": " list = clist_new();\n"
},
{
"line_no": 40,
"char_start": 970,
"char_end": 994,
"line": " if (list == NULL) {\n"
},
{
"line_no": 41,
"char_start": 994,
"char_end": 1028,
"line": " res = MAILIMF_ERROR_MEMORY;\n"
},
{
"line_no": 42,
"char_start": 1028,
"char_end": 1058,
"line": " goto free_display_name;\n"
},
{
"line_no": 43,
"char_start": 1058,
"char_end": 1064,
"line": " }\n"
},
{
"line_no": 44,
"char_start": 1064,
"char_end": 1115,
"line": " mailbox_list = mailimf_mailbox_list_new(list);\n"
},
{
"line_no": 45,
"char_start": 1115,
"char_end": 1147,
"line": " if (mailbox_list == NULL) {\n"
},
{
"line_no": 46,
"char_start": 1147,
"char_end": 1181,
"line": " res = MAILIMF_ERROR_MEMORY;\n"
},
{
"line_no": 47,
"char_start": 1181,
"char_end": 1205,
"line": " clist_free(list);\n"
},
{
"line_no": 48,
"char_start": 1205,
"char_end": 1235,
"line": " goto free_display_name;\n"
},
{
"line_no": 49,
"char_start": 1235,
"char_end": 1241,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 278,
"char_end": 294,
"chars": " clist * list;\n"
},
{
"char_start": 908,
"char_end": 1203,
"chars": ";\n goto free_display_name;\n }\n list = clist_new();\n if (list == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n goto free_display_name;\n }\n mailbox_list = mailimf_mailbox_list_new(list);\n if (mailbox_list == NULL) {\n res = MAILIMF_ERROR_MEMORY;\n clist_free(list)"
}
]
} | github.com/dinhviethoa/libetpan/commit/1fe8fbc032ccda1db9af66d93016b49c16c1f22d | src/low-level/imf/mailimf.c | cwe-476 |
srpt_handle_tsk_mgmt | static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct srp_tsk_mgmt *srp_tsk;
struct se_cmd *cmd;
struct se_session *sess = ch->sess;
uint64_t unpacked_lun;
uint32_t tag = 0;
int tcm_tmr;
int rc;
BUG_ON(!send_ioctx);
srp_tsk = recv_ioctx->ioctx.buf;
cmd = &send_ioctx->cmd;
pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld"
" cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func,
srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);
srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);
send_ioctx->cmd.tag = srp_tsk->tag;
tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);
if (tcm_tmr < 0) {
send_ioctx->cmd.se_tmr_req->response =
TMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;
goto fail;
}
unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,
sizeof(srp_tsk->lun));
if (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {
rc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);
if (rc < 0) {
send_ioctx->cmd.se_tmr_req->response =
TMR_TASK_DOES_NOT_EXIST;
goto fail;
}
tag = srp_tsk->task_tag;
}
rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,
srp_tsk, tcm_tmr, GFP_KERNEL, tag,
TARGET_SCF_ACK_KREF);
if (rc != 0) {
send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;
goto fail;
}
return;
fail:
transport_send_check_condition_and_sense(cmd, 0, 0); // XXX:
} | static void srpt_handle_tsk_mgmt(struct srpt_rdma_ch *ch,
struct srpt_recv_ioctx *recv_ioctx,
struct srpt_send_ioctx *send_ioctx)
{
struct srp_tsk_mgmt *srp_tsk;
struct se_cmd *cmd;
struct se_session *sess = ch->sess;
uint64_t unpacked_lun;
int tcm_tmr;
int rc;
BUG_ON(!send_ioctx);
srp_tsk = recv_ioctx->ioctx.buf;
cmd = &send_ioctx->cmd;
pr_debug("recv tsk_mgmt fn %d for task_tag %lld and cmd tag %lld"
" cm_id %p sess %p\n", srp_tsk->tsk_mgmt_func,
srp_tsk->task_tag, srp_tsk->tag, ch->cm_id, ch->sess);
srpt_set_cmd_state(send_ioctx, SRPT_STATE_MGMT);
send_ioctx->cmd.tag = srp_tsk->tag;
tcm_tmr = srp_tmr_to_tcm(srp_tsk->tsk_mgmt_func);
unpacked_lun = srpt_unpack_lun((uint8_t *)&srp_tsk->lun,
sizeof(srp_tsk->lun));
rc = target_submit_tmr(&send_ioctx->cmd, sess, NULL, unpacked_lun,
srp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag,
TARGET_SCF_ACK_KREF);
if (rc != 0) {
send_ioctx->cmd.se_tmr_req->response = TMR_FUNCTION_REJECTED;
goto fail;
}
return;
fail:
transport_send_check_condition_and_sense(cmd, 0, 0); // XXX:
} | {
"deleted": [
{
"line_no": 9,
"char_start": 255,
"char_end": 274,
"line": "\tuint32_t tag = 0;\n"
},
{
"line_no": 25,
"char_start": 695,
"char_end": 715,
"line": "\tif (tcm_tmr < 0) {\n"
},
{
"line_no": 26,
"char_start": 715,
"char_end": 756,
"line": "\t\tsend_ioctx->cmd.se_tmr_req->response =\n"
},
{
"line_no": 27,
"char_start": 756,
"char_end": 797,
"line": "\t\t\tTMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;\n"
},
{
"line_no": 28,
"char_start": 797,
"char_end": 810,
"line": "\t\tgoto fail;\n"
},
{
"line_no": 29,
"char_start": 810,
"char_end": 813,
"line": "\t}\n"
},
{
"line_no": 32,
"char_start": 905,
"char_end": 906,
"line": "\n"
},
{
"line_no": 33,
"char_start": 906,
"char_end": 959,
"line": "\tif (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {\n"
},
{
"line_no": 34,
"char_start": 959,
"char_end": 1018,
"line": "\t\trc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);\n"
},
{
"line_no": 35,
"char_start": 1018,
"char_end": 1034,
"line": "\t\tif (rc < 0) {\n"
},
{
"line_no": 36,
"char_start": 1034,
"char_end": 1076,
"line": "\t\t\tsend_ioctx->cmd.se_tmr_req->response =\n"
},
{
"line_no": 37,
"char_start": 1076,
"char_end": 1106,
"line": "\t\t\t\t\tTMR_TASK_DOES_NOT_EXIST;\n"
},
{
"line_no": 38,
"char_start": 1106,
"char_end": 1120,
"line": "\t\t\tgoto fail;\n"
},
{
"line_no": 39,
"char_start": 1120,
"char_end": 1124,
"line": "\t\t}\n"
},
{
"line_no": 40,
"char_start": 1124,
"char_end": 1151,
"line": "\t\ttag = srp_tsk->task_tag;\n"
},
{
"line_no": 41,
"char_start": 1151,
"char_end": 1154,
"line": "\t}\n"
},
{
"line_no": 43,
"char_start": 1222,
"char_end": 1261,
"line": "\t\t\t\tsrp_tsk, tcm_tmr, GFP_KERNEL, tag,\n"
}
],
"added": [
{
"line_no": 27,
"char_start": 836,
"char_end": 889,
"line": "\t\t\t\tsrp_tsk, tcm_tmr, GFP_KERNEL, srp_tsk->task_tag,\n"
}
]
} | {
"deleted": [
{
"char_start": 256,
"char_end": 275,
"chars": "uint32_t tag = 0;\n\t"
},
{
"char_start": 696,
"char_end": 814,
"chars": "if (tcm_tmr < 0) {\n\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\tTMR_TASK_MGMT_FUNCTION_NOT_SUPPORTED;\n\t\tgoto fail;\n\t}\n\t"
},
{
"char_start": 904,
"char_end": 1153,
"chars": "\n\n\tif (srp_tsk->tsk_mgmt_func == SRP_TSK_ABORT_TASK) {\n\t\trc = srpt_rx_mgmt_fn_tag(send_ioctx, srp_tsk->task_tag);\n\t\tif (rc < 0) {\n\t\t\tsend_ioctx->cmd.se_tmr_req->response =\n\t\t\t\t\tTMR_TASK_DOES_NOT_EXIST;\n\t\t\tgoto fail;\n\t\t}\n\t\ttag = srp_tsk->task_tag;\n\t}"
}
],
"added": [
{
"char_start": 870,
"char_end": 884,
"chars": "srp_tsk->task_"
}
]
} | github.com/torvalds/linux/commit/51093254bf879bc9ce96590400a87897c7498463 | drivers/infiniband/ulp/srpt/ib_srpt.c | cwe-476 |
ResolveStateAndPredicate | ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,
xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
{
if (expr == NULL) {
*pred_rtrn = MATCH_ANY_OR_NONE;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
*pred_rtrn = MATCH_EXACTLY;
if (expr->expr.op == EXPR_ACTION_DECL) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);
if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {
log_err(info->ctx,
"Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
return false;
}
expr = expr->action.args;
}
else if (expr->expr.op == EXPR_IDENT) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);
if (pred_txt && istreq(pred_txt, "any")) {
*pred_rtrn = MATCH_ANY;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
}
return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,
mods_rtrn);
} | ResolveStateAndPredicate(ExprDef *expr, enum xkb_match_operation *pred_rtrn,
xkb_mod_mask_t *mods_rtrn, CompatInfo *info)
{
if (expr == NULL) {
*pred_rtrn = MATCH_ANY_OR_NONE;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
*pred_rtrn = MATCH_EXACTLY;
if (expr->expr.op == EXPR_ACTION_DECL) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->action.name);
if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) ||
!expr->action.args) {
log_err(info->ctx,
"Illegal modifier predicate \"%s\"; Ignored\n", pred_txt);
return false;
}
expr = expr->action.args;
}
else if (expr->expr.op == EXPR_IDENT) {
const char *pred_txt = xkb_atom_text(info->ctx, expr->ident.ident);
if (pred_txt && istreq(pred_txt, "any")) {
*pred_rtrn = MATCH_ANY;
*mods_rtrn = MOD_REAL_MASK_ALL;
return true;
}
}
return ExprResolveModMask(info->ctx, expr, MOD_REAL, &info->mods,
mods_rtrn);
} | {
"deleted": [
{
"line_no": 13,
"char_start": 434,
"char_end": 512,
"line": " if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn)) {\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 434,
"char_end": 512,
"line": " if (!LookupString(symInterpretMatchMaskNames, pred_txt, pred_rtrn) ||\n"
},
{
"line_no": 14,
"char_start": 512,
"char_end": 546,
"line": " !expr->action.args) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 508,
"char_end": 542,
"chars": " ||\n !expr->action.args"
}
]
} | github.com/xkbcommon/libxkbcommon/commit/96df3106d49438e442510c59acad306e94f3db4d | src/xkbcomp/compat.c | cwe-476 |
GetOutboundPinholeTimeout | GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
} | GetOutboundPinholeTimeout(struct upnphttp * h, const char * action, const char * ns)
{
int r;
static const char resp[] =
"<u:%sResponse "
"xmlns:u=\"%s\">"
"<OutboundPinholeTimeout>%d</OutboundPinholeTimeout>"
"</u:%sResponse>";
char body[512];
int bodylen;
struct NameValueParserData data;
char * int_ip, * int_port, * rem_host, * rem_port, * protocol;
int opt=0;
/*int proto=0;*/
unsigned short iport, rport;
if (GETFLAG(IPV6FCFWDISABLEDMASK))
{
SoapError(h, 702, "FirewallDisabled");
return;
}
ParseNameValue(h->req_buf + h->req_contentoff, h->req_contentlen, &data);
int_ip = GetValueFromNameValueList(&data, "InternalClient");
int_port = GetValueFromNameValueList(&data, "InternalPort");
rem_host = GetValueFromNameValueList(&data, "RemoteHost");
rem_port = GetValueFromNameValueList(&data, "RemotePort");
protocol = GetValueFromNameValueList(&data, "Protocol");
if (!int_port || !ext_port || !protocol)
{
ClearNameValueList(&data);
SoapError(h, 402, "Invalid Args");
return;
}
rport = (unsigned short)atoi(rem_port);
iport = (unsigned short)atoi(int_port);
/*proto = atoi(protocol);*/
syslog(LOG_INFO, "%s: retrieving timeout for outbound pinhole from [%s]:%hu to [%s]:%hu protocol %s", action, int_ip, iport,rem_host, rport, protocol);
/* TODO */
r = -1;/*upnp_check_outbound_pinhole(proto, &opt);*/
switch(r)
{
case 1: /* success */
bodylen = snprintf(body, sizeof(body), resp,
action, ns/*"urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"*/,
opt, action);
BuildSendAndCloseSoapResp(h, body, bodylen);
break;
case -5: /* Protocol not supported */
SoapError(h, 705, "ProtocolNotSupported");
break;
default:
SoapError(h, 501, "ActionFailed");
}
ClearNameValueList(&data);
} | {
"deleted": [],
"added": [
{
"line_no": 32,
"char_start": 903,
"char_end": 945,
"line": "\tif (!int_port || !ext_port || !protocol)\n"
},
{
"line_no": 33,
"char_start": 945,
"char_end": 948,
"line": "\t{\n"
},
{
"line_no": 34,
"char_start": 948,
"char_end": 977,
"line": "\t\tClearNameValueList(&data);\n"
},
{
"line_no": 35,
"char_start": 977,
"char_end": 1014,
"line": "\t\tSoapError(h, 402, \"Invalid Args\");\n"
},
{
"line_no": 36,
"char_start": 1014,
"char_end": 1024,
"line": "\t\treturn;\n"
},
{
"line_no": 37,
"char_start": 1024,
"char_end": 1027,
"line": "\t}\n"
},
{
"line_no": 38,
"char_start": 1027,
"char_end": 1028,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 904,
"char_end": 1029,
"chars": "if (!int_port || !ext_port || !protocol)\n\t{\n\t\tClearNameValueList(&data);\n\t\tSoapError(h, 402, \"Invalid Args\");\n\t\treturn;\n\t}\n\n\t"
}
]
} | github.com/miniupnp/miniupnp/commit/13585f15c7f7dc28bbbba1661efb280d530d114c | miniupnpd/upnpsoap.c | cwe-476 |
AP4_AtomSampleTable::GetSample | AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have an stsc atom
if (!m_StscAtom) {
return AP4_ERROR_INVALID_FORMAT;
}
// check that we have a chunk offset table
if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// MP4 uses 1-based indexes internally, so adjust by one
index++;
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
if (AP4_FAILED(result)) return result;
// check that the result is within bounds
if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
} else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
if (AP4_FAILED(result)) return result;
// compute the additional offset inside the chunk
for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(i, size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(i, size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
result = m_SttsAtom->GetDts(index, dts, &duration);
if (AP4_FAILED(result)) return result;
sample.SetDuration(duration);
sample.SetDts(dts);
if (m_CttsAtom == NULL) {
sample.SetCts(dts);
} else {
result = m_CttsAtom->GetCtsOffset(index, cts_offset);
if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
}
// set the size
AP4_Size sample_size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(index, sample_size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(index, sample_size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
if (m_StssAtom == NULL) {
sample.SetSync(true);
} else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
// set the offset
sample.SetOffset(offset);
// set the data stream
sample.SetDataStream(m_SampleStream);
return AP4_SUCCESS;
} | AP4_AtomSampleTable::GetSample(AP4_Ordinal index,
AP4_Sample& sample)
{
AP4_Result result;
// check that we have an stsc atom
if (!m_StscAtom) {
return AP4_ERROR_INVALID_FORMAT;
}
// check that we have a chunk offset table
if (m_StcoAtom == NULL && m_Co64Atom == NULL) {
return AP4_ERROR_INVALID_FORMAT;
}
// MP4 uses 1-based indexes internally, so adjust by one
index++;
// find out in which chunk this sample is located
AP4_Ordinal chunk, skip, desc;
result = m_StscAtom->GetChunkForSample(index, chunk, skip, desc);
if (AP4_FAILED(result)) return result;
// check that the result is within bounds
if (skip > index) return AP4_ERROR_INTERNAL;
// get the atom offset for this chunk
AP4_UI64 offset;
if (m_StcoAtom) {
AP4_UI32 offset_32;
result = m_StcoAtom->GetChunkOffset(chunk, offset_32);
offset = offset_32;
} else {
result = m_Co64Atom->GetChunkOffset(chunk, offset);
}
if (AP4_FAILED(result)) return result;
// compute the additional offset inside the chunk
for (unsigned int i = index-skip; i < index; i++) {
AP4_Size size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(i, size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(i, size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
offset += size;
}
// set the description index
sample.SetDescriptionIndex(desc-1); // adjust for 0-based indexes
// set the dts and cts
AP4_UI32 cts_offset = 0;
AP4_UI64 dts = 0;
AP4_UI32 duration = 0;
if (m_SttsAtom) {
result = m_SttsAtom->GetDts(index, dts, &duration);
if (AP4_FAILED(result)) return result;
}
sample.SetDuration(duration);
sample.SetDts(dts);
if (m_CttsAtom == NULL) {
sample.SetCts(dts);
} else {
result = m_CttsAtom->GetCtsOffset(index, cts_offset);
if (AP4_FAILED(result)) return result;
sample.SetCtsDelta(cts_offset);
}
// set the size
AP4_Size sample_size = 0;
if (m_StszAtom) {
result = m_StszAtom->GetSampleSize(index, sample_size);
} else if (m_Stz2Atom) {
result = m_Stz2Atom->GetSampleSize(index, sample_size);
} else {
result = AP4_ERROR_INVALID_FORMAT;
}
if (AP4_FAILED(result)) return result;
sample.SetSize(sample_size);
// set the sync flag
if (m_StssAtom == NULL) {
sample.SetSync(true);
} else {
sample.SetSync(m_StssAtom->IsSampleSync(index));
}
// set the offset
sample.SetOffset(offset);
// set the data stream
sample.SetDataStream(m_SampleStream);
return AP4_SUCCESS;
} | {
"deleted": [
{
"line_no": 59,
"char_start": 1780,
"char_end": 1836,
"line": " result = m_SttsAtom->GetDts(index, dts, &duration);\n"
},
{
"line_no": 60,
"char_start": 1836,
"char_end": 1879,
"line": " if (AP4_FAILED(result)) return result;\n"
}
],
"added": [
{
"line_no": 59,
"char_start": 1780,
"char_end": 1802,
"line": " if (m_SttsAtom) {\n"
},
{
"line_no": 60,
"char_start": 1802,
"char_end": 1862,
"line": " result = m_SttsAtom->GetDts(index, dts, &duration);\n"
},
{
"line_no": 61,
"char_start": 1862,
"char_end": 1909,
"line": " if (AP4_FAILED(result)) return result;\n"
},
{
"line_no": 62,
"char_start": 1909,
"char_end": 1915,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1784,
"char_end": 1810,
"chars": "if (m_SttsAtom) {\n "
},
{
"char_start": 1866,
"char_end": 1870,
"chars": " "
},
{
"char_start": 1908,
"char_end": 1914,
"chars": "\n }"
}
]
} | github.com/axiomatic-systems/Bento4/commit/2f267f89f957088197f4b1fc254632d1645b415d | Source/C++/Core/Ap4AtomSampleTable.cpp | cwe-476 |
acc_ctx_cont | acc_ctx_cont(OM_uint32 *minstat,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 ret, tmpmin;
gss_OID supportedMech;
spnego_gss_ctx_id_t sc;
unsigned int len;
unsigned char *ptr, *bufstart;
sc = (spnego_gss_ctx_id_t)*ctx;
ret = GSS_S_DEFECTIVE_TOKEN;
*negState = REJECT;
*minstat = 0;
supportedMech = GSS_C_NO_OID;
*return_token = ERROR_TOKEN_SEND;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
#define REMAIN (buf->length - (ptr - bufstart))
if (REMAIN > INT_MAX)
return GSS_S_DEFECTIVE_TOKEN;
/*
* Attempt to work with old Sun SPNEGO.
*/
if (*ptr == HEADER_ID) {
ret = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (ret) {
*minstat = ret;
return GSS_S_DEFECTIVE_TOKEN;
}
}
if (*ptr != (CONTEXT | 0x01)) {
return GSS_S_DEFECTIVE_TOKEN;
}
ret = get_negTokenResp(minstat, ptr, REMAIN,
negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (*responseToken == GSS_C_NO_BUFFER &&
*mechListMIC == GSS_C_NO_BUFFER) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
if (supportedMech != GSS_C_NO_OID) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
sc->firstpass = 0;
*negState = ACCEPT_INCOMPLETE;
*return_token = CONT_TOKEN_SEND;
cleanup:
if (supportedMech != GSS_C_NO_OID) {
generic_gss_release_oid(&tmpmin, &supportedMech);
}
return ret;
#undef REMAIN
} | acc_ctx_cont(OM_uint32 *minstat,
gss_buffer_t buf,
gss_ctx_id_t *ctx,
gss_buffer_t *responseToken,
gss_buffer_t *mechListMIC,
OM_uint32 *negState,
send_token_flag *return_token)
{
OM_uint32 ret, tmpmin;
gss_OID supportedMech;
spnego_gss_ctx_id_t sc;
unsigned int len;
unsigned char *ptr, *bufstart;
sc = (spnego_gss_ctx_id_t)*ctx;
ret = GSS_S_DEFECTIVE_TOKEN;
*negState = REJECT;
*minstat = 0;
supportedMech = GSS_C_NO_OID;
*return_token = ERROR_TOKEN_SEND;
*responseToken = *mechListMIC = GSS_C_NO_BUFFER;
ptr = bufstart = buf->value;
#define REMAIN (buf->length - (ptr - bufstart))
if (REMAIN == 0 || REMAIN > INT_MAX)
return GSS_S_DEFECTIVE_TOKEN;
/*
* Attempt to work with old Sun SPNEGO.
*/
if (*ptr == HEADER_ID) {
ret = g_verify_token_header(gss_mech_spnego,
&len, &ptr, 0, REMAIN);
if (ret) {
*minstat = ret;
return GSS_S_DEFECTIVE_TOKEN;
}
}
if (*ptr != (CONTEXT | 0x01)) {
return GSS_S_DEFECTIVE_TOKEN;
}
ret = get_negTokenResp(minstat, ptr, REMAIN,
negState, &supportedMech,
responseToken, mechListMIC);
if (ret != GSS_S_COMPLETE)
goto cleanup;
if (*responseToken == GSS_C_NO_BUFFER &&
*mechListMIC == GSS_C_NO_BUFFER) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
if (supportedMech != GSS_C_NO_OID) {
ret = GSS_S_DEFECTIVE_TOKEN;
goto cleanup;
}
sc->firstpass = 0;
*negState = ACCEPT_INCOMPLETE;
*return_token = CONT_TOKEN_SEND;
cleanup:
if (supportedMech != GSS_C_NO_OID) {
generic_gss_release_oid(&tmpmin, &supportedMech);
}
return ret;
#undef REMAIN
} | {
"deleted": [
{
"line_no": 25,
"char_start": 635,
"char_end": 658,
"line": "\tif (REMAIN > INT_MAX)\n"
}
],
"added": [
{
"line_no": 25,
"char_start": 635,
"char_end": 673,
"line": "\tif (REMAIN == 0 || REMAIN > INT_MAX)\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 647,
"char_end": 662,
"chars": "== 0 || REMAIN "
}
]
} | github.com/krb5/krb5/commit/524688ce87a15fc75f87efc8c039ba4c7d5c197b | src/lib/gssapi/spnego/spnego_mech.c | cwe-476 |
chmd_read_headers | static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
/* consider blank filenames to be an error */
if (name_len == 0) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) {
if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) {
chm->sec1.content = fi;
}
else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) {
chm->sec1.control = fi;
}
else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {
chm->sec1.spaninfo = fi;
}
else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) {
chm->sec1.rtable = fi;
}
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
} | static int chmd_read_headers(struct mspack_system *sys, struct mspack_file *fh,
struct mschmd_header *chm, int entire)
{
unsigned int section, name_len, x, errors, num_chunks;
unsigned char buf[0x54], *chunk = NULL, *name, *p, *end;
struct mschmd_file *fi, *link = NULL;
off_t offset, length;
int num_entries;
/* initialise pointers */
chm->files = NULL;
chm->sysfiles = NULL;
chm->chunk_cache = NULL;
chm->sec0.base.chm = chm;
chm->sec0.base.id = 0;
chm->sec1.base.chm = chm;
chm->sec1.base.id = 1;
chm->sec1.content = NULL;
chm->sec1.control = NULL;
chm->sec1.spaninfo = NULL;
chm->sec1.rtable = NULL;
/* read the first header */
if (sys->read(fh, &buf[0], chmhead_SIZEOF) != chmhead_SIZEOF) {
return MSPACK_ERR_READ;
}
/* check ITSF signature */
if (EndGetI32(&buf[chmhead_Signature]) != 0x46535449) {
return MSPACK_ERR_SIGNATURE;
}
/* check both header GUIDs */
if (mspack_memcmp(&buf[chmhead_GUID1], &guids[0], 32L) != 0) {
D(("incorrect GUIDs"))
return MSPACK_ERR_SIGNATURE;
}
chm->version = EndGetI32(&buf[chmhead_Version]);
chm->timestamp = EndGetM32(&buf[chmhead_Timestamp]);
chm->language = EndGetI32(&buf[chmhead_LanguageID]);
if (chm->version > 3) {
sys->message(fh, "WARNING; CHM version > 3");
}
/* read the header section table */
if (sys->read(fh, &buf[0], chmhst3_SIZEOF) != chmhst3_SIZEOF) {
return MSPACK_ERR_READ;
}
/* chmhst3_OffsetCS0 does not exist in version 1 or 2 CHM files.
* The offset will be corrected later, once HS1 is read.
*/
if (read_off64(&offset, &buf[chmhst_OffsetHS0], sys, fh) ||
read_off64(&chm->dir_offset, &buf[chmhst_OffsetHS1], sys, fh) ||
read_off64(&chm->sec0.offset, &buf[chmhst3_OffsetCS0], sys, fh))
{
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 0 */
if (sys->seek(fh, offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 0 */
if (sys->read(fh, &buf[0], chmhs0_SIZEOF) != chmhs0_SIZEOF) {
return MSPACK_ERR_READ;
}
if (read_off64(&chm->length, &buf[chmhs0_FileLen], sys, fh)) {
return MSPACK_ERR_DATAFORMAT;
}
/* seek to header section 1 */
if (sys->seek(fh, chm->dir_offset, MSPACK_SYS_SEEK_START)) {
return MSPACK_ERR_SEEK;
}
/* read header section 1 */
if (sys->read(fh, &buf[0], chmhs1_SIZEOF) != chmhs1_SIZEOF) {
return MSPACK_ERR_READ;
}
chm->dir_offset = sys->tell(fh);
chm->chunk_size = EndGetI32(&buf[chmhs1_ChunkSize]);
chm->density = EndGetI32(&buf[chmhs1_Density]);
chm->depth = EndGetI32(&buf[chmhs1_Depth]);
chm->index_root = EndGetI32(&buf[chmhs1_IndexRoot]);
chm->num_chunks = EndGetI32(&buf[chmhs1_NumChunks]);
chm->first_pmgl = EndGetI32(&buf[chmhs1_FirstPMGL]);
chm->last_pmgl = EndGetI32(&buf[chmhs1_LastPMGL]);
if (chm->version < 3) {
/* versions before 3 don't have chmhst3_OffsetCS0 */
chm->sec0.offset = chm->dir_offset + (chm->chunk_size * chm->num_chunks);
}
/* check if content offset or file size is wrong */
if (chm->sec0.offset > chm->length) {
D(("content section begins after file has ended"))
return MSPACK_ERR_DATAFORMAT;
}
/* ensure there are chunks and that chunk size is
* large enough for signature and num_entries */
if (chm->chunk_size < (pmgl_Entries + 2)) {
D(("chunk size not large enough"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->num_chunks == 0) {
D(("no chunks"))
return MSPACK_ERR_DATAFORMAT;
}
/* The chunk_cache data structure is not great; large values for num_chunks
* or num_chunks*chunk_size can exhaust all memory. Until a better chunk
* cache is implemented, put arbitrary limits on num_chunks and chunk size.
*/
if (chm->num_chunks > 100000) {
D(("more than 100,000 chunks"))
return MSPACK_ERR_DATAFORMAT;
}
if ((off_t)chm->chunk_size * (off_t)chm->num_chunks > chm->length) {
D(("chunks larger than entire file"))
return MSPACK_ERR_DATAFORMAT;
}
/* common sense checks on header section 1 fields */
if ((chm->chunk_size & (chm->chunk_size - 1)) != 0) {
sys->message(fh, "WARNING; chunk size is not a power of two");
}
if (chm->first_pmgl != 0) {
sys->message(fh, "WARNING; first PMGL chunk is not zero");
}
if (chm->first_pmgl > chm->last_pmgl) {
D(("first pmgl chunk is after last pmgl chunk"))
return MSPACK_ERR_DATAFORMAT;
}
if (chm->index_root != 0xFFFFFFFF && chm->index_root >= chm->num_chunks) {
D(("index_root outside valid range"))
return MSPACK_ERR_DATAFORMAT;
}
/* if we are doing a quick read, stop here! */
if (!entire) {
return MSPACK_ERR_OK;
}
/* seek to the first PMGL chunk, and reduce the number of chunks to read */
if ((x = chm->first_pmgl) != 0) {
if (sys->seek(fh,(off_t) (x * chm->chunk_size), MSPACK_SYS_SEEK_CUR)) {
return MSPACK_ERR_SEEK;
}
}
num_chunks = chm->last_pmgl - x + 1;
if (!(chunk = (unsigned char *) sys->alloc(sys, (size_t)chm->chunk_size))) {
return MSPACK_ERR_NOMEMORY;
}
/* read and process all chunks from FirstPMGL to LastPMGL */
errors = 0;
while (num_chunks--) {
/* read next chunk */
if (sys->read(fh, chunk, (int)chm->chunk_size) != (int)chm->chunk_size) {
sys->free(chunk);
return MSPACK_ERR_READ;
}
/* process only directory (PMGL) chunks */
if (EndGetI32(&chunk[pmgl_Signature]) != 0x4C474D50) continue;
if (EndGetI32(&chunk[pmgl_QuickRefSize]) < 2) {
sys->message(fh, "WARNING; PMGL quickref area is too small");
}
if (EndGetI32(&chunk[pmgl_QuickRefSize]) >
((int)chm->chunk_size - pmgl_Entries))
{
sys->message(fh, "WARNING; PMGL quickref area is too large");
}
p = &chunk[pmgl_Entries];
end = &chunk[chm->chunk_size - 2];
num_entries = EndGetI16(end);
while (num_entries--) {
READ_ENCINT(name_len);
if (name_len > (unsigned int) (end - p)) goto chunk_end;
name = p; p += name_len;
READ_ENCINT(section);
READ_ENCINT(offset);
READ_ENCINT(length);
/* ignore blank or one-char (e.g. "/") filenames we'd return as blank */
if (name_len < 2 || !name[0] || !name[1]) continue;
/* empty files and directory names are stored as a file entry at
* offset 0 with length 0. We want to keep empty files, but not
* directory names, which end with a "/" */
if ((offset == 0) && (length == 0)) {
if ((name_len > 0) && (name[name_len-1] == '/')) continue;
}
if (section > 1) {
sys->message(fh, "invalid section number '%u'.", section);
continue;
}
if (!(fi = (struct mschmd_file *) sys->alloc(sys, sizeof(struct mschmd_file) + name_len + 1))) {
sys->free(chunk);
return MSPACK_ERR_NOMEMORY;
}
fi->next = NULL;
fi->filename = (char *) &fi[1];
fi->section = ((section == 0) ? (struct mschmd_section *) (&chm->sec0)
: (struct mschmd_section *) (&chm->sec1));
fi->offset = offset;
fi->length = length;
sys->copy(name, fi->filename, (size_t) name_len);
fi->filename[name_len] = '\0';
if (name[0] == ':' && name[1] == ':') {
/* system file */
if (mspack_memcmp(&name[2], &content_name[2], 31L) == 0) {
if (mspack_memcmp(&name[33], &content_name[33], 8L) == 0) {
chm->sec1.content = fi;
}
else if (mspack_memcmp(&name[33], &control_name[33], 11L) == 0) {
chm->sec1.control = fi;
}
else if (mspack_memcmp(&name[33], &spaninfo_name[33], 8L) == 0) {
chm->sec1.spaninfo = fi;
}
else if (mspack_memcmp(&name[33], &rtable_name[33], 72L) == 0) {
chm->sec1.rtable = fi;
}
}
fi->next = chm->sysfiles;
chm->sysfiles = fi;
}
else {
/* normal file */
if (link) link->next = fi; else chm->files = fi;
link = fi;
}
}
/* this is reached either when num_entries runs out, or if
* reading data from the chunk reached a premature end of chunk */
chunk_end:
if (num_entries >= 0) {
D(("chunk ended before all entries could be read"))
errors++;
}
}
sys->free(chunk);
return (errors > 0) ? MSPACK_ERR_DATAFORMAT : MSPACK_ERR_OK;
} | {
"deleted": [
{
"line_no": 189,
"char_start": 6005,
"char_end": 6057,
"line": " /* consider blank filenames to be an error */\n"
},
{
"line_no": 190,
"char_start": 6057,
"char_end": 6098,
"line": " if (name_len == 0) goto chunk_end;\n"
},
{
"line_no": 192,
"char_start": 6129,
"char_end": 6130,
"line": "\n"
}
],
"added": [
{
"line_no": 194,
"char_start": 6119,
"char_end": 6198,
"line": " /* ignore blank or one-char (e.g. \"/\") filenames we'd return as blank */\n"
},
{
"line_no": 195,
"char_start": 6198,
"char_end": 6256,
"line": " if (name_len < 2 || !name[0] || !name[1]) continue;\n"
},
{
"line_no": 196,
"char_start": 6256,
"char_end": 6257,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 6011,
"char_end": 6104,
"chars": "/* consider blank filenames to be an error */\n if (name_len == 0) goto chunk_end;\n "
},
{
"char_start": 6128,
"char_end": 6129,
"chars": "\n"
}
],
"added": [
{
"char_start": 6116,
"char_end": 6254,
"chars": ";\n\n /* ignore blank or one-char (e.g. \"/\") filenames we'd return as blank */\n if (name_len < 2 || !name[0] || !name[1]) continue"
}
]
} | github.com/kyz/libmspack/commit/8759da8db6ec9e866cb8eb143313f397f925bb4f | libmspack/mspack/chmd.c | cwe-476 |
filter_session_io | filter_session_io(struct io *io, int evt, void *arg)
{
struct filter_session *fs = arg;
char *line = NULL;
ssize_t len;
log_trace(TRACE_IO, "filter session: %p: %s %s", fs, io_strevent(evt),
io_strio(io));
switch (evt) {
case IO_DATAIN:
nextline:
line = io_getline(fs->io, &len);
/* No complete line received */
if (line == NULL)
return;
filter_data(fs->id, line);
goto nextline;
case IO_DISCONNECTED:
io_free(fs->io);
fs->io = NULL;
break;
}
} | filter_session_io(struct io *io, int evt, void *arg)
{
struct filter_session *fs = arg;
char *line = NULL;
ssize_t len;
log_trace(TRACE_IO, "filter session: %p: %s %s", fs, io_strevent(evt),
io_strio(io));
switch (evt) {
case IO_DATAIN:
nextline:
line = io_getline(fs->io, &len);
/* No complete line received */
if (line == NULL)
return;
filter_data(fs->id, line);
goto nextline;
}
} | {
"deleted": [
{
"line_no": 21,
"char_start": 409,
"char_end": 410,
"line": "\n"
},
{
"line_no": 22,
"char_start": 410,
"char_end": 433,
"line": "\tcase IO_DISCONNECTED:\n"
},
{
"line_no": 23,
"char_start": 433,
"char_end": 452,
"line": "\t\tio_free(fs->io);\n"
},
{
"line_no": 24,
"char_start": 452,
"char_end": 469,
"line": "\t\tfs->io = NULL;\n"
},
{
"line_no": 25,
"char_start": 469,
"char_end": 478,
"line": "\t\tbreak;\n"
}
],
"added": []
} | {
"deleted": [
{
"char_start": 409,
"char_end": 478,
"chars": "\n\tcase IO_DISCONNECTED:\n\t\tio_free(fs->io);\n\t\tfs->io = NULL;\n\t\tbreak;\n"
}
],
"added": []
} | github.com/openbsd/src/commit/6c3220444ed06b5796dedfd53a0f4becd903c0d1 | usr.sbin/smtpd/lka_filter.c | cwe-476 |
x86_decode_insn | int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len)
{
int rc = X86EMUL_CONTINUE;
int mode = ctxt->mode;
int def_op_bytes, def_ad_bytes, goffset, simd_prefix;
bool op_prefix = false;
bool has_seg_override = false;
struct opcode opcode;
ctxt->memop.type = OP_NONE;
ctxt->memopp = NULL;
ctxt->_eip = ctxt->eip;
ctxt->fetch.ptr = ctxt->fetch.data;
ctxt->fetch.end = ctxt->fetch.data + insn_len;
ctxt->opcode_len = 1;
if (insn_len > 0)
memcpy(ctxt->fetch.data, insn, insn_len);
else {
rc = __do_insn_fetch_bytes(ctxt, 1);
if (rc != X86EMUL_CONTINUE)
return rc;
}
switch (mode) {
case X86EMUL_MODE_REAL:
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
def_op_bytes = def_ad_bytes = 2;
break;
case X86EMUL_MODE_PROT32:
def_op_bytes = def_ad_bytes = 4;
break;
#ifdef CONFIG_X86_64
case X86EMUL_MODE_PROT64:
def_op_bytes = 4;
def_ad_bytes = 8;
break;
#endif
default:
return EMULATION_FAILED;
}
ctxt->op_bytes = def_op_bytes;
ctxt->ad_bytes = def_ad_bytes;
/* Legacy prefixes. */
for (;;) {
switch (ctxt->b = insn_fetch(u8, ctxt)) {
case 0x66: /* operand-size override */
op_prefix = true;
/* switch between 2/4 bytes */
ctxt->op_bytes = def_op_bytes ^ 6;
break;
case 0x67: /* address-size override */
if (mode == X86EMUL_MODE_PROT64)
/* switch between 4/8 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 12;
else
/* switch between 2/4 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 6;
break;
case 0x26: /* ES override */
case 0x2e: /* CS override */
case 0x36: /* SS override */
case 0x3e: /* DS override */
has_seg_override = true;
ctxt->seg_override = (ctxt->b >> 3) & 3;
break;
case 0x64: /* FS override */
case 0x65: /* GS override */
has_seg_override = true;
ctxt->seg_override = ctxt->b & 7;
break;
case 0x40 ... 0x4f: /* REX */
if (mode != X86EMUL_MODE_PROT64)
goto done_prefixes;
ctxt->rex_prefix = ctxt->b;
continue;
case 0xf0: /* LOCK */
ctxt->lock_prefix = 1;
break;
case 0xf2: /* REPNE/REPNZ */
case 0xf3: /* REP/REPE/REPZ */
ctxt->rep_prefix = ctxt->b;
break;
default:
goto done_prefixes;
}
/* Any legacy prefix after a REX prefix nullifies its effect. */
ctxt->rex_prefix = 0;
}
done_prefixes:
/* REX prefix. */
if (ctxt->rex_prefix & 8)
ctxt->op_bytes = 8; /* REX.W */
/* Opcode byte(s). */
opcode = opcode_table[ctxt->b];
/* Two-byte opcode? */
if (ctxt->b == 0x0f) {
ctxt->opcode_len = 2;
ctxt->b = insn_fetch(u8, ctxt);
opcode = twobyte_table[ctxt->b];
/* 0F_38 opcode map */
if (ctxt->b == 0x38) {
ctxt->opcode_len = 3;
ctxt->b = insn_fetch(u8, ctxt);
opcode = opcode_map_0f_38[ctxt->b];
}
}
ctxt->d = opcode.flags;
if (ctxt->d & ModRM)
ctxt->modrm = insn_fetch(u8, ctxt);
/* vex-prefix instructions are not implemented */
if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) &&
(mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) {
ctxt->d = NotImpl;
}
while (ctxt->d & GroupMask) {
switch (ctxt->d & GroupMask) {
case Group:
goffset = (ctxt->modrm >> 3) & 7;
opcode = opcode.u.group[goffset];
break;
case GroupDual:
goffset = (ctxt->modrm >> 3) & 7;
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.gdual->mod3[goffset];
else
opcode = opcode.u.gdual->mod012[goffset];
break;
case RMExt:
goffset = ctxt->modrm & 7;
opcode = opcode.u.group[goffset];
break;
case Prefix:
if (ctxt->rep_prefix && op_prefix)
return EMULATION_FAILED;
simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix;
switch (simd_prefix) {
case 0x00: opcode = opcode.u.gprefix->pfx_no; break;
case 0x66: opcode = opcode.u.gprefix->pfx_66; break;
case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break;
case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break;
}
break;
case Escape:
if (ctxt->modrm > 0xbf)
opcode = opcode.u.esc->high[ctxt->modrm - 0xc0];
else
opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7];
break;
case InstrDual:
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.idual->mod3;
else
opcode = opcode.u.idual->mod012;
break;
case ModeDual:
if (ctxt->mode == X86EMUL_MODE_PROT64)
opcode = opcode.u.mdual->mode64;
else
opcode = opcode.u.mdual->mode32;
break;
default:
return EMULATION_FAILED;
}
ctxt->d &= ~(u64)GroupMask;
ctxt->d |= opcode.flags;
}
/* Unrecognised? */
if (ctxt->d == 0)
return EMULATION_FAILED;
ctxt->execute = opcode.u.execute;
if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD)))
return EMULATION_FAILED;
if (unlikely(ctxt->d &
(NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch|
No16))) {
/*
* These are copied unconditionally here, and checked unconditionally
* in x86_emulate_insn.
*/
ctxt->check_perm = opcode.check_perm;
ctxt->intercept = opcode.intercept;
if (ctxt->d & NotImpl)
return EMULATION_FAILED;
if (mode == X86EMUL_MODE_PROT64) {
if (ctxt->op_bytes == 4 && (ctxt->d & Stack))
ctxt->op_bytes = 8;
else if (ctxt->d & NearBranch)
ctxt->op_bytes = 8;
}
if (ctxt->d & Op3264) {
if (mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
else
ctxt->op_bytes = 4;
}
if ((ctxt->d & No16) && ctxt->op_bytes == 2)
ctxt->op_bytes = 4;
if (ctxt->d & Sse)
ctxt->op_bytes = 16;
else if (ctxt->d & Mmx)
ctxt->op_bytes = 8;
}
/* ModRM and SIB bytes. */
if (ctxt->d & ModRM) {
rc = decode_modrm(ctxt, &ctxt->memop);
if (!has_seg_override) {
has_seg_override = true;
ctxt->seg_override = ctxt->modrm_seg;
}
} else if (ctxt->d & MemAbs)
rc = decode_abs(ctxt, &ctxt->memop);
if (rc != X86EMUL_CONTINUE)
goto done;
if (!has_seg_override)
ctxt->seg_override = VCPU_SREG_DS;
ctxt->memop.addr.mem.seg = ctxt->seg_override;
/*
* Decode and fetch the source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/*
* Decode and fetch the second source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/* Decode and fetch the destination operand: register or memory. */
rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask);
if (ctxt->rip_relative)
ctxt->memopp->addr.mem.ea = address_mask(ctxt,
ctxt->memopp->addr.mem.ea + ctxt->_eip);
done:
return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK;
} | int x86_decode_insn(struct x86_emulate_ctxt *ctxt, void *insn, int insn_len)
{
int rc = X86EMUL_CONTINUE;
int mode = ctxt->mode;
int def_op_bytes, def_ad_bytes, goffset, simd_prefix;
bool op_prefix = false;
bool has_seg_override = false;
struct opcode opcode;
ctxt->memop.type = OP_NONE;
ctxt->memopp = NULL;
ctxt->_eip = ctxt->eip;
ctxt->fetch.ptr = ctxt->fetch.data;
ctxt->fetch.end = ctxt->fetch.data + insn_len;
ctxt->opcode_len = 1;
if (insn_len > 0)
memcpy(ctxt->fetch.data, insn, insn_len);
else {
rc = __do_insn_fetch_bytes(ctxt, 1);
if (rc != X86EMUL_CONTINUE)
return rc;
}
switch (mode) {
case X86EMUL_MODE_REAL:
case X86EMUL_MODE_VM86:
case X86EMUL_MODE_PROT16:
def_op_bytes = def_ad_bytes = 2;
break;
case X86EMUL_MODE_PROT32:
def_op_bytes = def_ad_bytes = 4;
break;
#ifdef CONFIG_X86_64
case X86EMUL_MODE_PROT64:
def_op_bytes = 4;
def_ad_bytes = 8;
break;
#endif
default:
return EMULATION_FAILED;
}
ctxt->op_bytes = def_op_bytes;
ctxt->ad_bytes = def_ad_bytes;
/* Legacy prefixes. */
for (;;) {
switch (ctxt->b = insn_fetch(u8, ctxt)) {
case 0x66: /* operand-size override */
op_prefix = true;
/* switch between 2/4 bytes */
ctxt->op_bytes = def_op_bytes ^ 6;
break;
case 0x67: /* address-size override */
if (mode == X86EMUL_MODE_PROT64)
/* switch between 4/8 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 12;
else
/* switch between 2/4 bytes */
ctxt->ad_bytes = def_ad_bytes ^ 6;
break;
case 0x26: /* ES override */
case 0x2e: /* CS override */
case 0x36: /* SS override */
case 0x3e: /* DS override */
has_seg_override = true;
ctxt->seg_override = (ctxt->b >> 3) & 3;
break;
case 0x64: /* FS override */
case 0x65: /* GS override */
has_seg_override = true;
ctxt->seg_override = ctxt->b & 7;
break;
case 0x40 ... 0x4f: /* REX */
if (mode != X86EMUL_MODE_PROT64)
goto done_prefixes;
ctxt->rex_prefix = ctxt->b;
continue;
case 0xf0: /* LOCK */
ctxt->lock_prefix = 1;
break;
case 0xf2: /* REPNE/REPNZ */
case 0xf3: /* REP/REPE/REPZ */
ctxt->rep_prefix = ctxt->b;
break;
default:
goto done_prefixes;
}
/* Any legacy prefix after a REX prefix nullifies its effect. */
ctxt->rex_prefix = 0;
}
done_prefixes:
/* REX prefix. */
if (ctxt->rex_prefix & 8)
ctxt->op_bytes = 8; /* REX.W */
/* Opcode byte(s). */
opcode = opcode_table[ctxt->b];
/* Two-byte opcode? */
if (ctxt->b == 0x0f) {
ctxt->opcode_len = 2;
ctxt->b = insn_fetch(u8, ctxt);
opcode = twobyte_table[ctxt->b];
/* 0F_38 opcode map */
if (ctxt->b == 0x38) {
ctxt->opcode_len = 3;
ctxt->b = insn_fetch(u8, ctxt);
opcode = opcode_map_0f_38[ctxt->b];
}
}
ctxt->d = opcode.flags;
if (ctxt->d & ModRM)
ctxt->modrm = insn_fetch(u8, ctxt);
/* vex-prefix instructions are not implemented */
if (ctxt->opcode_len == 1 && (ctxt->b == 0xc5 || ctxt->b == 0xc4) &&
(mode == X86EMUL_MODE_PROT64 || (ctxt->modrm & 0xc0) == 0xc0)) {
ctxt->d = NotImpl;
}
while (ctxt->d & GroupMask) {
switch (ctxt->d & GroupMask) {
case Group:
goffset = (ctxt->modrm >> 3) & 7;
opcode = opcode.u.group[goffset];
break;
case GroupDual:
goffset = (ctxt->modrm >> 3) & 7;
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.gdual->mod3[goffset];
else
opcode = opcode.u.gdual->mod012[goffset];
break;
case RMExt:
goffset = ctxt->modrm & 7;
opcode = opcode.u.group[goffset];
break;
case Prefix:
if (ctxt->rep_prefix && op_prefix)
return EMULATION_FAILED;
simd_prefix = op_prefix ? 0x66 : ctxt->rep_prefix;
switch (simd_prefix) {
case 0x00: opcode = opcode.u.gprefix->pfx_no; break;
case 0x66: opcode = opcode.u.gprefix->pfx_66; break;
case 0xf2: opcode = opcode.u.gprefix->pfx_f2; break;
case 0xf3: opcode = opcode.u.gprefix->pfx_f3; break;
}
break;
case Escape:
if (ctxt->modrm > 0xbf)
opcode = opcode.u.esc->high[ctxt->modrm - 0xc0];
else
opcode = opcode.u.esc->op[(ctxt->modrm >> 3) & 7];
break;
case InstrDual:
if ((ctxt->modrm >> 6) == 3)
opcode = opcode.u.idual->mod3;
else
opcode = opcode.u.idual->mod012;
break;
case ModeDual:
if (ctxt->mode == X86EMUL_MODE_PROT64)
opcode = opcode.u.mdual->mode64;
else
opcode = opcode.u.mdual->mode32;
break;
default:
return EMULATION_FAILED;
}
ctxt->d &= ~(u64)GroupMask;
ctxt->d |= opcode.flags;
}
/* Unrecognised? */
if (ctxt->d == 0)
return EMULATION_FAILED;
ctxt->execute = opcode.u.execute;
if (unlikely(ctxt->ud) && likely(!(ctxt->d & EmulateOnUD)))
return EMULATION_FAILED;
if (unlikely(ctxt->d &
(NotImpl|Stack|Op3264|Sse|Mmx|Intercept|CheckPerm|NearBranch|
No16))) {
/*
* These are copied unconditionally here, and checked unconditionally
* in x86_emulate_insn.
*/
ctxt->check_perm = opcode.check_perm;
ctxt->intercept = opcode.intercept;
if (ctxt->d & NotImpl)
return EMULATION_FAILED;
if (mode == X86EMUL_MODE_PROT64) {
if (ctxt->op_bytes == 4 && (ctxt->d & Stack))
ctxt->op_bytes = 8;
else if (ctxt->d & NearBranch)
ctxt->op_bytes = 8;
}
if (ctxt->d & Op3264) {
if (mode == X86EMUL_MODE_PROT64)
ctxt->op_bytes = 8;
else
ctxt->op_bytes = 4;
}
if ((ctxt->d & No16) && ctxt->op_bytes == 2)
ctxt->op_bytes = 4;
if (ctxt->d & Sse)
ctxt->op_bytes = 16;
else if (ctxt->d & Mmx)
ctxt->op_bytes = 8;
}
/* ModRM and SIB bytes. */
if (ctxt->d & ModRM) {
rc = decode_modrm(ctxt, &ctxt->memop);
if (!has_seg_override) {
has_seg_override = true;
ctxt->seg_override = ctxt->modrm_seg;
}
} else if (ctxt->d & MemAbs)
rc = decode_abs(ctxt, &ctxt->memop);
if (rc != X86EMUL_CONTINUE)
goto done;
if (!has_seg_override)
ctxt->seg_override = VCPU_SREG_DS;
ctxt->memop.addr.mem.seg = ctxt->seg_override;
/*
* Decode and fetch the source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src, (ctxt->d >> SrcShift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/*
* Decode and fetch the second source operand: register, memory
* or immediate.
*/
rc = decode_operand(ctxt, &ctxt->src2, (ctxt->d >> Src2Shift) & OpMask);
if (rc != X86EMUL_CONTINUE)
goto done;
/* Decode and fetch the destination operand: register or memory. */
rc = decode_operand(ctxt, &ctxt->dst, (ctxt->d >> DstShift) & OpMask);
if (ctxt->rip_relative && likely(ctxt->memopp))
ctxt->memopp->addr.mem.ea = address_mask(ctxt,
ctxt->memopp->addr.mem.ea + ctxt->_eip);
done:
return (rc != X86EMUL_CONTINUE) ? EMULATION_FAILED : EMULATION_OK;
} | {
"deleted": [
{
"line_no": 262,
"char_start": 6416,
"char_end": 6441,
"line": "\tif (ctxt->rip_relative)\n"
}
],
"added": [
{
"line_no": 262,
"char_start": 6416,
"char_end": 6465,
"line": "\tif (ctxt->rip_relative && likely(ctxt->memopp))\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 6439,
"char_end": 6463,
"chars": " && likely(ctxt->memopp)"
}
]
} | github.com/torvalds/linux/commit/d9092f52d7e61dd1557f2db2400ddb430e85937e | arch/x86/kvm/emulate.c | cwe-476 |
expand_downwards | int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error;
address &= PAGE_MASK;
error = security_mmap_addr(address);
if (error)
return error;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
} | int expand_downwards(struct vm_area_struct *vma,
unsigned long address)
{
struct mm_struct *mm = vma->vm_mm;
struct vm_area_struct *prev;
int error = 0;
address &= PAGE_MASK;
if (address < mmap_min_addr)
return -EPERM;
/* Enforce stack_guard_gap */
prev = vma->vm_prev;
/* Check that both stack segments have the same anon_vma? */
if (prev && !(prev->vm_flags & VM_GROWSDOWN) &&
(prev->vm_flags & (VM_WRITE|VM_READ|VM_EXEC))) {
if (address - prev->vm_end < stack_guard_gap)
return -ENOMEM;
}
/* We must make sure the anon_vma is allocated. */
if (unlikely(anon_vma_prepare(vma)))
return -ENOMEM;
/*
* vma->vm_start/vm_end cannot change under us because the caller
* is required to hold the mmap_sem in read mode. We need the
* anon_vma lock to serialize against concurrent expand_stacks.
*/
anon_vma_lock_write(vma->anon_vma);
/* Somebody else might have raced and expanded it already */
if (address < vma->vm_start) {
unsigned long size, grow;
size = vma->vm_end - address;
grow = (vma->vm_start - address) >> PAGE_SHIFT;
error = -ENOMEM;
if (grow <= vma->vm_pgoff) {
error = acct_stack_growth(vma, size, grow);
if (!error) {
/*
* vma_gap_update() doesn't support concurrent
* updates, but we only hold a shared mmap_sem
* lock here, so we need to protect against
* concurrent vma expansions.
* anon_vma_lock_write() doesn't help here, as
* we don't guarantee that all growable vmas
* in a mm share the same root anon vma.
* So, we reuse mm->page_table_lock to guard
* against concurrent vma expansions.
*/
spin_lock(&mm->page_table_lock);
if (vma->vm_flags & VM_LOCKED)
mm->locked_vm += grow;
vm_stat_account(mm, vma->vm_flags, grow);
anon_vma_interval_tree_pre_update_vma(vma);
vma->vm_start = address;
vma->vm_pgoff -= grow;
anon_vma_interval_tree_post_update_vma(vma);
vma_gap_update(vma);
spin_unlock(&mm->page_table_lock);
perf_event_mmap(vma);
}
}
}
anon_vma_unlock_write(vma->anon_vma);
khugepaged_enter_vma_merge(vma, vma->vm_flags);
validate_mm(mm);
return error;
} | {
"deleted": [
{
"line_no": 6,
"char_start": 147,
"char_end": 159,
"line": "\tint error;\n"
},
{
"line_no": 9,
"char_start": 183,
"char_end": 221,
"line": "\terror = security_mmap_addr(address);\n"
},
{
"line_no": 10,
"char_start": 221,
"char_end": 233,
"line": "\tif (error)\n"
},
{
"line_no": 11,
"char_start": 233,
"char_end": 249,
"line": "\t\treturn error;\n"
}
],
"added": [
{
"line_no": 6,
"char_start": 147,
"char_end": 163,
"line": "\tint error = 0;\n"
},
{
"line_no": 9,
"char_start": 187,
"char_end": 217,
"line": "\tif (address < mmap_min_addr)\n"
},
{
"line_no": 10,
"char_start": 217,
"char_end": 234,
"line": "\t\treturn -EPERM;\n"
}
]
} | {
"deleted": [
{
"char_start": 185,
"char_end": 189,
"chars": "rror"
},
{
"char_start": 190,
"char_end": 191,
"chars": "="
},
{
"char_start": 192,
"char_end": 201,
"chars": "security_"
},
{
"char_start": 210,
"char_end": 231,
"chars": "(address);\n\tif (error"
},
{
"char_start": 242,
"char_end": 247,
"chars": "error"
}
],
"added": [
{
"char_start": 157,
"char_end": 161,
"chars": " = 0"
},
{
"char_start": 188,
"char_end": 195,
"chars": "if (add"
},
{
"char_start": 196,
"char_end": 199,
"chars": "ess"
},
{
"char_start": 200,
"char_end": 201,
"chars": "<"
},
{
"char_start": 207,
"char_end": 211,
"chars": "min_"
},
{
"char_start": 226,
"char_end": 232,
"chars": "-EPERM"
}
]
} | github.com/torvalds/linux/commit/0a1d52994d440e21def1c2174932410b4f2a98a1 | mm/mmap.c | cwe-476 |
rfbHandleAuthResult | rfbHandleAuthResult(rfbClient* client)
{
uint32_t authResult=0, reasonLen=0;
char *reason=NULL;
if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;
authResult = rfbClientSwap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
rfbClientLog("VNC authentication succeeded\n");
return TRUE;
break;
case rfbVncAuthFailed:
if (client->major==3 && client->minor>7)
{
/* we have an error following */
if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE;
reasonLen = rfbClientSwap32IfLE(reasonLen);
reason = malloc((uint64_t)reasonLen+1);
if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; }
reason[reasonLen]=0;
rfbClientLog("VNC connection failed: %s\n",reason);
free(reason);
return FALSE;
}
rfbClientLog("VNC authentication failed\n");
return FALSE;
case rfbVncAuthTooMany:
rfbClientLog("VNC authentication failed - too many tries\n");
return FALSE;
}
rfbClientLog("Unknown VNC authentication result: %d\n",
(int)authResult);
return FALSE;
} | rfbHandleAuthResult(rfbClient* client)
{
uint32_t authResult=0;
if (!ReadFromRFBServer(client, (char *)&authResult, 4)) return FALSE;
authResult = rfbClientSwap32IfLE(authResult);
switch (authResult) {
case rfbVncAuthOK:
rfbClientLog("VNC authentication succeeded\n");
return TRUE;
break;
case rfbVncAuthFailed:
if (client->major==3 && client->minor>7)
{
/* we have an error following */
ReadReason(client);
return FALSE;
}
rfbClientLog("VNC authentication failed\n");
return FALSE;
case rfbVncAuthTooMany:
rfbClientLog("VNC authentication failed - too many tries\n");
return FALSE;
}
rfbClientLog("Unknown VNC authentication result: %d\n",
(int)authResult);
return FALSE;
} | {
"deleted": [
{
"line_no": 3,
"char_start": 41,
"char_end": 81,
"line": " uint32_t authResult=0, reasonLen=0;\n"
},
{
"line_no": 4,
"char_start": 81,
"char_end": 104,
"line": " char *reason=NULL;\n"
},
{
"line_no": 19,
"char_start": 489,
"char_end": 566,
"line": " if (!ReadFromRFBServer(client, (char *)&reasonLen, 4)) return FALSE;\n"
},
{
"line_no": 20,
"char_start": 566,
"char_end": 618,
"line": " reasonLen = rfbClientSwap32IfLE(reasonLen);\n"
},
{
"line_no": 21,
"char_start": 618,
"char_end": 666,
"line": " reason = malloc((uint64_t)reasonLen+1);\n"
},
{
"line_no": 22,
"char_start": 666,
"char_end": 757,
"line": " if (!ReadFromRFBServer(client, reason, reasonLen)) { free(reason); return FALSE; }\n"
},
{
"line_no": 23,
"char_start": 757,
"char_end": 786,
"line": " reason[reasonLen]=0;\n"
},
{
"line_no": 24,
"char_start": 786,
"char_end": 846,
"line": " rfbClientLog(\"VNC connection failed: %s\\n\",reason);\n"
},
{
"line_no": 25,
"char_start": 846,
"char_end": 868,
"line": " free(reason);\n"
}
],
"added": [
{
"line_no": 3,
"char_start": 41,
"char_end": 68,
"line": " uint32_t authResult=0;\n"
},
{
"line_no": 18,
"char_start": 453,
"char_end": 481,
"line": " ReadReason(client);\n"
}
]
} | {
"deleted": [
{
"char_start": 66,
"char_end": 102,
"chars": ", reasonLen=0;\n char *reason=NULL"
},
{
"char_start": 497,
"char_end": 502,
"chars": "if (!"
},
{
"char_start": 506,
"char_end": 510,
"chars": "From"
},
{
"char_start": 511,
"char_end": 538,
"chars": "FBServer(client, (char *)&r"
},
{
"char_start": 543,
"char_end": 696,
"chars": "Len, 4)) return FALSE;\n reasonLen = rfbClientSwap32IfLE(reasonLen);\n reason = malloc((uint64_t)reasonLen+1);\n if (!ReadFromRFBServer"
},
{
"char_start": 703,
"char_end": 865,
"chars": ", reason, reasonLen)) { free(reason); return FALSE; }\n reason[reasonLen]=0;\n rfbClientLog(\"VNC connection failed: %s\\n\",reason);\n free(reason"
}
],
"added": [
{
"char_start": 68,
"char_end": 68,
"chars": ""
}
]
} | github.com/LibVNC/libvncserver/commit/e34bcbb759ca5bef85809967a268fdf214c1ad2c | libvncclient/rfbproto.c | cwe-787 |
jbig2_image_compose | jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
uint32_t w, h;
uint32_t shift;
uint32_t leftbyte;
uint8_t *ss;
uint8_t *dd;
uint8_t leftmask, rightmask;
int early = x >= 0;
int late;
uint32_t bytewidth;
uint32_t syoffset = 0;
if (src == NULL)
return 0;
/* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */
/* Data is packed msb first within a byte, so with bits numbered: 01234567.
* Second byte is: 89abcdef. So to combine into a run, we use:
* (s[0]<<8) | s[1] == 0123456789abcdef.
* To read from src into dst at offset 3, we need to read:
* read: 0123456789abcdef...
* write: 0123456798abcdef...
* In general, to read from src and write into dst at offset x, we need to shift
* down by (x&7) bits to allow for bit alignment. So shift = x&7.
* So the 'central' part of our runs will see us doing:
* *d++ op= ((s[0]<<8)|s[1])>>shift;
* with special cases on the left and right edges of the run to mask.
* With the left hand edge, we have to be careful not to 'underread' the start of
* the src image; this is what the early flag is about. Similarly we have to be
* careful not to read off the right hand edge; this is what the late flag is for.
*/
/* clip */
w = src->width;
h = src->height;
shift = (x & 7);
ss = src->data - early;
if (x < 0) {
if (w < (uint32_t) -x)
w = 0;
else
w += x;
ss += (-x-1)>>3;
x = 0;
}
if (y < 0) {
if (h < (uint32_t) -y)
h = 0;
else
h += y;
syoffset = -y * src->stride;
y = 0;
}
if ((uint32_t)x + w > dst->width)
{
if (dst->width < (uint32_t)x)
w = 0;
else
w = dst->width - x;
}
if ((uint32_t)y + h > dst->height)
{
if (dst->height < (uint32_t)y)
h = 0;
else
h = dst->height - y;
}
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
leftbyte = (uint32_t) x >> 3;
dd = dst->data + y * dst->stride + leftbyte;
bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1;
leftmask = 255>>(x&7);
rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7));
if (bytewidth == 1)
leftmask &= rightmask;
late = (ss + bytewidth >= src->data + ((src->width+7)>>3));
ss += syoffset;
switch(op)
{
case JBIG2_COMPOSE_OR:
jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_AND:
jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_XOR:
jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_XNOR:
jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_REPLACE:
jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
}
return 0;
} | jbig2_image_compose(Jbig2Ctx *ctx, Jbig2Image *dst, Jbig2Image *src, int x, int y, Jbig2ComposeOp op)
{
uint32_t w, h;
uint32_t shift;
uint32_t leftbyte;
uint8_t *ss;
uint8_t *dd;
uint8_t leftmask, rightmask;
int early = x >= 0;
int late;
uint32_t bytewidth;
uint32_t syoffset = 0;
if (src == NULL)
return 0;
if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) ||
(UINT32_MAX - src->height < (y > 0 ? y : -y)))
{
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "overflow in compose_image");
#endif
return 0;
}
/* This code takes a src image and combines it onto dst at offset (x,y), with operation op. */
/* Data is packed msb first within a byte, so with bits numbered: 01234567.
* Second byte is: 89abcdef. So to combine into a run, we use:
* (s[0]<<8) | s[1] == 0123456789abcdef.
* To read from src into dst at offset 3, we need to read:
* read: 0123456789abcdef...
* write: 0123456798abcdef...
* In general, to read from src and write into dst at offset x, we need to shift
* down by (x&7) bits to allow for bit alignment. So shift = x&7.
* So the 'central' part of our runs will see us doing:
* *d++ op= ((s[0]<<8)|s[1])>>shift;
* with special cases on the left and right edges of the run to mask.
* With the left hand edge, we have to be careful not to 'underread' the start of
* the src image; this is what the early flag is about. Similarly we have to be
* careful not to read off the right hand edge; this is what the late flag is for.
*/
/* clip */
w = src->width;
h = src->height;
shift = (x & 7);
ss = src->data - early;
if (x < 0) {
if (w < (uint32_t) -x)
w = 0;
else
w += x;
ss += (-x-1)>>3;
x = 0;
}
if (y < 0) {
if (h < (uint32_t) -y)
h = 0;
else
h += y;
syoffset = -y * src->stride;
y = 0;
}
if ((uint32_t)x + w > dst->width)
{
if (dst->width < (uint32_t)x)
w = 0;
else
w = dst->width - x;
}
if ((uint32_t)y + h > dst->height)
{
if (dst->height < (uint32_t)y)
h = 0;
else
h = dst->height - y;
}
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "compositing %dx%d at (%d, %d) after clipping", w, h, x, y);
#endif
/* check for zero clipping region */
if ((w <= 0) || (h <= 0)) {
#ifdef JBIG2_DEBUG
jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, "zero clipping region");
#endif
return 0;
}
leftbyte = (uint32_t) x >> 3;
dd = dst->data + y * dst->stride + leftbyte;
bytewidth = (((uint32_t) x + w - 1) >> 3) - leftbyte + 1;
leftmask = 255>>(x&7);
rightmask = (((x+w)&7) == 0) ? 255 : ~(255>>((x+w)&7));
if (bytewidth == 1)
leftmask &= rightmask;
late = (ss + bytewidth >= src->data + ((src->width+7)>>3));
ss += syoffset;
switch(op)
{
case JBIG2_COMPOSE_OR:
jbig2_image_compose_opt_OR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_AND:
jbig2_image_compose_opt_AND(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_XOR:
jbig2_image_compose_opt_XOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_XNOR:
jbig2_image_compose_opt_XNOR(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
case JBIG2_COMPOSE_REPLACE:
jbig2_image_compose_opt_REPLACE(ss, dd, early, late, leftmask, rightmask, bytewidth, h, shift, dst->stride, src->stride);
break;
}
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 17,
"char_start": 363,
"char_end": 420,
"line": " if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) ||\n"
},
{
"line_no": 18,
"char_start": 420,
"char_end": 475,
"line": " (UINT32_MAX - src->height < (y > 0 ? y : -y)))\n"
},
{
"line_no": 19,
"char_start": 475,
"char_end": 481,
"line": " {\n"
},
{
"line_no": 21,
"char_start": 500,
"char_end": 581,
"line": " jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"overflow in compose_image\");\n"
},
{
"line_no": 23,
"char_start": 588,
"char_end": 606,
"line": " return 0;\n"
},
{
"line_no": 24,
"char_start": 606,
"char_end": 612,
"line": " }\n"
},
{
"line_no": 25,
"char_start": 612,
"char_end": 613,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 367,
"char_end": 617,
"chars": "if ((UINT32_MAX - src->width < (x > 0 ? x : -x)) ||\n (UINT32_MAX - src->height < (y > 0 ? y : -y)))\n {\n#ifdef JBIG2_DEBUG\n jbig2_error(ctx, JBIG2_SEVERITY_DEBUG, -1, \"overflow in compose_image\");\n#endif\n return 0;\n }\n\n "
}
]
} | github.com/ArtifexSoftware/jbig2dec/commit/0726320a4b55078e9d8deb590e477d598b3da66e | jbig2_image.c | cwe-787 |
next_state_class | next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
if (*state == CCS_RANGE)
return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;
if (*state == CCS_VALUE && *type != CCV_CLASS) {
if (*type == CCV_SB)
BITSET_SET_BIT(cc->bs, (int )(*vs));
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
}
*state = CCS_VALUE;
*type = CCV_CLASS;
return 0;
} | next_state_class(CClassNode* cc, OnigCodePoint* vs, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
if (*state == CCS_RANGE)
return ONIGERR_CHAR_CLASS_VALUE_AT_END_OF_RANGE;
if (*state == CCS_VALUE && *type != CCV_CLASS) {
if (*type == CCV_SB)
BITSET_SET_BIT(cc->bs, (int )(*vs));
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
}
if (*state != CCS_START)
*state = CCS_VALUE;
*type = CCV_CLASS;
return 0;
} | {
"deleted": [
{
"line_no": 18,
"char_start": 456,
"char_end": 478,
"line": " *state = CCS_VALUE;\n"
}
],
"added": [
{
"line_no": 18,
"char_start": 456,
"char_end": 483,
"line": " if (*state != CCS_START)\n"
},
{
"line_no": 19,
"char_start": 483,
"char_end": 507,
"line": " *state = CCS_VALUE;\n"
},
{
"line_no": 20,
"char_start": 507,
"char_end": 508,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 458,
"char_end": 487,
"chars": "if (*state != CCS_START)\n "
},
{
"char_start": 506,
"char_end": 507,
"chars": "\n"
}
]
} | github.com/kkos/oniguruma/commit/3b63d12038c8d8fc278e81c942fa9bec7c704c8b | src/regparse.c | cwe-787 |
mpol_parse_str | int mpol_parse_str(char *str, struct mempolicy **mpol)
{
struct mempolicy *new = NULL;
unsigned short mode_flags;
nodemask_t nodes;
char *nodelist = strchr(str, ':');
char *flags = strchr(str, '=');
int err = 1, mode;
if (flags)
*flags++ = '\0'; /* terminate mode string */
if (nodelist) {
/* NUL-terminate mode or flags string */
*nodelist++ = '\0';
if (nodelist_parse(nodelist, nodes))
goto out;
if (!nodes_subset(nodes, node_states[N_MEMORY]))
goto out;
} else
nodes_clear(nodes);
mode = match_string(policy_modes, MPOL_MAX, str);
if (mode < 0)
goto out;
switch (mode) {
case MPOL_PREFERRED:
/*
* Insist on a nodelist of one node only
*/
if (nodelist) {
char *rest = nodelist;
while (isdigit(*rest))
rest++;
if (*rest)
goto out;
}
break;
case MPOL_INTERLEAVE:
/*
* Default to online nodes with memory if no nodelist
*/
if (!nodelist)
nodes = node_states[N_MEMORY];
break;
case MPOL_LOCAL:
/*
* Don't allow a nodelist; mpol_new() checks flags
*/
if (nodelist)
goto out;
mode = MPOL_PREFERRED;
break;
case MPOL_DEFAULT:
/*
* Insist on a empty nodelist
*/
if (!nodelist)
err = 0;
goto out;
case MPOL_BIND:
/*
* Insist on a nodelist
*/
if (!nodelist)
goto out;
}
mode_flags = 0;
if (flags) {
/*
* Currently, we only support two mutually exclusive
* mode flags.
*/
if (!strcmp(flags, "static"))
mode_flags |= MPOL_F_STATIC_NODES;
else if (!strcmp(flags, "relative"))
mode_flags |= MPOL_F_RELATIVE_NODES;
else
goto out;
}
new = mpol_new(mode, mode_flags, &nodes);
if (IS_ERR(new))
goto out;
/*
* Save nodes for mpol_to_str() to show the tmpfs mount options
* for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
*/
if (mode != MPOL_PREFERRED)
new->v.nodes = nodes;
else if (nodelist)
new->v.preferred_node = first_node(nodes);
else
new->flags |= MPOL_F_LOCAL;
/*
* Save nodes for contextualization: this will be used to "clone"
* the mempolicy in a specific context [cpuset] at a later time.
*/
new->w.user_nodemask = nodes;
err = 0;
out:
/* Restore string for error message */
if (nodelist)
*--nodelist = ':';
if (flags)
*--flags = '=';
if (!err)
*mpol = new;
return err;
} | int mpol_parse_str(char *str, struct mempolicy **mpol)
{
struct mempolicy *new = NULL;
unsigned short mode_flags;
nodemask_t nodes;
char *nodelist = strchr(str, ':');
char *flags = strchr(str, '=');
int err = 1, mode;
if (flags)
*flags++ = '\0'; /* terminate mode string */
if (nodelist) {
/* NUL-terminate mode or flags string */
*nodelist++ = '\0';
if (nodelist_parse(nodelist, nodes))
goto out;
if (!nodes_subset(nodes, node_states[N_MEMORY]))
goto out;
} else
nodes_clear(nodes);
mode = match_string(policy_modes, MPOL_MAX, str);
if (mode < 0)
goto out;
switch (mode) {
case MPOL_PREFERRED:
/*
* Insist on a nodelist of one node only, although later
* we use first_node(nodes) to grab a single node, so here
* nodelist (or nodes) cannot be empty.
*/
if (nodelist) {
char *rest = nodelist;
while (isdigit(*rest))
rest++;
if (*rest)
goto out;
if (nodes_empty(nodes))
goto out;
}
break;
case MPOL_INTERLEAVE:
/*
* Default to online nodes with memory if no nodelist
*/
if (!nodelist)
nodes = node_states[N_MEMORY];
break;
case MPOL_LOCAL:
/*
* Don't allow a nodelist; mpol_new() checks flags
*/
if (nodelist)
goto out;
mode = MPOL_PREFERRED;
break;
case MPOL_DEFAULT:
/*
* Insist on a empty nodelist
*/
if (!nodelist)
err = 0;
goto out;
case MPOL_BIND:
/*
* Insist on a nodelist
*/
if (!nodelist)
goto out;
}
mode_flags = 0;
if (flags) {
/*
* Currently, we only support two mutually exclusive
* mode flags.
*/
if (!strcmp(flags, "static"))
mode_flags |= MPOL_F_STATIC_NODES;
else if (!strcmp(flags, "relative"))
mode_flags |= MPOL_F_RELATIVE_NODES;
else
goto out;
}
new = mpol_new(mode, mode_flags, &nodes);
if (IS_ERR(new))
goto out;
/*
* Save nodes for mpol_to_str() to show the tmpfs mount options
* for /proc/mounts, /proc/pid/mounts and /proc/pid/mountinfo.
*/
if (mode != MPOL_PREFERRED)
new->v.nodes = nodes;
else if (nodelist)
new->v.preferred_node = first_node(nodes);
else
new->flags |= MPOL_F_LOCAL;
/*
* Save nodes for contextualization: this will be used to "clone"
* the mempolicy in a specific context [cpuset] at a later time.
*/
new->w.user_nodemask = nodes;
err = 0;
out:
/* Restore string for error message */
if (nodelist)
*--nodelist = ':';
if (flags)
*--flags = '=';
if (!err)
*mpol = new;
return err;
} | {
"deleted": [
{
"line_no": 30,
"char_start": 637,
"char_end": 680,
"line": "\t\t * Insist on a nodelist of one node only\n"
}
],
"added": [
{
"line_no": 30,
"char_start": 637,
"char_end": 696,
"line": "\t\t * Insist on a nodelist of one node only, although later\n"
},
{
"line_no": 31,
"char_start": 696,
"char_end": 757,
"line": "\t\t * we use first_node(nodes) to grab a single node, so here\n"
},
{
"line_no": 32,
"char_start": 757,
"char_end": 799,
"line": "\t\t * nodelist (or nodes) cannot be empty.\n"
},
{
"line_no": 40,
"char_start": 915,
"char_end": 942,
"line": "\t\t\tif (nodes_empty(nodes))\n"
},
{
"line_no": 41,
"char_start": 942,
"char_end": 956,
"line": "\t\t\t\tgoto out;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 679,
"char_end": 798,
"chars": ", although later\n\t\t * we use first_node(nodes) to grab a single node, so here\n\t\t * nodelist (or nodes) cannot be empty."
},
{
"char_start": 899,
"char_end": 940,
"chars": ")\n\t\t\t\tgoto out;\n\t\t\tif (nodes_empty(nodes)"
}
]
} | github.com/torvalds/linux/commit/aa9f7d5172fac9bf1f09e678c35e287a40a7b7dd | mm/mempolicy.c | cwe-787 |
keycompare_mb | keycompare_mb (const struct line *a, const struct line *b)
{
struct keyfield *key = keylist;
/* For the first iteration only, the key positions have been
precomputed for us. */
char *texta = a->keybeg;
char *textb = b->keybeg;
char *lima = a->keylim;
char *limb = b->keylim;
size_t mblength_a, mblength_b;
wchar_t wc_a, wc_b;
mbstate_t state_a, state_b;
int diff = 0;
memset (&state_a, '\0', sizeof(mbstate_t));
memset (&state_b, '\0', sizeof(mbstate_t));
/* Ignore keys with start after end. */
if (a->keybeg - a->keylim > 0)
return 0;
/* Ignore and/or translate chars before comparing. */
# define IGNORE_CHARS(NEW_LEN, LEN, TEXT, COPY, WC, MBLENGTH, STATE) \
do \
{ \
wchar_t uwc; \
char mbc[MB_LEN_MAX]; \
mbstate_t state_wc; \
\
for (NEW_LEN = i = 0; i < LEN;) \
{ \
mbstate_t state_bak; \
\
state_bak = STATE; \
MBLENGTH = mbrtowc (&WC, TEXT + i, LEN - i, &STATE); \
\
if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1 \
|| MBLENGTH == 0) \
{ \
if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1) \
STATE = state_bak; \
if (!ignore) \
COPY[NEW_LEN++] = TEXT[i]; \
i++; \
continue; \
} \
\
if (ignore) \
{ \
if ((ignore == nonprinting && !iswprint (WC)) \
|| (ignore == nondictionary \
&& !iswalnum (WC) && !iswblank (WC))) \
{ \
i += MBLENGTH; \
continue; \
} \
} \
\
if (translate) \
{ \
\
uwc = towupper(WC); \
if (WC == uwc) \
{ \
memcpy (mbc, TEXT + i, MBLENGTH); \
i += MBLENGTH; \
} \
else \
{ \
i += MBLENGTH; \
WC = uwc; \
memset (&state_wc, '\0', sizeof (mbstate_t)); \
\
MBLENGTH = wcrtomb (mbc, WC, &state_wc); \
assert (MBLENGTH != (size_t)-1 && MBLENGTH != 0); \
} \
\
for (j = 0; j < MBLENGTH; j++) \
COPY[NEW_LEN++] = mbc[j]; \
} \
else \
for (j = 0; j < MBLENGTH; j++) \
COPY[NEW_LEN++] = TEXT[i++]; \
} \
COPY[NEW_LEN] = '\0'; \
} \
while (0)
/* Actually compare the fields. */
for (;;)
{
/* Find the lengths. */
size_t lena = lima <= texta ? 0 : lima - texta;
size_t lenb = limb <= textb ? 0 : limb - textb;
char enda IF_LINT (= 0);
char endb IF_LINT (= 0);
char const *translate = key->translate;
bool const *ignore = key->ignore;
if (ignore || translate)
{
char *copy_a = (char *) xmalloc (lena + 1 + lenb + 1);
char *copy_b = copy_a + lena + 1;
size_t new_len_a, new_len_b;
size_t i, j;
IGNORE_CHARS (new_len_a, lena, texta, copy_a,
wc_a, mblength_a, state_a);
IGNORE_CHARS (new_len_b, lenb, textb, copy_b,
wc_b, mblength_b, state_b);
texta = copy_a; textb = copy_b;
lena = new_len_a; lenb = new_len_b;
}
else
{
/* Use the keys in-place, temporarily null-terminated. */
enda = texta[lena]; texta[lena] = '\0';
endb = textb[lenb]; textb[lenb] = '\0';
}
if (key->random)
diff = compare_random (texta, lena, textb, lenb);
else if (key->numeric | key->general_numeric | key->human_numeric)
{
char savea = *lima, saveb = *limb;
*lima = *limb = '\0';
diff = (key->numeric ? numcompare (texta, textb)
: key->general_numeric ? general_numcompare (texta, textb)
: human_numcompare (texta, textb));
*lima = savea, *limb = saveb;
}
else if (key->version)
diff = filevercmp (texta, textb);
else if (key->month)
diff = getmonth (texta, lena, NULL) - getmonth (textb, lenb, NULL);
else if (lena == 0)
diff = - NONZERO (lenb);
else if (lenb == 0)
diff = 1;
else if (hard_LC_COLLATE && !folding)
{
diff = xmemcoll0 (texta, lena + 1, textb, lenb + 1);
}
else
{
diff = memcmp (texta, textb, MIN (lena, lenb));
if (diff == 0)
diff = lena < lenb ? -1 : lena != lenb;
}
if (ignore || translate)
free (texta);
else
{
texta[lena] = enda;
textb[lenb] = endb;
}
if (diff)
goto not_equal;
key = key->next;
if (! key)
break;
/* Find the beginning and limit of the next field. */
if (key->eword != -1)
lima = limfield (a, key), limb = limfield (b, key);
else
lima = a->text + a->length - 1, limb = b->text + b->length - 1;
if (key->sword != -1)
texta = begfield (a, key), textb = begfield (b, key);
else
{
texta = a->text, textb = b->text;
if (key->skipsblanks)
{
while (texta < lima && ismbblank (texta, lima - texta, &mblength_a))
texta += mblength_a;
while (textb < limb && ismbblank (textb, limb - textb, &mblength_b))
textb += mblength_b;
}
}
}
not_equal:
if (key && key->reverse)
return -diff;
else
return diff;
} | keycompare_mb (const struct line *a, const struct line *b)
{
struct keyfield *key = keylist;
/* For the first iteration only, the key positions have been
precomputed for us. */
char *texta = a->keybeg;
char *textb = b->keybeg;
char *lima = a->keylim;
char *limb = b->keylim;
size_t mblength_a, mblength_b;
wchar_t wc_a, wc_b;
mbstate_t state_a, state_b;
int diff = 0;
memset (&state_a, '\0', sizeof(mbstate_t));
memset (&state_b, '\0', sizeof(mbstate_t));
/* Ignore keys with start after end. */
if (a->keybeg - a->keylim > 0)
return 0;
/* Ignore and/or translate chars before comparing. */
# define IGNORE_CHARS(NEW_LEN, LEN, TEXT, COPY, WC, MBLENGTH, STATE) \
do \
{ \
wchar_t uwc; \
char mbc[MB_LEN_MAX]; \
mbstate_t state_wc; \
\
for (NEW_LEN = i = 0; i < LEN;) \
{ \
mbstate_t state_bak; \
\
state_bak = STATE; \
MBLENGTH = mbrtowc (&WC, TEXT + i, LEN - i, &STATE); \
\
if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1 \
|| MBLENGTH == 0) \
{ \
if (MBLENGTH == (size_t)-2 || MBLENGTH == (size_t)-1) \
STATE = state_bak; \
if (!ignore) \
COPY[NEW_LEN++] = TEXT[i]; \
i++; \
continue; \
} \
\
if (ignore) \
{ \
if ((ignore == nonprinting && !iswprint (WC)) \
|| (ignore == nondictionary \
&& !iswalnum (WC) && !iswblank (WC))) \
{ \
i += MBLENGTH; \
continue; \
} \
} \
\
if (translate) \
{ \
\
uwc = towupper(WC); \
if (WC == uwc) \
{ \
memcpy (mbc, TEXT + i, MBLENGTH); \
i += MBLENGTH; \
} \
else \
{ \
i += MBLENGTH; \
WC = uwc; \
memset (&state_wc, '\0', sizeof (mbstate_t)); \
\
MBLENGTH = wcrtomb (mbc, WC, &state_wc); \
assert (MBLENGTH != (size_t)-1 && MBLENGTH != 0); \
} \
\
for (j = 0; j < MBLENGTH; j++) \
COPY[NEW_LEN++] = mbc[j]; \
} \
else \
for (j = 0; j < MBLENGTH; j++) \
COPY[NEW_LEN++] = TEXT[i++]; \
} \
COPY[NEW_LEN] = '\0'; \
} \
while (0)
/* Actually compare the fields. */
for (;;)
{
/* Find the lengths. */
size_t lena = lima <= texta ? 0 : lima - texta;
size_t lenb = limb <= textb ? 0 : limb - textb;
char enda IF_LINT (= 0);
char endb IF_LINT (= 0);
char const *translate = key->translate;
bool const *ignore = key->ignore;
if (ignore || translate)
{
if (SIZE_MAX - lenb - 2 < lena)
xalloc_die ();
char *copy_a = (char *) xnmalloc (lena + lenb + 2, MB_CUR_MAX);
char *copy_b = copy_a + lena * MB_CUR_MAX + 1;
size_t new_len_a, new_len_b;
size_t i, j;
IGNORE_CHARS (new_len_a, lena, texta, copy_a,
wc_a, mblength_a, state_a);
IGNORE_CHARS (new_len_b, lenb, textb, copy_b,
wc_b, mblength_b, state_b);
texta = copy_a; textb = copy_b;
lena = new_len_a; lenb = new_len_b;
}
else
{
/* Use the keys in-place, temporarily null-terminated. */
enda = texta[lena]; texta[lena] = '\0';
endb = textb[lenb]; textb[lenb] = '\0';
}
if (key->random)
diff = compare_random (texta, lena, textb, lenb);
else if (key->numeric | key->general_numeric | key->human_numeric)
{
char savea = *lima, saveb = *limb;
*lima = *limb = '\0';
diff = (key->numeric ? numcompare (texta, textb)
: key->general_numeric ? general_numcompare (texta, textb)
: human_numcompare (texta, textb));
*lima = savea, *limb = saveb;
}
else if (key->version)
diff = filevercmp (texta, textb);
else if (key->month)
diff = getmonth (texta, lena, NULL) - getmonth (textb, lenb, NULL);
else if (lena == 0)
diff = - NONZERO (lenb);
else if (lenb == 0)
diff = 1;
else if (hard_LC_COLLATE && !folding)
{
diff = xmemcoll0 (texta, lena + 1, textb, lenb + 1);
}
else
{
diff = memcmp (texta, textb, MIN (lena, lenb));
if (diff == 0)
diff = lena < lenb ? -1 : lena != lenb;
}
if (ignore || translate)
free (texta);
else
{
texta[lena] = enda;
textb[lenb] = endb;
}
if (diff)
goto not_equal;
key = key->next;
if (! key)
break;
/* Find the beginning and limit of the next field. */
if (key->eword != -1)
lima = limfield (a, key), limb = limfield (b, key);
else
lima = a->text + a->length - 1, limb = b->text + b->length - 1;
if (key->sword != -1)
texta = begfield (a, key), textb = begfield (b, key);
else
{
texta = a->text, textb = b->text;
if (key->skipsblanks)
{
while (texta < lima && ismbblank (texta, lima - texta, &mblength_a))
texta += mblength_a;
while (textb < limb && ismbblank (textb, limb - textb, &mblength_b))
textb += mblength_b;
}
}
}
not_equal:
if (key && key->reverse)
return -diff;
else
return diff;
} | {
"deleted": [
{
"line_no": 108,
"char_start": 5967,
"char_end": 6032,
"line": " char *copy_a = (char *) xmalloc (lena + 1 + lenb + 1);\n"
},
{
"line_no": 109,
"char_start": 6032,
"char_end": 6076,
"line": " char *copy_b = copy_a + lena + 1;\n"
}
],
"added": [
{
"line_no": 108,
"char_start": 5967,
"char_end": 6009,
"line": " if (SIZE_MAX - lenb - 2 < lena)\n"
},
{
"line_no": 109,
"char_start": 6009,
"char_end": 6036,
"line": " xalloc_die ();\n"
},
{
"line_no": 110,
"char_start": 6036,
"char_end": 6110,
"line": " char *copy_a = (char *) xnmalloc (lena + lenb + 2, MB_CUR_MAX);\n"
},
{
"line_no": 111,
"char_start": 6110,
"char_end": 6167,
"line": " char *copy_b = copy_a + lena * MB_CUR_MAX + 1;\n"
}
]
} | {
"deleted": [
{
"char_start": 6017,
"char_end": 6021,
"chars": "1 + "
},
{
"char_start": 6028,
"char_end": 6029,
"chars": "1"
}
],
"added": [
{
"char_start": 5977,
"char_end": 6046,
"chars": "if (SIZE_MAX - lenb - 2 < lena)\n xalloc_die ();\n "
},
{
"char_start": 6071,
"char_end": 6072,
"chars": "n"
},
{
"char_start": 6094,
"char_end": 6107,
"chars": "2, MB_CUR_MAX"
},
{
"char_start": 6148,
"char_end": 6161,
"chars": " * MB_CUR_MAX"
}
]
} | github.com/pixelb/coreutils/commit/bea5e36cc876ed627bb5e0eca36fdfaa6465e940 | src/sort.c | cwe-787 |
next_state_val | next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v,
int* vs_israw, int v_israw,
enum CCVALTYPE intype, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
switch (*state) {
case CCS_VALUE:
if (*type == CCV_SB) {
BITSET_SET_BIT(cc->bs, (int )(*vs));
}
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
break;
case CCS_RANGE:
if (intype == *type) {
if (intype == CCV_SB) {
if (*vs > 0xff || v > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )v);
}
else {
r = add_code_range(&(cc->mbuf), env, *vs, v);
if (r < 0) return r;
}
}
else {
#if 0
if (intype == CCV_CODE_POINT && *type == CCV_SB) {
#endif
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff));
r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v);
if (r < 0) return r;
#if 0
}
else
return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE;
#endif
}
ccs_range_end:
*state = CCS_COMPLETE;
break;
case CCS_COMPLETE:
case CCS_START:
*state = CCS_VALUE;
break;
default:
break;
}
*vs_israw = v_israw;
*vs = v;
*type = intype;
return 0;
} | next_state_val(CClassNode* cc, OnigCodePoint *vs, OnigCodePoint v,
int* vs_israw, int v_israw,
enum CCVALTYPE intype, enum CCVALTYPE* type,
enum CCSTATE* state, ScanEnv* env)
{
int r;
switch (*state) {
case CCS_VALUE:
if (*type == CCV_SB) {
if (*vs > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
BITSET_SET_BIT(cc->bs, (int )(*vs));
}
else if (*type == CCV_CODE_POINT) {
r = add_code_range(&(cc->mbuf), env, *vs, *vs);
if (r < 0) return r;
}
break;
case CCS_RANGE:
if (intype == *type) {
if (intype == CCV_SB) {
if (*vs > 0xff || v > 0xff)
return ONIGERR_INVALID_CODE_POINT_VALUE;
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )v);
}
else {
r = add_code_range(&(cc->mbuf), env, *vs, v);
if (r < 0) return r;
}
}
else {
#if 0
if (intype == CCV_CODE_POINT && *type == CCV_SB) {
#endif
if (*vs > v) {
if (IS_SYNTAX_BV(env->syntax, ONIG_SYN_ALLOW_EMPTY_RANGE_IN_CC))
goto ccs_range_end;
else
return ONIGERR_EMPTY_RANGE_IN_CHAR_CLASS;
}
bitset_set_range(cc->bs, (int )*vs, (int )(v < 0xff ? v : 0xff));
r = add_code_range(&(cc->mbuf), env, (OnigCodePoint )*vs, v);
if (r < 0) return r;
#if 0
}
else
return ONIGERR_MISMATCH_CODE_LENGTH_IN_CLASS_RANGE;
#endif
}
ccs_range_end:
*state = CCS_COMPLETE;
break;
case CCS_COMPLETE:
case CCS_START:
*state = CCS_VALUE;
break;
default:
break;
}
*vs_israw = v_israw;
*vs = v;
*type = intype;
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 11,
"char_start": 276,
"char_end": 298,
"line": " if (*vs > 0xff)\n"
},
{
"line_no": 12,
"char_start": 298,
"char_end": 349,
"line": " return ONIGERR_INVALID_CODE_POINT_VALUE;\n"
},
{
"line_no": 13,
"char_start": 349,
"char_end": 350,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 282,
"char_end": 356,
"chars": "if (*vs > 0xff)\n return ONIGERR_INVALID_CODE_POINT_VALUE;\n\n "
}
]
} | github.com/kkos/oniguruma/commit/b4bf968ad52afe14e60a2dc8a95d3555c543353a | src/regparse.c | cwe-787 |
cbs_jpeg_split_fragment | static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,
CodedBitstreamFragment *frag,
int header)
{
AVBufferRef *data_ref;
uint8_t *data;
size_t data_size;
int unit, start, end, marker, next_start, next_marker;
int err, i, j, length;
if (frag->data_size < 4) {
// Definitely too short to be meaningful.
return AVERROR_INVALIDDATA;
}
for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);
if (i > 0) {
av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at "
"beginning of image.\n", i);
}
for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size && frag->data[i]) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"no SOI marker found.\n");
return AVERROR_INVALIDDATA;
}
marker = frag->data[i];
if (marker != JPEG_MARKER_SOI) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first "
"marker is %02x, should be SOI.\n", marker);
return AVERROR_INVALIDDATA;
}
for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"no image content found.\n");
return AVERROR_INVALIDDATA;
}
marker = frag->data[i];
start = i + 1;
for (unit = 0;; unit++) {
if (marker == JPEG_MARKER_EOI) {
break;
} else if (marker == JPEG_MARKER_SOS) {
for (i = start; i + 1 < frag->data_size; i++) {
if (frag->data[i] != 0xff)
continue;
end = i;
for (++i; i + 1 < frag->data_size &&
frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
next_marker = -1;
} else {
if (frag->data[i] == 0x00)
continue;
next_marker = frag->data[i];
next_start = i + 1;
}
break;
}
} else {
i = start;
if (i + 2 > frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"truncated at %02x marker.\n", marker);
return AVERROR_INVALIDDATA;
}
length = AV_RB16(frag->data + i);
if (i + length > frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"truncated at %02x marker segment.\n", marker);
return AVERROR_INVALIDDATA;
}
end = start + length;
i = end;
if (frag->data[i] != 0xff) {
next_marker = -1;
} else {
for (++i; i + 1 < frag->data_size &&
frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
next_marker = -1;
} else {
next_marker = frag->data[i];
next_start = i + 1;
}
}
}
if (marker == JPEG_MARKER_SOS) {
length = AV_RB16(frag->data + start);
data_ref = NULL;
data = av_malloc(end - start +
AV_INPUT_BUFFER_PADDING_SIZE);
if (!data)
return AVERROR(ENOMEM);
memcpy(data, frag->data + start, length);
for (i = start + length, j = length; i < end; i++, j++) {
if (frag->data[i] == 0xff) {
while (frag->data[i] == 0xff)
++i;
data[j] = 0xff;
} else {
data[j] = frag->data[i];
}
}
data_size = j;
memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
} else {
data = frag->data + start;
data_size = end - start;
data_ref = frag->data_ref;
}
err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,
data, data_size, data_ref);
if (err < 0)
return err;
if (next_marker == -1)
break;
marker = next_marker;
start = next_start;
}
return 0;
} | static int cbs_jpeg_split_fragment(CodedBitstreamContext *ctx,
CodedBitstreamFragment *frag,
int header)
{
AVBufferRef *data_ref;
uint8_t *data;
size_t data_size;
int unit, start, end, marker, next_start, next_marker;
int err, i, j, length;
if (frag->data_size < 4) {
// Definitely too short to be meaningful.
return AVERROR_INVALIDDATA;
}
for (i = 0; i + 1 < frag->data_size && frag->data[i] != 0xff; i++);
if (i > 0) {
av_log(ctx->log_ctx, AV_LOG_WARNING, "Discarding %d bytes at "
"beginning of image.\n", i);
}
for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size && frag->data[i]) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"no SOI marker found.\n");
return AVERROR_INVALIDDATA;
}
marker = frag->data[i];
if (marker != JPEG_MARKER_SOI) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: first "
"marker is %02x, should be SOI.\n", marker);
return AVERROR_INVALIDDATA;
}
for (++i; i + 1 < frag->data_size && frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"no image content found.\n");
return AVERROR_INVALIDDATA;
}
marker = frag->data[i];
start = i + 1;
for (unit = 0;; unit++) {
if (marker == JPEG_MARKER_EOI) {
break;
} else if (marker == JPEG_MARKER_SOS) {
for (i = start; i + 1 < frag->data_size; i++) {
if (frag->data[i] != 0xff)
continue;
end = i;
for (++i; i + 1 < frag->data_size &&
frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
next_marker = -1;
} else {
if (frag->data[i] == 0x00)
continue;
next_marker = frag->data[i];
next_start = i + 1;
}
break;
}
} else {
i = start;
if (i + 2 > frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"truncated at %02x marker.\n", marker);
return AVERROR_INVALIDDATA;
}
length = AV_RB16(frag->data + i);
if (i + length > frag->data_size) {
av_log(ctx->log_ctx, AV_LOG_ERROR, "Invalid JPEG image: "
"truncated at %02x marker segment.\n", marker);
return AVERROR_INVALIDDATA;
}
end = start + length;
i = end;
if (frag->data[i] != 0xff) {
next_marker = -1;
} else {
for (++i; i + 1 < frag->data_size &&
frag->data[i] == 0xff; i++);
if (i + 1 >= frag->data_size) {
next_marker = -1;
} else {
next_marker = frag->data[i];
next_start = i + 1;
}
}
}
if (marker == JPEG_MARKER_SOS) {
length = AV_RB16(frag->data + start);
if (length > end - start)
return AVERROR_INVALIDDATA;
data_ref = NULL;
data = av_malloc(end - start +
AV_INPUT_BUFFER_PADDING_SIZE);
if (!data)
return AVERROR(ENOMEM);
memcpy(data, frag->data + start, length);
for (i = start + length, j = length; i < end; i++, j++) {
if (frag->data[i] == 0xff) {
while (frag->data[i] == 0xff)
++i;
data[j] = 0xff;
} else {
data[j] = frag->data[i];
}
}
data_size = j;
memset(data + data_size, 0, AV_INPUT_BUFFER_PADDING_SIZE);
} else {
data = frag->data + start;
data_size = end - start;
data_ref = frag->data_ref;
}
err = ff_cbs_insert_unit_data(ctx, frag, unit, marker,
data, data_size, data_ref);
if (err < 0)
return err;
if (next_marker == -1)
break;
marker = next_marker;
start = next_start;
}
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 95,
"char_start": 3398,
"char_end": 3436,
"line": " if (length > end - start)\n"
},
{
"line_no": 96,
"char_start": 3436,
"char_end": 3480,
"line": " return AVERROR_INVALIDDATA;\n"
},
{
"line_no": 97,
"char_start": 3480,
"char_end": 3481,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 3410,
"char_end": 3493,
"chars": "if (length > end - start)\n return AVERROR_INVALIDDATA;\n\n "
}
]
} | github.com/FFmpeg/FFmpeg/commit/1812352d767ccf5431aa440123e2e260a4db2726 | libavcodec/cbs_jpeg.c | cwe-787 |
avcodec_align_dimensions2 | void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
int linesize_align[AV_NUM_DATA_POINTERS])
{
int i;
int w_align = 1;
int h_align = 1;
AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);
if (desc) {
w_align = 1 << desc->log2_chroma_w;
h_align = 1 << desc->log2_chroma_h;
}
switch (s->pix_fmt) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUYV422:
case AV_PIX_FMT_YVYU422:
case AV_PIX_FMT_UYVY422:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV440P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_GBRP:
case AV_PIX_FMT_GBRAP:
case AV_PIX_FMT_GRAY8:
case AV_PIX_FMT_GRAY16BE:
case AV_PIX_FMT_GRAY16LE:
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUVJ440P:
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUVA420P:
case AV_PIX_FMT_YUVA422P:
case AV_PIX_FMT_YUVA444P:
case AV_PIX_FMT_YUV420P9LE:
case AV_PIX_FMT_YUV420P9BE:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV420P10BE:
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV420P12BE:
case AV_PIX_FMT_YUV420P14LE:
case AV_PIX_FMT_YUV420P14BE:
case AV_PIX_FMT_YUV420P16LE:
case AV_PIX_FMT_YUV420P16BE:
case AV_PIX_FMT_YUVA420P9LE:
case AV_PIX_FMT_YUVA420P9BE:
case AV_PIX_FMT_YUVA420P10LE:
case AV_PIX_FMT_YUVA420P10BE:
case AV_PIX_FMT_YUVA420P16LE:
case AV_PIX_FMT_YUVA420P16BE:
case AV_PIX_FMT_YUV422P9LE:
case AV_PIX_FMT_YUV422P9BE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV422P10BE:
case AV_PIX_FMT_YUV422P12LE:
case AV_PIX_FMT_YUV422P12BE:
case AV_PIX_FMT_YUV422P14LE:
case AV_PIX_FMT_YUV422P14BE:
case AV_PIX_FMT_YUV422P16LE:
case AV_PIX_FMT_YUV422P16BE:
case AV_PIX_FMT_YUVA422P9LE:
case AV_PIX_FMT_YUVA422P9BE:
case AV_PIX_FMT_YUVA422P10LE:
case AV_PIX_FMT_YUVA422P10BE:
case AV_PIX_FMT_YUVA422P16LE:
case AV_PIX_FMT_YUVA422P16BE:
case AV_PIX_FMT_YUV440P10LE:
case AV_PIX_FMT_YUV440P10BE:
case AV_PIX_FMT_YUV440P12LE:
case AV_PIX_FMT_YUV440P12BE:
case AV_PIX_FMT_YUV444P9LE:
case AV_PIX_FMT_YUV444P9BE:
case AV_PIX_FMT_YUV444P10LE:
case AV_PIX_FMT_YUV444P10BE:
case AV_PIX_FMT_YUV444P12LE:
case AV_PIX_FMT_YUV444P12BE:
case AV_PIX_FMT_YUV444P14LE:
case AV_PIX_FMT_YUV444P14BE:
case AV_PIX_FMT_YUV444P16LE:
case AV_PIX_FMT_YUV444P16BE:
case AV_PIX_FMT_YUVA444P9LE:
case AV_PIX_FMT_YUVA444P9BE:
case AV_PIX_FMT_YUVA444P10LE:
case AV_PIX_FMT_YUVA444P10BE:
case AV_PIX_FMT_YUVA444P16LE:
case AV_PIX_FMT_YUVA444P16BE:
case AV_PIX_FMT_GBRP9LE:
case AV_PIX_FMT_GBRP9BE:
case AV_PIX_FMT_GBRP10LE:
case AV_PIX_FMT_GBRP10BE:
case AV_PIX_FMT_GBRP12LE:
case AV_PIX_FMT_GBRP12BE:
case AV_PIX_FMT_GBRP14LE:
case AV_PIX_FMT_GBRP14BE:
case AV_PIX_FMT_GBRP16LE:
case AV_PIX_FMT_GBRP16BE:
case AV_PIX_FMT_GBRAP12LE:
case AV_PIX_FMT_GBRAP12BE:
case AV_PIX_FMT_GBRAP16LE:
case AV_PIX_FMT_GBRAP16BE:
w_align = 16; //FIXME assume 16 pixel per macroblock
h_align = 16 * 2; // interlaced needs 2 macroblocks height
break;
case AV_PIX_FMT_YUV411P:
case AV_PIX_FMT_YUVJ411P:
case AV_PIX_FMT_UYYVYY411:
w_align = 32;
h_align = 16 * 2;
break;
case AV_PIX_FMT_YUV410P:
if (s->codec_id == AV_CODEC_ID_SVQ1) {
w_align = 64;
h_align = 64;
}
break;
case AV_PIX_FMT_RGB555:
if (s->codec_id == AV_CODEC_ID_RPZA) {
w_align = 4;
h_align = 4;
}
break;
case AV_PIX_FMT_PAL8:
case AV_PIX_FMT_BGR8:
case AV_PIX_FMT_RGB8:
if (s->codec_id == AV_CODEC_ID_SMC ||
s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
if (s->codec_id == AV_CODEC_ID_JV) {
w_align = 8;
h_align = 8;
}
break;
case AV_PIX_FMT_BGR24:
if ((s->codec_id == AV_CODEC_ID_MSZH) ||
(s->codec_id == AV_CODEC_ID_ZLIB)) {
w_align = 4;
h_align = 4;
}
break;
case AV_PIX_FMT_RGB24:
if (s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
break;
default:
break;
}
if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {
w_align = FFMAX(w_align, 8);
}
*width = FFALIGN(*width, w_align);
*height = FFALIGN(*height, h_align);
if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {
// some of the optimized chroma MC reads one line too much
// which is also done in mpeg decoders with lowres > 0
*height += 2;
// H.264 uses edge emulation for out of frame motion vectors, for this
// it requires a temporary area large enough to hold a 21x21 block,
// increasing witdth ensure that the temporary area is large enough,
// the next rounded up width is 32
*width = FFMAX(*width, 32);
}
for (i = 0; i < 4; i++)
linesize_align[i] = STRIDE_ALIGN;
} | void avcodec_align_dimensions2(AVCodecContext *s, int *width, int *height,
int linesize_align[AV_NUM_DATA_POINTERS])
{
int i;
int w_align = 1;
int h_align = 1;
AVPixFmtDescriptor const *desc = av_pix_fmt_desc_get(s->pix_fmt);
if (desc) {
w_align = 1 << desc->log2_chroma_w;
h_align = 1 << desc->log2_chroma_h;
}
switch (s->pix_fmt) {
case AV_PIX_FMT_YUV420P:
case AV_PIX_FMT_YUYV422:
case AV_PIX_FMT_YVYU422:
case AV_PIX_FMT_UYVY422:
case AV_PIX_FMT_YUV422P:
case AV_PIX_FMT_YUV440P:
case AV_PIX_FMT_YUV444P:
case AV_PIX_FMT_GBRP:
case AV_PIX_FMT_GBRAP:
case AV_PIX_FMT_GRAY8:
case AV_PIX_FMT_GRAY16BE:
case AV_PIX_FMT_GRAY16LE:
case AV_PIX_FMT_YUVJ420P:
case AV_PIX_FMT_YUVJ422P:
case AV_PIX_FMT_YUVJ440P:
case AV_PIX_FMT_YUVJ444P:
case AV_PIX_FMT_YUVA420P:
case AV_PIX_FMT_YUVA422P:
case AV_PIX_FMT_YUVA444P:
case AV_PIX_FMT_YUV420P9LE:
case AV_PIX_FMT_YUV420P9BE:
case AV_PIX_FMT_YUV420P10LE:
case AV_PIX_FMT_YUV420P10BE:
case AV_PIX_FMT_YUV420P12LE:
case AV_PIX_FMT_YUV420P12BE:
case AV_PIX_FMT_YUV420P14LE:
case AV_PIX_FMT_YUV420P14BE:
case AV_PIX_FMT_YUV420P16LE:
case AV_PIX_FMT_YUV420P16BE:
case AV_PIX_FMT_YUVA420P9LE:
case AV_PIX_FMT_YUVA420P9BE:
case AV_PIX_FMT_YUVA420P10LE:
case AV_PIX_FMT_YUVA420P10BE:
case AV_PIX_FMT_YUVA420P16LE:
case AV_PIX_FMT_YUVA420P16BE:
case AV_PIX_FMT_YUV422P9LE:
case AV_PIX_FMT_YUV422P9BE:
case AV_PIX_FMT_YUV422P10LE:
case AV_PIX_FMT_YUV422P10BE:
case AV_PIX_FMT_YUV422P12LE:
case AV_PIX_FMT_YUV422P12BE:
case AV_PIX_FMT_YUV422P14LE:
case AV_PIX_FMT_YUV422P14BE:
case AV_PIX_FMT_YUV422P16LE:
case AV_PIX_FMT_YUV422P16BE:
case AV_PIX_FMT_YUVA422P9LE:
case AV_PIX_FMT_YUVA422P9BE:
case AV_PIX_FMT_YUVA422P10LE:
case AV_PIX_FMT_YUVA422P10BE:
case AV_PIX_FMT_YUVA422P16LE:
case AV_PIX_FMT_YUVA422P16BE:
case AV_PIX_FMT_YUV440P10LE:
case AV_PIX_FMT_YUV440P10BE:
case AV_PIX_FMT_YUV440P12LE:
case AV_PIX_FMT_YUV440P12BE:
case AV_PIX_FMT_YUV444P9LE:
case AV_PIX_FMT_YUV444P9BE:
case AV_PIX_FMT_YUV444P10LE:
case AV_PIX_FMT_YUV444P10BE:
case AV_PIX_FMT_YUV444P12LE:
case AV_PIX_FMT_YUV444P12BE:
case AV_PIX_FMT_YUV444P14LE:
case AV_PIX_FMT_YUV444P14BE:
case AV_PIX_FMT_YUV444P16LE:
case AV_PIX_FMT_YUV444P16BE:
case AV_PIX_FMT_YUVA444P9LE:
case AV_PIX_FMT_YUVA444P9BE:
case AV_PIX_FMT_YUVA444P10LE:
case AV_PIX_FMT_YUVA444P10BE:
case AV_PIX_FMT_YUVA444P16LE:
case AV_PIX_FMT_YUVA444P16BE:
case AV_PIX_FMT_GBRP9LE:
case AV_PIX_FMT_GBRP9BE:
case AV_PIX_FMT_GBRP10LE:
case AV_PIX_FMT_GBRP10BE:
case AV_PIX_FMT_GBRP12LE:
case AV_PIX_FMT_GBRP12BE:
case AV_PIX_FMT_GBRP14LE:
case AV_PIX_FMT_GBRP14BE:
case AV_PIX_FMT_GBRP16LE:
case AV_PIX_FMT_GBRP16BE:
case AV_PIX_FMT_GBRAP12LE:
case AV_PIX_FMT_GBRAP12BE:
case AV_PIX_FMT_GBRAP16LE:
case AV_PIX_FMT_GBRAP16BE:
w_align = 16; //FIXME assume 16 pixel per macroblock
h_align = 16 * 2; // interlaced needs 2 macroblocks height
break;
case AV_PIX_FMT_YUV411P:
case AV_PIX_FMT_YUVJ411P:
case AV_PIX_FMT_UYYVYY411:
w_align = 32;
h_align = 16 * 2;
break;
case AV_PIX_FMT_YUV410P:
if (s->codec_id == AV_CODEC_ID_SVQ1) {
w_align = 64;
h_align = 64;
}
break;
case AV_PIX_FMT_RGB555:
if (s->codec_id == AV_CODEC_ID_RPZA) {
w_align = 4;
h_align = 4;
}
if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
w_align = 8;
h_align = 8;
}
break;
case AV_PIX_FMT_PAL8:
case AV_PIX_FMT_BGR8:
case AV_PIX_FMT_RGB8:
if (s->codec_id == AV_CODEC_ID_SMC ||
s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
if (s->codec_id == AV_CODEC_ID_JV ||
s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {
w_align = 8;
h_align = 8;
}
break;
case AV_PIX_FMT_BGR24:
if ((s->codec_id == AV_CODEC_ID_MSZH) ||
(s->codec_id == AV_CODEC_ID_ZLIB)) {
w_align = 4;
h_align = 4;
}
break;
case AV_PIX_FMT_RGB24:
if (s->codec_id == AV_CODEC_ID_CINEPAK) {
w_align = 4;
h_align = 4;
}
break;
default:
break;
}
if (s->codec_id == AV_CODEC_ID_IFF_ILBM) {
w_align = FFMAX(w_align, 8);
}
*width = FFALIGN(*width, w_align);
*height = FFALIGN(*height, h_align);
if (s->codec_id == AV_CODEC_ID_H264 || s->lowres) {
// some of the optimized chroma MC reads one line too much
// which is also done in mpeg decoders with lowres > 0
*height += 2;
// H.264 uses edge emulation for out of frame motion vectors, for this
// it requires a temporary area large enough to hold a 21x21 block,
// increasing witdth ensure that the temporary area is large enough,
// the next rounded up width is 32
*width = FFMAX(*width, 32);
}
for (i = 0; i < 4; i++)
linesize_align[i] = STRIDE_ALIGN;
} | {
"deleted": [
{
"line_no": 129,
"char_start": 3941,
"char_end": 3986,
"line": " if (s->codec_id == AV_CODEC_ID_JV) {\n"
}
],
"added": [
{
"line_no": 120,
"char_start": 3692,
"char_end": 3750,
"line": " if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n"
},
{
"line_no": 121,
"char_start": 3750,
"char_end": 3775,
"line": " w_align = 8;\n"
},
{
"line_no": 122,
"char_start": 3775,
"char_end": 3800,
"line": " h_align = 8;\n"
},
{
"line_no": 123,
"char_start": 3800,
"char_end": 3810,
"line": " }\n"
},
{
"line_no": 133,
"char_start": 4059,
"char_end": 4104,
"line": " if (s->codec_id == AV_CODEC_ID_JV ||\n"
},
{
"line_no": 134,
"char_start": 4104,
"char_end": 4162,
"line": " s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 3700,
"char_end": 3818,
"chars": "if (s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO) {\n w_align = 8;\n h_align = 8;\n }\n "
},
{
"char_start": 4100,
"char_end": 4158,
"chars": " ||\n s->codec_id == AV_CODEC_ID_INTERPLAY_VIDEO"
}
]
} | github.com/FFmpeg/FFmpeg/commit/2080bc33717955a0e4268e738acf8c1eeddbf8cb | libavcodec/utils.c | cwe-787 |
ContentLine_Analyzer::DoDeliverOnce | int ContentLine_Analyzer::DoDeliverOnce(int len, const u_char* data)
{
const u_char* data_start = data;
if ( len <= 0 )
return 0;
for ( ; len > 0; --len, ++data )
{
if ( offset >= buf_len )
InitBuffer(buf_len * 2);
int c = data[0];
#define EMIT_LINE \
{ \
buf[offset] = '\0'; \
int seq_len = data + 1 - data_start; \
seq_delivered_in_lines = seq + seq_len; \
last_char = c; \
ForwardStream(offset, buf, IsOrig()); \
offset = 0; \
return seq_len; \
}
switch ( c ) {
case '\r':
// Look ahead for '\n'.
if ( len > 1 && data[1] == '\n' )
{
--len; ++data;
last_char = c;
c = data[0];
EMIT_LINE
}
else if ( CR_LF_as_EOL & CR_as_EOL )
EMIT_LINE
else
buf[offset++] = c;
break;
case '\n':
if ( last_char == '\r' )
{
--offset; // remove '\r'
EMIT_LINE
}
else if ( CR_LF_as_EOL & LF_as_EOL )
EMIT_LINE
else
{
if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_LF) )
Conn()->Weird("line_terminated_with_single_LF");
buf[offset++] = c;
}
break;
case '\0':
if ( flag_NULs )
CheckNUL();
else
buf[offset++] = c;
break;
default:
buf[offset++] = c;
break;
}
if ( last_char == '\r' )
if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_CR) )
Conn()->Weird("line_terminated_with_single_CR");
last_char = c;
}
return data - data_start;
} | int ContentLine_Analyzer::DoDeliverOnce(int len, const u_char* data)
{
const u_char* data_start = data;
if ( len <= 0 )
return 0;
for ( ; len > 0; --len, ++data )
{
if ( offset >= buf_len )
InitBuffer(buf_len * 2);
int c = data[0];
#define EMIT_LINE \
{ \
buf[offset] = '\0'; \
int seq_len = data + 1 - data_start; \
seq_delivered_in_lines = seq + seq_len; \
last_char = c; \
ForwardStream(offset, buf, IsOrig()); \
offset = 0; \
return seq_len; \
}
switch ( c ) {
case '\r':
// Look ahead for '\n'.
if ( len > 1 && data[1] == '\n' )
{
--len; ++data;
last_char = c;
c = data[0];
EMIT_LINE
}
else if ( CR_LF_as_EOL & CR_as_EOL )
EMIT_LINE
else
buf[offset++] = c;
break;
case '\n':
if ( last_char == '\r' )
{
// Weird corner-case:
// this can happen if we see a \r at the end of a packet where crlf is
// set to CR_as_EOL | LF_as_EOL, with the packet causing crlf to be set to
// 0 and the next packet beginning with a \n. In this case we just swallow
// the character and re-set last_char.
if ( offset == 0 )
{
last_char = c;
break;
}
--offset; // remove '\r'
EMIT_LINE
}
else if ( CR_LF_as_EOL & LF_as_EOL )
EMIT_LINE
else
{
if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_LF) )
Conn()->Weird("line_terminated_with_single_LF");
buf[offset++] = c;
}
break;
case '\0':
if ( flag_NULs )
CheckNUL();
else
buf[offset++] = c;
break;
default:
buf[offset++] = c;
break;
}
if ( last_char == '\r' )
if ( ! suppress_weirds && Conn()->FlagEvent(SINGULAR_CR) )
Conn()->Weird("line_terminated_with_single_CR");
last_char = c;
}
return data - data_start;
} | {
"deleted": [],
"added": [
{
"line_no": 52,
"char_start": 1101,
"char_end": 1124,
"line": "\t\t\t\tif ( offset == 0 )\n"
},
{
"line_no": 53,
"char_start": 1124,
"char_end": 1131,
"line": "\t\t\t\t\t{\n"
},
{
"line_no": 54,
"char_start": 1131,
"char_end": 1151,
"line": "\t\t\t\t\tlast_char = c;\n"
},
{
"line_no": 55,
"char_start": 1151,
"char_end": 1163,
"line": "\t\t\t\t\tbreak;\n"
},
{
"line_no": 56,
"char_start": 1163,
"char_end": 1170,
"line": "\t\t\t\t\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 803,
"char_end": 1174,
"chars": "// Weird corner-case:\n\t\t\t\t// this can happen if we see a \\r at the end of a packet where crlf is\n\t\t\t\t// set to CR_as_EOL | LF_as_EOL, with the packet causing crlf to be set to\n\t\t\t\t// 0 and the next packet beginning with a \\n. In this case we just swallow\n\t\t\t\t// the character and re-set last_char.\n\t\t\t\tif ( offset == 0 )\n\t\t\t\t\t{\n\t\t\t\t\tlast_char = c;\n\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t"
}
]
} | github.com/bro/bro/commit/6c0f101a62489b1c5927b4ed63b0e1d37db40282 | src/analyzer/protocol/tcp/ContentLine.cc | cwe-787 |
idn2_to_ascii_4i | idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)
{
uint32_t *input_u32;
uint8_t *input_u8, *output_u8;
size_t length;
int rc;
if (!input)
{
if (output)
*output = 0;
return IDN2_OK;
}
input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));
if (!input_u32)
return IDN2_MALLOC;
u32_cpy (input_u32, input, inlen);
input_u32[inlen] = 0;
input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);
free (input_u32);
if (!input_u8)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
rc = idn2_lookup_u8 (input_u8, &output_u8, flags);
free (input_u8);
if (rc == IDN2_OK)
{
/* wow, this is ugly, but libidn manpage states:
* char * out output zero terminated string that must have room for at
* least 63 characters plus the terminating zero.
*/
if (output)
strcpy (output, (const char *) output_u8);
free(output_u8);
}
return rc;
} | idn2_to_ascii_4i (const uint32_t * input, size_t inlen, char * output, int flags)
{
uint32_t *input_u32;
uint8_t *input_u8, *output_u8;
size_t length;
int rc;
if (!input)
{
if (output)
*output = 0;
return IDN2_OK;
}
input_u32 = (uint32_t *) malloc ((inlen + 1) * sizeof(uint32_t));
if (!input_u32)
return IDN2_MALLOC;
u32_cpy (input_u32, input, inlen);
input_u32[inlen] = 0;
input_u8 = u32_to_u8 (input_u32, inlen + 1, NULL, &length);
free (input_u32);
if (!input_u8)
{
if (errno == ENOMEM)
return IDN2_MALLOC;
return IDN2_ENCODING_ERROR;
}
rc = idn2_lookup_u8 (input_u8, &output_u8, flags);
free (input_u8);
if (rc == IDN2_OK)
{
/* wow, this is ugly, but libidn manpage states:
* char * out output zero terminated string that must have room for at
* least 63 characters plus the terminating zero.
*/
size_t len = strlen ((char *) output_u8);
if (len > 63)
{
free (output_u8);
return IDN2_TOO_BIG_DOMAIN;
}
if (output)
strcpy (output, (char *) output_u8);
free (output_u8);
}
return rc;
} | {
"deleted": [
{
"line_no": 41,
"char_start": 933,
"char_end": 977,
"line": "\tstrcpy (output, (const char *) output_u8);\n"
},
{
"line_no": 43,
"char_start": 978,
"char_end": 1001,
"line": " free(output_u8);\n"
}
],
"added": [
{
"line_no": 40,
"char_start": 915,
"char_end": 963,
"line": " size_t len = strlen ((char *) output_u8);\n"
},
{
"line_no": 41,
"char_start": 963,
"char_end": 964,
"line": "\n"
},
{
"line_no": 42,
"char_start": 964,
"char_end": 984,
"line": " if (len > 63)\n"
},
{
"line_no": 43,
"char_start": 984,
"char_end": 994,
"line": " {\n"
},
{
"line_no": 44,
"char_start": 994,
"char_end": 1015,
"line": "\t free (output_u8);\n"
},
{
"line_no": 45,
"char_start": 1015,
"char_end": 1046,
"line": "\t return IDN2_TOO_BIG_DOMAIN;\n"
},
{
"line_no": 46,
"char_start": 1046,
"char_end": 1056,
"line": " }\n"
},
{
"line_no": 47,
"char_start": 1056,
"char_end": 1057,
"line": "\n"
},
{
"line_no": 49,
"char_start": 1075,
"char_end": 1113,
"line": "\tstrcpy (output, (char *) output_u8);\n"
},
{
"line_no": 51,
"char_start": 1114,
"char_end": 1138,
"line": " free (output_u8);\n"
}
]
} | {
"deleted": [
{
"char_start": 951,
"char_end": 957,
"chars": "const "
}
],
"added": [
{
"char_start": 921,
"char_end": 1063,
"chars": "size_t len = strlen ((char *) output_u8);\n\n if (len > 63)\n {\n\t free (output_u8);\n\t return IDN2_TOO_BIG_DOMAIN;\n }\n\n "
},
{
"char_start": 1124,
"char_end": 1125,
"chars": " "
}
]
} | github.com/libidn/libidn2/commit/e4d1558aa2c1c04a05066ee8600f37603890ba8c | lib/lookup.c | cwe-787 |
blosc_c | static int blosc_c(struct thread_context* thread_context, int32_t bsize,
int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes,
const uint8_t* src, const int32_t offset, uint8_t* dest,
uint8_t* tmp, uint8_t* tmp2) {
blosc2_context* context = thread_context->parent_context;
int dont_split = (context->header_flags & 0x10) >> 4;
int dict_training = context->use_dict && context->dict_cdict == NULL;
int32_t j, neblock, nstreams;
int32_t cbytes; /* number of compressed bytes in split */
int32_t ctbytes = 0; /* number of compressed bytes in block */
int64_t maxout;
int32_t typesize = context->typesize;
const char* compname;
int accel;
const uint8_t* _src;
uint8_t *_tmp = tmp, *_tmp2 = tmp2;
uint8_t *_tmp3 = thread_context->tmp4;
int last_filter_index = last_filter(context->filters, 'c');
bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED;
if (last_filter_index >= 0 || context->prefilter != NULL) {
/* Apply the filter pipeline just for the prefilter */
if (memcpyed && context->prefilter != NULL) {
// We only need the prefilter output
_src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3);
if (_src == NULL) {
return -9; // signals a problem with the filter pipeline
}
return bsize;
}
/* Apply regular filter pipeline */
_src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3);
if (_src == NULL) {
return -9; // signals a problem with the filter pipeline
}
} else {
_src = src + offset;
}
assert(context->clevel > 0);
/* Calculate acceleration for different compressors */
accel = get_accel(context);
/* The number of compressed data streams for this block */
if (!dont_split && !leftoverblock && !dict_training) {
nstreams = (int32_t)typesize;
}
else {
nstreams = 1;
}
neblock = bsize / nstreams;
for (j = 0; j < nstreams; j++) {
if (!dict_training) {
dest += sizeof(int32_t);
ntbytes += sizeof(int32_t);
ctbytes += sizeof(int32_t);
}
// See if we have a run here
const uint8_t* ip = (uint8_t*)_src + j * neblock;
const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock;
if (get_run(ip, ipbound)) {
// A run. Encode the repeated byte as a negative length in the length of the split.
int32_t value = _src[j * neblock];
_sw32(dest - 4, -value);
continue;
}
maxout = neblock;
#if defined(HAVE_SNAPPY)
if (context->compcode == BLOSC_SNAPPY) {
maxout = (int32_t)snappy_max_compressed_length((size_t)neblock);
}
#endif /* HAVE_SNAPPY */
if (ntbytes + maxout > maxbytes) {
/* avoid buffer * overrun */
maxout = (int64_t)maxbytes - (int64_t)ntbytes;
if (maxout <= 0) {
return 0; /* non-compressible block */
}
}
if (dict_training) {
// We are in the build dict state, so don't compress
// TODO: copy only a percentage for sampling
memcpy(dest, _src + j * neblock, (unsigned int)neblock);
cbytes = (int32_t)neblock;
}
else if (context->compcode == BLOSC_BLOSCLZ) {
cbytes = blosclz_compress(context->clevel, _src + j * neblock,
(int)neblock, dest, (int)maxout);
}
#if defined(HAVE_LZ4)
else if (context->compcode == BLOSC_LZ4) {
void *hash_table = NULL;
#ifdef HAVE_IPP
hash_table = (void*)thread_context->lz4_hash_table;
#endif
cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, accel, hash_table);
}
else if (context->compcode == BLOSC_LZ4HC) {
cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_LZ4 */
#if defined(HAVE_LIZARD)
else if (context->compcode == BLOSC_LIZARD) {
cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, accel);
}
#endif /* HAVE_LIZARD */
#if defined(HAVE_SNAPPY)
else if (context->compcode == BLOSC_SNAPPY) {
cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout);
}
#endif /* HAVE_SNAPPY */
#if defined(HAVE_ZLIB)
else if (context->compcode == BLOSC_ZLIB) {
cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_ZLIB */
#if defined(HAVE_ZSTD)
else if (context->compcode == BLOSC_ZSTD) {
cbytes = zstd_wrap_compress(thread_context,
(char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_ZSTD */
else {
blosc_compcode_to_compname(context->compcode, &compname);
fprintf(stderr, "Blosc has not been compiled with '%s' ", compname);
fprintf(stderr, "compression support. Please use one having it.");
return -5; /* signals no compression support */
}
if (cbytes > maxout) {
/* Buffer overrun caused by compression (should never happen) */
return -1;
}
if (cbytes < 0) {
/* cbytes should never be negative */
return -2;
}
if (!dict_training) {
if (cbytes == 0 || cbytes == neblock) {
/* The compressor has been unable to compress data at all. */
/* Before doing the copy, check that we are not running into a
buffer overflow. */
if ((ntbytes + neblock) > maxbytes) {
return 0; /* Non-compressible data */
}
memcpy(dest, _src + j * neblock, (unsigned int)neblock);
cbytes = neblock;
}
_sw32(dest - 4, cbytes);
}
dest += cbytes;
ntbytes += cbytes;
ctbytes += cbytes;
} /* Closes j < nstreams */
//printf("c%d", ctbytes);
return ctbytes;
} | static int blosc_c(struct thread_context* thread_context, int32_t bsize,
int32_t leftoverblock, int32_t ntbytes, int32_t destsize,
const uint8_t* src, const int32_t offset, uint8_t* dest,
uint8_t* tmp, uint8_t* tmp2) {
blosc2_context* context = thread_context->parent_context;
int dont_split = (context->header_flags & 0x10) >> 4;
int dict_training = context->use_dict && context->dict_cdict == NULL;
int32_t j, neblock, nstreams;
int32_t cbytes; /* number of compressed bytes in split */
int32_t ctbytes = 0; /* number of compressed bytes in block */
int64_t maxout;
int32_t typesize = context->typesize;
const char* compname;
int accel;
const uint8_t* _src;
uint8_t *_tmp = tmp, *_tmp2 = tmp2;
uint8_t *_tmp3 = thread_context->tmp4;
int last_filter_index = last_filter(context->filters, 'c');
bool memcpyed = context->header_flags & (uint8_t)BLOSC_MEMCPYED;
if (last_filter_index >= 0 || context->prefilter != NULL) {
/* Apply the filter pipeline just for the prefilter */
if (memcpyed && context->prefilter != NULL) {
// We only need the prefilter output
_src = pipeline_c(thread_context, bsize, src, offset, dest, _tmp2, _tmp3);
if (_src == NULL) {
return -9; // signals a problem with the filter pipeline
}
return bsize;
}
/* Apply regular filter pipeline */
_src = pipeline_c(thread_context, bsize, src, offset, _tmp, _tmp2, _tmp3);
if (_src == NULL) {
return -9; // signals a problem with the filter pipeline
}
} else {
_src = src + offset;
}
assert(context->clevel > 0);
/* Calculate acceleration for different compressors */
accel = get_accel(context);
/* The number of compressed data streams for this block */
if (!dont_split && !leftoverblock && !dict_training) {
nstreams = (int32_t)typesize;
}
else {
nstreams = 1;
}
neblock = bsize / nstreams;
for (j = 0; j < nstreams; j++) {
if (!dict_training) {
dest += sizeof(int32_t);
ntbytes += sizeof(int32_t);
ctbytes += sizeof(int32_t);
}
// See if we have a run here
const uint8_t* ip = (uint8_t*)_src + j * neblock;
const uint8_t* ipbound = (uint8_t*)_src + (j + 1) * neblock;
if (get_run(ip, ipbound)) {
// A run. Encode the repeated byte as a negative length in the length of the split.
int32_t value = _src[j * neblock];
if (ntbytes > destsize) {
/* Not enough space to write out compressed block size */
return -1;
}
_sw32(dest - 4, -value);
continue;
}
maxout = neblock;
#if defined(HAVE_SNAPPY)
if (context->compcode == BLOSC_SNAPPY) {
maxout = (int32_t)snappy_max_compressed_length((size_t)neblock);
}
#endif /* HAVE_SNAPPY */
if (ntbytes + maxout > destsize) {
/* avoid buffer * overrun */
maxout = (int64_t)destsize - (int64_t)ntbytes;
if (maxout <= 0) {
return 0; /* non-compressible block */
}
}
if (dict_training) {
// We are in the build dict state, so don't compress
// TODO: copy only a percentage for sampling
memcpy(dest, _src + j * neblock, (unsigned int)neblock);
cbytes = (int32_t)neblock;
}
else if (context->compcode == BLOSC_BLOSCLZ) {
cbytes = blosclz_compress(context->clevel, _src + j * neblock,
(int)neblock, dest, (int)maxout);
}
#if defined(HAVE_LZ4)
else if (context->compcode == BLOSC_LZ4) {
void *hash_table = NULL;
#ifdef HAVE_IPP
hash_table = (void*)thread_context->lz4_hash_table;
#endif
cbytes = lz4_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, accel, hash_table);
}
else if (context->compcode == BLOSC_LZ4HC) {
cbytes = lz4hc_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_LZ4 */
#if defined(HAVE_LIZARD)
else if (context->compcode == BLOSC_LIZARD) {
cbytes = lizard_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, accel);
}
#endif /* HAVE_LIZARD */
#if defined(HAVE_SNAPPY)
else if (context->compcode == BLOSC_SNAPPY) {
cbytes = snappy_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout);
}
#endif /* HAVE_SNAPPY */
#if defined(HAVE_ZLIB)
else if (context->compcode == BLOSC_ZLIB) {
cbytes = zlib_wrap_compress((char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_ZLIB */
#if defined(HAVE_ZSTD)
else if (context->compcode == BLOSC_ZSTD) {
cbytes = zstd_wrap_compress(thread_context,
(char*)_src + j * neblock, (size_t)neblock,
(char*)dest, (size_t)maxout, context->clevel);
}
#endif /* HAVE_ZSTD */
else {
blosc_compcode_to_compname(context->compcode, &compname);
fprintf(stderr, "Blosc has not been compiled with '%s' ", compname);
fprintf(stderr, "compression support. Please use one having it.");
return -5; /* signals no compression support */
}
if (cbytes > maxout) {
/* Buffer overrun caused by compression (should never happen) */
return -1;
}
if (cbytes < 0) {
/* cbytes should never be negative */
return -2;
}
if (!dict_training) {
if (cbytes == 0 || cbytes == neblock) {
/* The compressor has been unable to compress data at all. */
/* Before doing the copy, check that we are not running into a
buffer overflow. */
if ((ntbytes + neblock) > destsize) {
return 0; /* Non-compressible data */
}
memcpy(dest, _src + j * neblock, (unsigned int)neblock);
cbytes = neblock;
}
_sw32(dest - 4, cbytes);
}
dest += cbytes;
ntbytes += cbytes;
ctbytes += cbytes;
} /* Closes j < nstreams */
//printf("c%d", ctbytes);
return ctbytes;
} | {
"deleted": [
{
"line_no": 2,
"char_start": 73,
"char_end": 150,
"line": " int32_t leftoverblock, int32_t ntbytes, int32_t maxbytes,\n"
},
{
"line_no": 78,
"char_start": 2729,
"char_end": 2768,
"line": " if (ntbytes + maxout > maxbytes) {\n"
},
{
"line_no": 80,
"char_start": 2803,
"char_end": 2856,
"line": " maxout = (int64_t)maxbytes - (int64_t)ntbytes;\n"
},
{
"line_no": 155,
"char_start": 5822,
"char_end": 5868,
"line": " if ((ntbytes + neblock) > maxbytes) {\n"
}
],
"added": [
{
"line_no": 2,
"char_start": 73,
"char_end": 150,
"line": " int32_t leftoverblock, int32_t ntbytes, int32_t destsize,\n"
},
{
"line_no": 68,
"char_start": 2476,
"char_end": 2508,
"line": " if (ntbytes > destsize) {\n"
},
{
"line_no": 69,
"char_start": 2508,
"char_end": 2574,
"line": " /* Not enough space to write out compressed block size */\n"
},
{
"line_no": 70,
"char_start": 2574,
"char_end": 2593,
"line": " return -1;\n"
},
{
"line_no": 71,
"char_start": 2593,
"char_end": 2601,
"line": " }\n"
},
{
"line_no": 82,
"char_start": 2854,
"char_end": 2893,
"line": " if (ntbytes + maxout > destsize) {\n"
},
{
"line_no": 84,
"char_start": 2928,
"char_end": 2981,
"line": " maxout = (int64_t)destsize - (int64_t)ntbytes;\n"
},
{
"line_no": 159,
"char_start": 5947,
"char_end": 5993,
"line": " if ((ntbytes + neblock) > destsize) {\n"
}
]
} | {
"deleted": [
{
"char_start": 140,
"char_end": 146,
"chars": "maxbyt"
},
{
"char_start": 2756,
"char_end": 2762,
"chars": "maxbyt"
},
{
"char_start": 2827,
"char_end": 2833,
"chars": "maxbyt"
},
{
"char_start": 5856,
"char_end": 5862,
"chars": "maxbyt"
}
],
"added": [
{
"char_start": 140,
"char_end": 143,
"chars": "des"
},
{
"char_start": 144,
"char_end": 147,
"chars": "siz"
},
{
"char_start": 2482,
"char_end": 2607,
"chars": "if (ntbytes > destsize) {\n /* Not enough space to write out compressed block size */\n return -1;\n }\n "
},
{
"char_start": 2881,
"char_end": 2884,
"chars": "des"
},
{
"char_start": 2885,
"char_end": 2888,
"chars": "siz"
},
{
"char_start": 2952,
"char_end": 2955,
"chars": "des"
},
{
"char_start": 2956,
"char_end": 2959,
"chars": "siz"
},
{
"char_start": 5981,
"char_end": 5984,
"chars": "des"
},
{
"char_start": 5985,
"char_end": 5988,
"chars": "siz"
}
]
} | github.com/Blosc/c-blosc2/commit/c4c6470e88210afc95262c8b9fcc27e30ca043ee | blosc/blosc2.c | cwe-787 |
re2c::Scanner::fill | bool Scanner::fill(size_t need)
{
if (eof) return false;
pop_finished_files();
DASSERT(bot <= tok && tok <= lim);
size_t free = static_cast<size_t>(tok - bot);
size_t copy = static_cast<size_t>(lim - tok);
if (free >= need) {
memmove(bot, tok, copy);
shift_ptrs_and_fpos(-static_cast<ptrdiff_t>(free));
}
else {
BSIZE += std::max(BSIZE, need);
char * buf = new char[BSIZE + YYMAXFILL];
if (!buf) fatal("out of memory");
memmove(buf, tok, copy);
shift_ptrs_and_fpos(buf - bot);
delete [] bot;
bot = buf;
free = BSIZE - copy;
}
if (!read(free)) {
eof = lim;
memset(lim, 0, YYMAXFILL);
lim += YYMAXFILL;
}
return true;
} | bool Scanner::fill(size_t need)
{
if (eof) return false;
pop_finished_files();
DASSERT(bot <= tok && tok <= lim);
size_t free = static_cast<size_t>(tok - bot);
size_t copy = static_cast<size_t>(lim - tok);
if (free >= need) {
memmove(bot, tok, copy);
shift_ptrs_and_fpos(-static_cast<ptrdiff_t>(free));
}
else {
BSIZE += std::max(BSIZE, need);
char * buf = new char[BSIZE + YYMAXFILL];
if (!buf) fatal("out of memory");
memmove(buf, tok, copy);
shift_ptrs_and_fpos(buf - tok);
delete [] bot;
bot = buf;
free = BSIZE - copy;
}
DASSERT(lim + free <= bot + BSIZE);
if (!read(free)) {
eof = lim;
memset(lim, 0, YYMAXFILL);
lim += YYMAXFILL;
}
return true;
} | {
"deleted": [
{
"line_no": 21,
"char_start": 529,
"char_end": 569,
"line": " shift_ptrs_and_fpos(buf - bot);\n"
}
],
"added": [
{
"line_no": 21,
"char_start": 529,
"char_end": 569,
"line": " shift_ptrs_and_fpos(buf - tok);\n"
},
{
"line_no": 28,
"char_start": 648,
"char_end": 688,
"line": " DASSERT(lim + free <= bot + BSIZE);\n"
}
]
} | {
"deleted": [
{
"char_start": 563,
"char_end": 565,
"chars": "bo"
}
],
"added": [
{
"char_start": 563,
"char_end": 564,
"chars": "t"
},
{
"char_start": 565,
"char_end": 566,
"chars": "k"
},
{
"char_start": 647,
"char_end": 687,
"chars": "\n DASSERT(lim + free <= bot + BSIZE);"
}
]
} | github.com/skvadrik/re2c/commit/c4603ba5ce229db83a2a4fb93e6d4b4e3ec3776a | src/parse/scanner.cc | cwe-787 |
input_csi_dispatch_sgr_colon | input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i)
{
struct grid_cell *gc = &ictx->cell.cell;
char *s = ictx->param_list[i].str, *copy, *ptr, *out;
int p[8];
u_int n;
const char *errstr;
for (n = 0; n < nitems(p); n++)
p[n] = -1;
n = 0;
ptr = copy = xstrdup(s);
while ((out = strsep(&ptr, ":")) != NULL) {
if (*out != '\0') {
p[n++] = strtonum(out, 0, INT_MAX, &errstr);
if (errstr != NULL || n == nitems(p)) {
free(copy);
return;
}
} else
n++;
log_debug("%s: %u = %d", __func__, n - 1, p[n - 1]);
}
free(copy);
if (n == 0)
return;
if (p[0] == 4) {
if (n != 2)
return;
switch (p[1]) {
case 0:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
break;
case 1:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE;
break;
case 2:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_2;
break;
case 3:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_3;
break;
case 4:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_4;
break;
case 5:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_5;
break;
}
return;
}
if (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58))
return;
switch (p[1]) {
case 2:
if (n < 3)
break;
if (n == 5)
i = 2;
else
i = 3;
if (n < i + 3)
break;
input_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1],
p[i + 2]);
break;
case 5:
if (n < 3)
break;
input_csi_dispatch_sgr_256_do(ictx, p[0], p[2]);
break;
}
} | input_csi_dispatch_sgr_colon(struct input_ctx *ictx, u_int i)
{
struct grid_cell *gc = &ictx->cell.cell;
char *s = ictx->param_list[i].str, *copy, *ptr, *out;
int p[8];
u_int n;
const char *errstr;
for (n = 0; n < nitems(p); n++)
p[n] = -1;
n = 0;
ptr = copy = xstrdup(s);
while ((out = strsep(&ptr, ":")) != NULL) {
if (*out != '\0') {
p[n++] = strtonum(out, 0, INT_MAX, &errstr);
if (errstr != NULL || n == nitems(p)) {
free(copy);
return;
}
} else {
n++;
if (n == nitems(p)) {
free(copy);
return;
}
}
log_debug("%s: %u = %d", __func__, n - 1, p[n - 1]);
}
free(copy);
if (n == 0)
return;
if (p[0] == 4) {
if (n != 2)
return;
switch (p[1]) {
case 0:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
break;
case 1:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE;
break;
case 2:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_2;
break;
case 3:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_3;
break;
case 4:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_4;
break;
case 5:
gc->attr &= ~GRID_ATTR_ALL_UNDERSCORE;
gc->attr |= GRID_ATTR_UNDERSCORE_5;
break;
}
return;
}
if (n < 2 || (p[0] != 38 && p[0] != 48 && p[0] != 58))
return;
switch (p[1]) {
case 2:
if (n < 3)
break;
if (n == 5)
i = 2;
else
i = 3;
if (n < i + 3)
break;
input_csi_dispatch_sgr_rgb_do(ictx, p[0], p[i], p[i + 1],
p[i + 2]);
break;
case 5:
if (n < 3)
break;
input_csi_dispatch_sgr_256_do(ictx, p[0], p[2]);
break;
}
} | {
"deleted": [
{
"line_no": 21,
"char_start": 485,
"char_end": 494,
"line": "\t\t} else\n"
}
],
"added": [
{
"line_no": 21,
"char_start": 485,
"char_end": 496,
"line": "\t\t} else {\n"
},
{
"line_no": 23,
"char_start": 504,
"char_end": 529,
"line": "\t\t\tif (n == nitems(p)) {\n"
},
{
"line_no": 24,
"char_start": 529,
"char_end": 545,
"line": "\t\t\t\tfree(copy);\n"
},
{
"line_no": 25,
"char_start": 545,
"char_end": 557,
"line": "\t\t\t\treturn;\n"
},
{
"line_no": 26,
"char_start": 557,
"char_end": 562,
"line": "\t\t\t}\n"
},
{
"line_no": 27,
"char_start": 562,
"char_end": 566,
"line": "\t\t}\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 493,
"char_end": 495,
"chars": " {"
},
{
"char_start": 503,
"char_end": 565,
"chars": "\n\t\t\tif (n == nitems(p)) {\n\t\t\t\tfree(copy);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}"
}
]
} | github.com/tmux/tmux/commit/a868bacb46e3c900530bed47a1c6f85b0fbe701c | input.c | cwe-787 |
enl_ipc_get | char *enl_ipc_get(const char *msg_data)
{
static char *message = NULL;
static unsigned short len = 0;
char buff[13], *ret_msg = NULL;
register unsigned char i;
unsigned char blen;
if (msg_data == IPC_TIMEOUT) {
return(IPC_TIMEOUT);
}
for (i = 0; i < 12; i++) {
buff[i] = msg_data[i];
}
buff[12] = 0;
blen = strlen(buff);
if (message != NULL) {
len += blen;
message = (char *) erealloc(message, len + 1);
strcat(message, buff);
} else {
len = blen;
message = (char *) emalloc(len + 1);
strcpy(message, buff);
}
if (blen < 12) {
ret_msg = message;
message = NULL;
D(("Received complete reply: \"%s\"\n", ret_msg));
}
return(ret_msg);
} | char *enl_ipc_get(const char *msg_data)
{
static char *message = NULL;
static size_t len = 0;
char buff[13], *ret_msg = NULL;
register unsigned char i;
unsigned char blen;
if (msg_data == IPC_TIMEOUT) {
return(IPC_TIMEOUT);
}
for (i = 0; i < 12; i++) {
buff[i] = msg_data[i];
}
buff[12] = 0;
blen = strlen(buff);
if (message != NULL) {
len += blen;
message = (char *) erealloc(message, len + 1);
strcat(message, buff);
} else {
len = blen;
message = (char *) emalloc(len + 1);
strcpy(message, buff);
}
if (blen < 12) {
ret_msg = message;
message = NULL;
D(("Received complete reply: \"%s\"\n", ret_msg));
}
return(ret_msg);
} | {
"deleted": [
{
"line_no": 5,
"char_start": 73,
"char_end": 105,
"line": "\tstatic unsigned short len = 0;\n"
}
],
"added": [
{
"line_no": 5,
"char_start": 73,
"char_end": 97,
"line": "\tstatic size_t len = 0;\n"
}
]
} | {
"deleted": [
{
"char_start": 81,
"char_end": 83,
"chars": "un"
},
{
"char_start": 85,
"char_end": 87,
"chars": "gn"
},
{
"char_start": 88,
"char_end": 94,
"chars": "d shor"
}
],
"added": [
{
"char_start": 83,
"char_end": 84,
"chars": "z"
},
{
"char_start": 85,
"char_end": 86,
"chars": "_"
}
]
} | github.com/derf/feh/commit/f7a547b7ef8fc8ebdeaa4c28515c9d72e592fb6d | src/wallpaper.c | cwe-787 |
xdp_umem_reg | static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)
{
bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;
u32 chunk_size = mr->chunk_size, headroom = mr->headroom;
unsigned int chunks, chunks_per_page;
u64 addr = mr->addr, size = mr->len;
int size_chk, err;
if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {
/* Strictly speaking we could support this, if:
* - huge pages, or*
* - using an IOMMU, or
* - making sure the memory area is consecutive
* but for now, we simply say "computer says no".
*/
return -EINVAL;
}
if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |
XDP_UMEM_USES_NEED_WAKEUP))
return -EINVAL;
if (!unaligned_chunks && !is_power_of_2(chunk_size))
return -EINVAL;
if (!PAGE_ALIGNED(addr)) {
/* Memory area has to be page size aligned. For
* simplicity, this might change.
*/
return -EINVAL;
}
if ((addr + size) < addr)
return -EINVAL;
chunks = (unsigned int)div_u64(size, chunk_size);
if (chunks == 0)
return -EINVAL;
if (!unaligned_chunks) {
chunks_per_page = PAGE_SIZE / chunk_size;
if (chunks < chunks_per_page || chunks % chunks_per_page)
return -EINVAL;
}
size_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;
if (size_chk < 0)
return -EINVAL;
umem->address = (unsigned long)addr;
umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK
: ~((u64)chunk_size - 1);
umem->size = size;
umem->headroom = headroom;
umem->chunk_size_nohr = chunk_size - headroom;
umem->npgs = size / PAGE_SIZE;
umem->pgs = NULL;
umem->user = NULL;
umem->flags = mr->flags;
INIT_LIST_HEAD(&umem->xsk_list);
spin_lock_init(&umem->xsk_list_lock);
refcount_set(&umem->users, 1);
err = xdp_umem_account_pages(umem);
if (err)
return err;
err = xdp_umem_pin_pages(umem);
if (err)
goto out_account;
umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),
GFP_KERNEL_ACCOUNT);
if (!umem->pages) {
err = -ENOMEM;
goto out_pin;
}
err = xdp_umem_map_pages(umem);
if (!err)
return 0;
kvfree(umem->pages);
out_pin:
xdp_umem_unpin_pages(umem);
out_account:
xdp_umem_unaccount_pages(umem);
return err;
} | static int xdp_umem_reg(struct xdp_umem *umem, struct xdp_umem_reg *mr)
{
bool unaligned_chunks = mr->flags & XDP_UMEM_UNALIGNED_CHUNK_FLAG;
u32 chunk_size = mr->chunk_size, headroom = mr->headroom;
unsigned int chunks, chunks_per_page;
u64 addr = mr->addr, size = mr->len;
int err;
if (chunk_size < XDP_UMEM_MIN_CHUNK_SIZE || chunk_size > PAGE_SIZE) {
/* Strictly speaking we could support this, if:
* - huge pages, or*
* - using an IOMMU, or
* - making sure the memory area is consecutive
* but for now, we simply say "computer says no".
*/
return -EINVAL;
}
if (mr->flags & ~(XDP_UMEM_UNALIGNED_CHUNK_FLAG |
XDP_UMEM_USES_NEED_WAKEUP))
return -EINVAL;
if (!unaligned_chunks && !is_power_of_2(chunk_size))
return -EINVAL;
if (!PAGE_ALIGNED(addr)) {
/* Memory area has to be page size aligned. For
* simplicity, this might change.
*/
return -EINVAL;
}
if ((addr + size) < addr)
return -EINVAL;
chunks = (unsigned int)div_u64(size, chunk_size);
if (chunks == 0)
return -EINVAL;
if (!unaligned_chunks) {
chunks_per_page = PAGE_SIZE / chunk_size;
if (chunks < chunks_per_page || chunks % chunks_per_page)
return -EINVAL;
}
if (headroom >= chunk_size - XDP_PACKET_HEADROOM)
return -EINVAL;
umem->address = (unsigned long)addr;
umem->chunk_mask = unaligned_chunks ? XSK_UNALIGNED_BUF_ADDR_MASK
: ~((u64)chunk_size - 1);
umem->size = size;
umem->headroom = headroom;
umem->chunk_size_nohr = chunk_size - headroom;
umem->npgs = size / PAGE_SIZE;
umem->pgs = NULL;
umem->user = NULL;
umem->flags = mr->flags;
INIT_LIST_HEAD(&umem->xsk_list);
spin_lock_init(&umem->xsk_list_lock);
refcount_set(&umem->users, 1);
err = xdp_umem_account_pages(umem);
if (err)
return err;
err = xdp_umem_pin_pages(umem);
if (err)
goto out_account;
umem->pages = kvcalloc(umem->npgs, sizeof(*umem->pages),
GFP_KERNEL_ACCOUNT);
if (!umem->pages) {
err = -ENOMEM;
goto out_pin;
}
err = xdp_umem_map_pages(umem);
if (!err)
return 0;
kvfree(umem->pages);
out_pin:
xdp_umem_unpin_pages(umem);
out_account:
xdp_umem_unaccount_pages(umem);
return err;
} | {
"deleted": [
{
"line_no": 7,
"char_start": 278,
"char_end": 298,
"line": "\tint size_chk, err;\n"
},
{
"line_no": 46,
"char_start": 1202,
"char_end": 1259,
"line": "\tsize_chk = chunk_size - headroom - XDP_PACKET_HEADROOM;\n"
},
{
"line_no": 47,
"char_start": 1259,
"char_end": 1278,
"line": "\tif (size_chk < 0)\n"
}
],
"added": [
{
"line_no": 7,
"char_start": 278,
"char_end": 288,
"line": "\tint err;\n"
},
{
"line_no": 46,
"char_start": 1192,
"char_end": 1243,
"line": "\tif (headroom >= chunk_size - XDP_PACKET_HEADROOM)\n"
}
]
} | {
"deleted": [
{
"char_start": 283,
"char_end": 293,
"chars": "size_chk, "
},
{
"char_start": 1203,
"char_end": 1204,
"chars": "s"
},
{
"char_start": 1205,
"char_end": 1209,
"chars": "ze_c"
},
{
"char_start": 1210,
"char_end": 1211,
"chars": "k"
},
{
"char_start": 1227,
"char_end": 1238,
"chars": "headroom - "
},
{
"char_start": 1257,
"char_end": 1276,
"chars": ";\n\tif (size_chk < 0"
}
],
"added": [
{
"char_start": 1194,
"char_end": 1198,
"chars": "f (h"
},
{
"char_start": 1199,
"char_end": 1205,
"chars": "adroom"
},
{
"char_start": 1206,
"char_end": 1207,
"chars": ">"
}
]
} | github.com/torvalds/linux/commit/99e3a236dd43d06c65af0a2ef9cb44306aef6e02 | net/xdp/xdp_umem.c | cwe-787 |
gps_tracker | void gps_tracker( void )
{
ssize_t unused;
int gpsd_sock;
char line[256], *temp;
struct sockaddr_in gpsd_addr;
int ret, is_json, pos;
fd_set read_fd;
struct timeval timeout;
/* attempt to connect to localhost, port 2947 */
pos = 0;
gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 );
if( gpsd_sock < 0 ) {
return;
}
gpsd_addr.sin_family = AF_INET;
gpsd_addr.sin_port = htons( 2947 );
gpsd_addr.sin_addr.s_addr = inet_addr( "127.0.0.1" );
if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr,
sizeof( gpsd_addr ) ) < 0 ) {
return;
}
// Check if it's GPSd < 2.92 or the new one
// 2.92+ immediately send stuff
// < 2.92 requires to send PVTAD command
FD_ZERO(&read_fd);
FD_SET(gpsd_sock, &read_fd);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout);
if (is_json) {
/*
{"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3}
?WATCH={"json":true};
{"class":"DEVICES","devices":[]}
*/
// Get the crap and ignore it: {"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3}
if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )
return;
is_json = (line[0] == '{');
if (is_json) {
// Send ?WATCH={"json":true};
memset( line, 0, sizeof( line ) );
strcpy(line, "?WATCH={\"json\":true};\n");
if( send( gpsd_sock, line, 22, 0 ) != 22 )
return;
// Check that we have devices
memset(line, 0, sizeof(line));
if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )
return;
// Stop processing if there is no device
if (strncmp(line, "{\"class\":\"DEVICES\",\"devices\":[]}", 32) == 0) {
close(gpsd_sock);
return;
} else {
pos = strlen(line);
}
}
}
/* loop reading the GPS coordinates */
while( G.do_exit == 0 )
{
usleep( 500000 );
memset( G.gps_loc, 0, sizeof( float ) * 5 );
/* read position, speed, heading, altitude */
if (is_json) {
// Format definition: http://catb.org/gpsd/gpsd_json.html
if (pos == sizeof( line )) {
memset(line, 0, sizeof(line));
pos = 0;
}
// New version, JSON
if( recv( gpsd_sock, line + pos, sizeof( line ) - 1, 0 ) <= 0 )
return;
// search for TPV class: {"class":"TPV"
temp = strstr(line, "{\"class\":\"TPV\"");
if (temp == NULL) {
continue;
}
// Make sure the data we have is complete
if (strchr(temp, '}') == NULL) {
// Move the data at the beginning of the buffer;
pos = strlen(temp);
if (temp != line) {
memmove(line, temp, pos);
memset(line + pos, 0, sizeof(line) - pos);
}
}
// Example line: {"class":"TPV","tag":"MID2","device":"/dev/ttyUSB0","time":1350957517.000,"ept":0.005,"lat":46.878936576,"lon":-115.832602964,"alt":1968.382,"track":0.0000,"speed":0.000,"climb":0.000,"mode":3}
// Latitude
temp = strstr(temp, "\"lat\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[0]);
// Longitude
temp = strstr(temp, "\"lon\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[1]);
// Altitude
temp = strstr(temp, "\"alt\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[4]);
// Speed
temp = strstr(temp, "\"speed\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[2]);
// No more heading
// Get the next TPV class
temp = strstr(temp, "{\"class\":\"TPV\"");
if (temp == NULL) {
memset( line, 0, sizeof( line ) );
pos = 0;
} else {
pos = strlen(temp);
memmove(line, temp, pos);
memset(line + pos, 0, sizeof(line) - pos);
}
} else {
memset( line, 0, sizeof( line ) );
snprintf( line, sizeof( line ) - 1, "PVTAD\r\n" );
if( send( gpsd_sock, line, 7, 0 ) != 7 )
return;
memset( line, 0, sizeof( line ) );
if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )
return;
if( memcmp( line, "GPSD,P=", 7 ) != 0 )
continue;
/* make sure the coordinates are present */
if( line[7] == '?' )
continue;
ret = sscanf( line + 7, "%f %f", &G.gps_loc[0], &G.gps_loc[1] );
if( ( temp = strstr( line, "V=" ) ) == NULL ) continue;
ret = sscanf( temp + 2, "%f", &G.gps_loc[2] ); /* speed */
if( ( temp = strstr( line, "T=" ) ) == NULL ) continue;
ret = sscanf( temp + 2, "%f", &G.gps_loc[3] ); /* heading */
if( ( temp = strstr( line, "A=" ) ) == NULL ) continue;
ret = sscanf( temp + 2, "%f", &G.gps_loc[4] ); /* altitude */
}
if (G.record_data)
fputs( line, G.f_gps );
G.save_gps = 1;
if (G.do_exit == 0)
{
unused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 );
kill( getppid(), SIGUSR2 );
}
}
} | void gps_tracker( void )
{
ssize_t unused;
int gpsd_sock;
char line[256], *temp;
struct sockaddr_in gpsd_addr;
int ret, is_json, pos;
fd_set read_fd;
struct timeval timeout;
/* attempt to connect to localhost, port 2947 */
pos = 0;
gpsd_sock = socket( AF_INET, SOCK_STREAM, 0 );
if( gpsd_sock < 0 ) {
return;
}
gpsd_addr.sin_family = AF_INET;
gpsd_addr.sin_port = htons( 2947 );
gpsd_addr.sin_addr.s_addr = inet_addr( "127.0.0.1" );
if( connect( gpsd_sock, (struct sockaddr *) &gpsd_addr,
sizeof( gpsd_addr ) ) < 0 ) {
return;
}
// Check if it's GPSd < 2.92 or the new one
// 2.92+ immediately send stuff
// < 2.92 requires to send PVTAD command
FD_ZERO(&read_fd);
FD_SET(gpsd_sock, &read_fd);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
is_json = select(gpsd_sock + 1, &read_fd, NULL, NULL, &timeout);
if (is_json) {
/*
{"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3}
?WATCH={"json":true};
{"class":"DEVICES","devices":[]}
*/
// Get the crap and ignore it: {"class":"VERSION","release":"2.95","rev":"2010-11-16T21:12:35","proto_major":3,"proto_minor":3}
if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )
return;
is_json = (line[0] == '{');
if (is_json) {
// Send ?WATCH={"json":true};
memset( line, 0, sizeof( line ) );
strcpy(line, "?WATCH={\"json\":true};\n");
if( send( gpsd_sock, line, 22, 0 ) != 22 )
return;
// Check that we have devices
memset(line, 0, sizeof(line));
if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )
return;
// Stop processing if there is no device
if (strncmp(line, "{\"class\":\"DEVICES\",\"devices\":[]}", 32) == 0) {
close(gpsd_sock);
return;
} else {
pos = strlen(line);
}
}
}
/* loop reading the GPS coordinates */
while( G.do_exit == 0 )
{
usleep( 500000 );
memset( G.gps_loc, 0, sizeof( float ) * 5 );
/* read position, speed, heading, altitude */
if (is_json) {
// Format definition: http://catb.org/gpsd/gpsd_json.html
if (pos == sizeof( line )) {
memset(line, 0, sizeof(line));
pos = 0;
}
// New version, JSON
if( recv( gpsd_sock, line + pos, sizeof( line ) - pos - 1, 0 ) <= 0 )
return;
// search for TPV class: {"class":"TPV"
temp = strstr(line, "{\"class\":\"TPV\"");
if (temp == NULL) {
continue;
}
// Make sure the data we have is complete
if (strchr(temp, '}') == NULL) {
// Move the data at the beginning of the buffer;
pos = strlen(temp);
if (temp != line) {
memmove(line, temp, pos);
memset(line + pos, 0, sizeof(line) - pos);
}
}
// Example line: {"class":"TPV","tag":"MID2","device":"/dev/ttyUSB0","time":1350957517.000,"ept":0.005,"lat":46.878936576,"lon":-115.832602964,"alt":1968.382,"track":0.0000,"speed":0.000,"climb":0.000,"mode":3}
// Latitude
temp = strstr(temp, "\"lat\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[0]);
// Longitude
temp = strstr(temp, "\"lon\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[1]);
// Altitude
temp = strstr(temp, "\"alt\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[4]);
// Speed
temp = strstr(temp, "\"speed\":");
if (temp == NULL) {
continue;
}
ret = sscanf(temp + 6, "%f", &G.gps_loc[2]);
// No more heading
// Get the next TPV class
temp = strstr(temp, "{\"class\":\"TPV\"");
if (temp == NULL) {
memset( line, 0, sizeof( line ) );
pos = 0;
} else {
pos = strlen(temp);
memmove(line, temp, pos);
memset(line + pos, 0, sizeof(line) - pos);
}
} else {
memset( line, 0, sizeof( line ) );
snprintf( line, sizeof( line ) - 1, "PVTAD\r\n" );
if( send( gpsd_sock, line, 7, 0 ) != 7 )
return;
memset( line, 0, sizeof( line ) );
if( recv( gpsd_sock, line, sizeof( line ) - 1, 0 ) <= 0 )
return;
if( memcmp( line, "GPSD,P=", 7 ) != 0 )
continue;
/* make sure the coordinates are present */
if( line[7] == '?' )
continue;
ret = sscanf( line + 7, "%f %f", &G.gps_loc[0], &G.gps_loc[1] );
if( ( temp = strstr( line, "V=" ) ) == NULL ) continue;
ret = sscanf( temp + 2, "%f", &G.gps_loc[2] ); /* speed */
if( ( temp = strstr( line, "T=" ) ) == NULL ) continue;
ret = sscanf( temp + 2, "%f", &G.gps_loc[3] ); /* heading */
if( ( temp = strstr( line, "A=" ) ) == NULL ) continue;
ret = sscanf( temp + 2, "%f", &G.gps_loc[4] ); /* altitude */
}
if (G.record_data)
fputs( line, G.f_gps );
G.save_gps = 1;
if (G.do_exit == 0)
{
unused = write( G.gc_pipe[1], G.gps_loc, sizeof( float ) * 5 );
kill( getppid(), SIGUSR2 );
}
}
} | {
"deleted": [
{
"line_no": 89,
"char_start": 2379,
"char_end": 2452,
"line": " \tif( recv( gpsd_sock, line + pos, sizeof( line ) - 1, 0 ) <= 0 )\n"
}
],
"added": [
{
"line_no": 89,
"char_start": 2379,
"char_end": 2458,
"line": " \tif( recv( gpsd_sock, line + pos, sizeof( line ) - pos - 1, 0 ) <= 0 )\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2438,
"char_end": 2444,
"chars": "pos - "
}
]
} | github.com/aircrack-ng/aircrack-ng/commit/ff70494dd389ba570dbdbf36f217c28d4381c6b5/ | src/airodump-ng.c | cwe-787 |
tcp_test | int tcp_test(const char* ip_str, const short port)
{
int sock, i;
struct sockaddr_in s_in;
int packetsize = 1024;
unsigned char packet[packetsize];
struct timeval tv, tv2, tv3;
int caplen = 0;
int times[REQUESTS];
int min, avg, max, len;
struct net_hdr nh;
tv3.tv_sec=0;
tv3.tv_usec=1;
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
if (!inet_aton(ip_str, &s_in.sin_addr))
return -1;
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
/* avoid blocking on reading the socket */
if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 )
{
perror( "fcntl(O_NONBLOCK) failed" );
return( 1 );
}
gettimeofday( &tv, NULL );
while (1) //waiting for relayed packet
{
if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)
{
if(errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return -1;
}
}
else
{
gettimeofday( &tv2, NULL );
break;
}
gettimeofday( &tv2, NULL );
//wait 3000ms for a successful connect
if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000))
{
printf("Connection timed out\n");
close(sock);
return(-1);
}
usleep(10);
}
PCT; printf("TCP connection successful\n");
//trying to identify airserv-ng
memset(&nh, 0, sizeof(nh));
// command: GET_CHAN
nh.nh_type = 2;
nh.nh_len = htonl(0);
if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh))
{
perror("send");
return -1;
}
gettimeofday( &tv, NULL );
i=0;
while (1) //waiting for GET_CHAN answer
{
caplen = read(sock, &nh, sizeof(nh));
if(caplen == -1)
{
if( errno != EAGAIN )
{
perror("read");
return -1;
}
}
if( (unsigned)caplen == sizeof(nh))
{
len = ntohl(nh.nh_len);
if( nh.nh_type == 1 && i==0 )
{
i=1;
caplen = read(sock, packet, len);
if(caplen == len)
{
i=2;
break;
}
else
{
i=0;
}
}
else
{
caplen = read(sock, packet, len);
}
}
gettimeofday( &tv2, NULL );
//wait 1000ms for an answer
if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000))
{
break;
}
if(caplen == -1)
usleep(10);
}
if(i==2)
{
PCT; printf("airserv-ng found\n");
}
else
{
PCT; printf("airserv-ng NOT found\n");
}
close(sock);
for(i=0; i<REQUESTS; i++)
{
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
/* avoid blocking on reading the socket */
if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 )
{
perror( "fcntl(O_NONBLOCK) failed" );
return( 1 );
}
usleep(1000);
gettimeofday( &tv, NULL );
while (1) //waiting for relayed packet
{
if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)
{
if(errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return -1;
}
}
else
{
gettimeofday( &tv2, NULL );
break;
}
gettimeofday( &tv2, NULL );
//wait 1000ms for a successful connect
if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000))
{
break;
}
//simple "high-precision" usleep
select(1, NULL, NULL, NULL, &tv3);
}
times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec));
printf( "\r%d/%d\r", i, REQUESTS);
fflush(stdout);
close(sock);
}
min = INT_MAX;
avg = 0;
max = 0;
for(i=0; i<REQUESTS; i++)
{
if(times[i] < min) min = times[i];
if(times[i] > max) max = times[i];
avg += times[i];
}
avg /= REQUESTS;
PCT; printf("ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n", ip_str, port, min/1000.0, avg/1000.0, max/1000.0);
return 0;
} | int tcp_test(const char* ip_str, const short port)
{
int sock, i;
struct sockaddr_in s_in;
int packetsize = 1024;
unsigned char packet[packetsize];
struct timeval tv, tv2, tv3;
int caplen = 0;
int times[REQUESTS];
int min, avg, max, len;
struct net_hdr nh;
tv3.tv_sec=0;
tv3.tv_usec=1;
s_in.sin_family = PF_INET;
s_in.sin_port = htons(port);
if (!inet_aton(ip_str, &s_in.sin_addr))
return -1;
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
/* avoid blocking on reading the socket */
if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 )
{
perror( "fcntl(O_NONBLOCK) failed" );
return( 1 );
}
gettimeofday( &tv, NULL );
while (1) //waiting for relayed packet
{
if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)
{
if(errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return -1;
}
}
else
{
gettimeofday( &tv2, NULL );
break;
}
gettimeofday( &tv2, NULL );
//wait 3000ms for a successful connect
if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (3000*1000))
{
printf("Connection timed out\n");
close(sock);
return(-1);
}
usleep(10);
}
PCT; printf("TCP connection successful\n");
//trying to identify airserv-ng
memset(&nh, 0, sizeof(nh));
// command: GET_CHAN
nh.nh_type = 2;
nh.nh_len = htonl(0);
if (send(sock, &nh, sizeof(nh), 0) != sizeof(nh))
{
perror("send");
return -1;
}
gettimeofday( &tv, NULL );
i=0;
while (1) //waiting for GET_CHAN answer
{
caplen = read(sock, &nh, sizeof(nh));
if(caplen == -1)
{
if( errno != EAGAIN )
{
perror("read");
return -1;
}
}
if( (unsigned)caplen == sizeof(nh))
{
len = ntohl(nh.nh_len);
if (len > 1024 || len < 0)
continue;
if( nh.nh_type == 1 && i==0 )
{
i=1;
caplen = read(sock, packet, len);
if(caplen == len)
{
i=2;
break;
}
else
{
i=0;
}
}
else
{
caplen = read(sock, packet, len);
}
}
gettimeofday( &tv2, NULL );
//wait 1000ms for an answer
if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000))
{
break;
}
if(caplen == -1)
usleep(10);
}
if(i==2)
{
PCT; printf("airserv-ng found\n");
}
else
{
PCT; printf("airserv-ng NOT found\n");
}
close(sock);
for(i=0; i<REQUESTS; i++)
{
if ((sock = socket(s_in.sin_family, SOCK_STREAM, IPPROTO_TCP)) == -1)
return -1;
/* avoid blocking on reading the socket */
if( fcntl( sock, F_SETFL, O_NONBLOCK ) < 0 )
{
perror( "fcntl(O_NONBLOCK) failed" );
return( 1 );
}
usleep(1000);
gettimeofday( &tv, NULL );
while (1) //waiting for relayed packet
{
if (connect(sock, (struct sockaddr*) &s_in, sizeof(s_in)) == -1)
{
if(errno != EINPROGRESS && errno != EALREADY)
{
perror("connect");
close(sock);
printf("Failed to connect\n");
return -1;
}
}
else
{
gettimeofday( &tv2, NULL );
break;
}
gettimeofday( &tv2, NULL );
//wait 1000ms for a successful connect
if (((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec)) > (1000*1000))
{
break;
}
//simple "high-precision" usleep
select(1, NULL, NULL, NULL, &tv3);
}
times[i] = ((tv2.tv_sec*1000000 - tv.tv_sec*1000000) + (tv2.tv_usec - tv.tv_usec));
printf( "\r%d/%d\r", i, REQUESTS);
fflush(stdout);
close(sock);
}
min = INT_MAX;
avg = 0;
max = 0;
for(i=0; i<REQUESTS; i++)
{
if(times[i] < min) min = times[i];
if(times[i] > max) max = times[i];
avg += times[i];
}
avg /= REQUESTS;
PCT; printf("ping %s:%d (min/avg/max): %.3fms/%.3fms/%.3fms\n", ip_str, port, min/1000.0, avg/1000.0, max/1000.0);
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 97,
"char_start": 2251,
"char_end": 2290,
"line": " if (len > 1024 || len < 0)\n"
},
{
"line_no": 98,
"char_start": 2290,
"char_end": 2316,
"line": " continue;\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2265,
"char_end": 2330,
"chars": " (len > 1024 || len < 0)\n continue;\n if"
}
]
} | github.com/aircrack-ng/aircrack-ng/commit/091b153f294b9b695b0b2831e65936438b550d7b | src/aireplay-ng.c | cwe-787 |
mapi_attr_read | mapi_attr_read (size_t len, unsigned char *buf)
{
size_t idx = 0;
uint32 i,j;
assert(len > 4);
uint32 num_properties = GETINT32(buf+idx);
MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1));
idx += 4;
if (!attrs) return NULL;
for (i = 0; i < num_properties; i++)
{
MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1);
MAPI_Value* v = NULL;
CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2;
CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2;
/* handle special case of GUID prefixed properties */
if (a->name & GUID_EXISTS_FLAG)
{
/* copy GUID */
a->guid = CHECKED_XMALLOC(GUID, 1);
copy_guid_from_buf(a->guid, buf+idx, len);
idx += sizeof (GUID);
CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4;
if (a->num_names > 0)
{
/* FIXME: do something useful here! */
size_t i;
a->names = CHECKED_XCALLOC(VarLenData, a->num_names);
for (i = 0; i < a->num_names; i++)
{
size_t j;
CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;
/* read the data into a buffer */
a->names[i].data
= CHECKED_XMALLOC(unsigned char, a->names[i].len);
for (j = 0; j < (a->names[i].len >> 1); j++)
a->names[i].data[j] = (buf+idx)[j*2];
/* But what are we going to do with it? */
idx += pad_to_4byte(a->names[i].len);
}
}
else
{
/* get the 'real' name */
CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4;
}
}
/*
* Multi-value types and string/object/binary types have
* multiple values
*/
if (a->type & MULTI_VALUE_FLAG ||
a->type == szMAPI_STRING ||
a->type == szMAPI_UNICODE_STRING ||
a->type == szMAPI_OBJECT ||
a->type == szMAPI_BINARY)
{
CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx);
idx += 4;
}
else
{
a->num_values = 1;
}
/* Amend the type in case of multi-value type */
if (a->type & MULTI_VALUE_FLAG)
{
a->type -= MULTI_VALUE_FLAG;
}
v = alloc_mapi_values (a);
for (j = 0; j < a->num_values; j++)
{
switch (a->type)
{
case szMAPI_SHORT: /* 2 bytes */
v->len = 2;
CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx);
idx += 4; /* assume padding of 2, advance by 4! */
break;
case szMAPI_INT: /* 4 bytes */
v->len = 4;
CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
idx += 4;
v++;
break;
case szMAPI_FLOAT: /* 4 bytes */
case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */
v->len = 4;
CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
idx += v->len;
break;
case szMAPI_SYSTIME: /* 8 bytes */
v->len = 8;
CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
idx += 8;
v++;
break;
case szMAPI_DOUBLE: /* 8 bytes */
case szMAPI_APPTIME:
case szMAPI_CURRENCY:
case szMAPI_INT8BYTE:
v->len = 8;
CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
idx += v->len;
break;
case szMAPI_CLSID:
v->len = sizeof (GUID);
copy_guid_from_buf(&v->data.guid, buf+idx, len);
idx += v->len;
break;
case szMAPI_STRING:
case szMAPI_UNICODE_STRING:
case szMAPI_OBJECT:
case szMAPI_BINARY:
CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4;
if (a->type == szMAPI_UNICODE_STRING)
{
v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx);
}
else
{
v->data.buf = CHECKED_XMALLOC(unsigned char, v->len);
memmove (v->data.buf, buf+idx, v->len);
}
idx += pad_to_4byte(v->len);
v++;
break;
case szMAPI_NULL: /* illegal in input tnef streams */
case szMAPI_ERROR:
case szMAPI_UNSPECIFIED:
fprintf (stderr,
"Invalid attribute, input file may be corrupted\n");
if (!ENCODE_SKIP) exit (1);
return NULL;
default: /* should never get here */
fprintf (stderr,
"Undefined attribute, input file may be corrupted\n");
if (!ENCODE_SKIP) exit (1);
return NULL;
}
if (DEBUG_ON) mapi_attr_dump (attrs[i]);
}
}
attrs[i] = NULL;
return attrs;
} | mapi_attr_read (size_t len, unsigned char *buf)
{
size_t idx = 0;
uint32 i,j;
assert(len > 4);
uint32 num_properties = GETINT32(buf+idx);
assert((num_properties+1) != 0);
MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1));
idx += 4;
if (!attrs) return NULL;
for (i = 0; i < num_properties; i++)
{
MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1);
MAPI_Value* v = NULL;
CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2;
CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2;
/* handle special case of GUID prefixed properties */
if (a->name & GUID_EXISTS_FLAG)
{
/* copy GUID */
a->guid = CHECKED_XMALLOC(GUID, 1);
copy_guid_from_buf(a->guid, buf+idx, len);
idx += sizeof (GUID);
CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4;
if (a->num_names > 0)
{
/* FIXME: do something useful here! */
size_t i;
a->names = CHECKED_XCALLOC(VarLenData, a->num_names);
for (i = 0; i < a->num_names; i++)
{
size_t j;
CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4;
/* read the data into a buffer */
a->names[i].data
= CHECKED_XMALLOC(unsigned char, a->names[i].len);
assert((idx+(a->names[i].len*2)) <= len);
for (j = 0; j < (a->names[i].len >> 1); j++)
a->names[i].data[j] = (buf+idx)[j*2];
/* But what are we going to do with it? */
idx += pad_to_4byte(a->names[i].len);
}
}
else
{
/* get the 'real' name */
CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4;
}
}
/*
* Multi-value types and string/object/binary types have
* multiple values
*/
if (a->type & MULTI_VALUE_FLAG ||
a->type == szMAPI_STRING ||
a->type == szMAPI_UNICODE_STRING ||
a->type == szMAPI_OBJECT ||
a->type == szMAPI_BINARY)
{
CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx);
idx += 4;
}
else
{
a->num_values = 1;
}
/* Amend the type in case of multi-value type */
if (a->type & MULTI_VALUE_FLAG)
{
a->type -= MULTI_VALUE_FLAG;
}
v = alloc_mapi_values (a);
for (j = 0; j < a->num_values; j++)
{
switch (a->type)
{
case szMAPI_SHORT: /* 2 bytes */
v->len = 2;
CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx);
idx += 4; /* assume padding of 2, advance by 4! */
break;
case szMAPI_INT: /* 4 bytes */
v->len = 4;
CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
idx += 4;
v++;
break;
case szMAPI_FLOAT: /* 4 bytes */
case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */
v->len = 4;
CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx);
idx += v->len;
break;
case szMAPI_SYSTIME: /* 8 bytes */
v->len = 8;
CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
idx += 8;
v++;
break;
case szMAPI_DOUBLE: /* 8 bytes */
case szMAPI_APPTIME:
case szMAPI_CURRENCY:
case szMAPI_INT8BYTE:
v->len = 8;
CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx);
CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4);
idx += v->len;
break;
case szMAPI_CLSID:
v->len = sizeof (GUID);
copy_guid_from_buf(&v->data.guid, buf+idx, len);
idx += v->len;
break;
case szMAPI_STRING:
case szMAPI_UNICODE_STRING:
case szMAPI_OBJECT:
case szMAPI_BINARY:
CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4;
assert(v->len + idx <= len);
if (a->type == szMAPI_UNICODE_STRING)
{
assert(v->len != 0);
v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx);
}
else
{
v->data.buf = CHECKED_XMALLOC(unsigned char, v->len);
memmove (v->data.buf, buf+idx, v->len);
}
idx += pad_to_4byte(v->len);
v++;
break;
case szMAPI_NULL: /* illegal in input tnef streams */
case szMAPI_ERROR:
case szMAPI_UNSPECIFIED:
fprintf (stderr,
"Invalid attribute, input file may be corrupted\n");
if (!ENCODE_SKIP) exit (1);
return NULL;
default: /* should never get here */
fprintf (stderr,
"Undefined attribute, input file may be corrupted\n");
if (!ENCODE_SKIP) exit (1);
return NULL;
}
if (DEBUG_ON) mapi_attr_dump (attrs[i]);
}
}
attrs[i] = NULL;
return attrs;
} | {
"deleted": [],
"added": [
{
"line_no": 7,
"char_start": 154,
"char_end": 191,
"line": " assert((num_properties+1) != 0);\n"
},
{
"line_no": 46,
"char_start": 1263,
"char_end": 1311,
"line": "\t\t assert((idx+(a->names[i].len*2)) <= len);\n"
},
{
"line_no": 143,
"char_start": 3582,
"char_end": 3613,
"line": "\t\tassert(v->len + idx <= len);\n"
},
{
"line_no": 144,
"char_start": 3613,
"char_end": 3614,
"line": "\n"
},
{
"line_no": 147,
"char_start": 3658,
"char_end": 3685,
"line": "\t\t assert(v->len != 0);\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 158,
"char_end": 195,
"chars": "assert((num_properties+1) != 0);\n "
},
{
"char_start": 1257,
"char_end": 1305,
"chars": "len);\n\t\t assert((idx+(a->names[i].len*2)) <= "
},
{
"char_start": 3584,
"char_end": 3616,
"chars": "assert(v->len + idx <= len);\n\n\t\t"
},
{
"char_start": 3657,
"char_end": 3684,
"chars": "\n\t\t assert(v->len != 0);"
}
]
} | github.com/verdammelt/tnef/commit/1a17af1ed0c791aec44dbdc9eab91218cc1e335a | src/mapi_attr.c | cwe-787 |
WritePSDChannel | static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
} | static size_t WritePSDChannel(const PSDInfo *psd_info,
const ImageInfo *image_info,Image *image,Image *next_image,
const QuantumType quantum_type, unsigned char *compact_pixels,
MagickOffsetType size_offset,const MagickBooleanType separate,
ExceptionInfo *exception)
{
int
y;
MagickBooleanType
monochrome;
QuantumInfo
*quantum_info;
register const Quantum
*p;
register ssize_t
i;
size_t
count,
length;
unsigned char
*pixels;
#ifdef MAGICKCORE_ZLIB_DELEGATE
#define CHUNK 16384
int
flush,
level;
unsigned char
*compressed_pixels;
z_stream
stream;
compressed_pixels=(unsigned char *) NULL;
flush=Z_NO_FLUSH;
#endif
count=0;
if (separate != MagickFalse)
{
size_offset=TellBlob(image)+2;
count+=WriteCompressionStart(psd_info,image,next_image,1);
}
if (next_image->depth > 8)
next_image->depth=16;
monochrome=IsImageMonochrome(image) && (image->depth == 1) ?
MagickTrue : MagickFalse;
quantum_info=AcquireQuantumInfo(image_info,next_image);
if (quantum_info == (QuantumInfo *) NULL)
return(0);
pixels=(unsigned char *) GetQuantumPixels(quantum_info);
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK,
sizeof(*compressed_pixels));
if (compressed_pixels == (unsigned char *) NULL)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
ResetMagickMemory(&stream,0,sizeof(stream));
stream.data_type=Z_BINARY;
level=Z_DEFAULT_COMPRESSION;
if ((image_info->quality > 0 && image_info->quality < 10))
level=(int) image_info->quality;
if (deflateInit(&stream,level) != Z_OK)
{
quantum_info=DestroyQuantumInfo(quantum_info);
return(0);
}
}
#endif
for (y=0; y < (ssize_t) next_image->rows; y++)
{
p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception);
if (p == (const Quantum *) NULL)
break;
length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info,
quantum_type,pixels,exception);
if (monochrome != MagickFalse)
for (i=0; i < (ssize_t) length; i++)
pixels[i]=(~pixels[i]);
if (next_image->compression == RLECompression)
{
length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels,
exception);
count+=WriteBlob(image,length,compact_pixels);
size_offset+=WritePSDOffset(psd_info,image,length,size_offset);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
else if (next_image->compression == ZipCompression)
{
stream.avail_in=(uInt) length;
stream.next_in=(Bytef *) pixels;
if (y == (ssize_t) next_image->rows-1)
flush=Z_FINISH;
do {
stream.avail_out=(uInt) CHUNK;
stream.next_out=(Bytef *) compressed_pixels;
if (deflate(&stream,flush) == Z_STREAM_ERROR)
break;
length=(size_t) CHUNK-stream.avail_out;
if (length > 0)
count+=WriteBlob(image,length,compressed_pixels);
} while (stream.avail_out == 0);
}
#endif
else
count+=WriteBlob(image,length,pixels);
}
#ifdef MAGICKCORE_ZLIB_DELEGATE
if (next_image->compression == ZipCompression)
{
(void) deflateEnd(&stream);
compressed_pixels=(unsigned char *) RelinquishMagickMemory(
compressed_pixels);
}
#endif
quantum_info=DestroyQuantumInfo(quantum_info);
return(count);
} | {
"deleted": [
{
"line_no": 56,
"char_start": 1009,
"char_end": 1062,
"line": " quantum_info=AcquireQuantumInfo(image_info,image);\n"
}
],
"added": [
{
"line_no": 56,
"char_start": 1009,
"char_end": 1067,
"line": " quantum_info=AcquireQuantumInfo(image_info,next_image);\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 1054,
"char_end": 1059,
"chars": "next_"
}
]
} | github.com/ImageMagick/ImageMagick/commit/91cc3f36f2ccbd485a0456bab9aebe63b635da88 | coders/psd.c | cwe-787 |
flb_gzip_compress | int flb_gzip_compress(void *in_data, size_t in_len,
void **out_data, size_t *out_len)
{
int flush;
int status;
int footer_start;
uint8_t *pb;
size_t out_size;
void *out_buf;
z_stream strm;
mz_ulong crc;
out_size = in_len + 32;
out_buf = flb_malloc(out_size);
if (!out_buf) {
flb_errno();
flb_error("[gzip] could not allocate outgoing buffer");
return -1;
}
/* Initialize streaming buffer context */
memset(&strm, '\0', sizeof(strm));
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = in_data;
strm.avail_in = in_len;
strm.total_out = 0;
/* Deflate mode */
deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY);
/*
* Miniz don't support GZip format directly, instead we will:
*
* - append manual GZip magic bytes
* - deflate raw content
* - append manual CRC32 data
*/
gzip_header(out_buf);
/* Header offset */
pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET;
flush = Z_NO_FLUSH;
while (1) {
strm.next_out = pb + strm.total_out;
strm.avail_out = out_size - (pb - (uint8_t *) out_buf);
if (strm.avail_in == 0) {
flush = Z_FINISH;
}
status = deflate(&strm, flush);
if (status == Z_STREAM_END) {
break;
}
else if (status != Z_OK) {
deflateEnd(&strm);
return -1;
}
}
if (deflateEnd(&strm) != Z_OK) {
flb_free(out_buf);
return -1;
}
*out_len = strm.total_out;
/* Construct the gzip checksum (CRC32 footer) */
footer_start = FLB_GZIP_HEADER_OFFSET + *out_len;
pb = (uint8_t *) out_buf + footer_start;
crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len);
*pb++ = crc & 0xFF;
*pb++ = (crc >> 8) & 0xFF;
*pb++ = (crc >> 16) & 0xFF;
*pb++ = (crc >> 24) & 0xFF;
*pb++ = in_len & 0xFF;
*pb++ = (in_len >> 8) & 0xFF;
*pb++ = (in_len >> 16) & 0xFF;
*pb++ = (in_len >> 24) & 0xFF;
/* Set the real buffer size for the caller */
*out_len += FLB_GZIP_HEADER_OFFSET + 8;
*out_data = out_buf;
return 0;
} | int flb_gzip_compress(void *in_data, size_t in_len,
void **out_data, size_t *out_len)
{
int flush;
int status;
int footer_start;
uint8_t *pb;
size_t out_size;
void *out_buf;
z_stream strm;
mz_ulong crc;
/*
* GZIP relies on an algorithm with worst-case expansion
* of 5 bytes per 32KB data. This means we need to create a variable
* length output, that depends on the input length.
* See RFC 1951 for details.
*/
int max_input_expansion = ((int)(in_len / 32000) + 1) * 5;
/*
* Max compressed size is equal to sum of:
* 10 byte header
* 8 byte foot
* max input expansion
* size of input
*/
out_size = 10 + 8 + max_input_expansion + in_len;
out_buf = flb_malloc(out_size);
if (!out_buf) {
flb_errno();
flb_error("[gzip] could not allocate outgoing buffer");
return -1;
}
/* Initialize streaming buffer context */
memset(&strm, '\0', sizeof(strm));
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = in_data;
strm.avail_in = in_len;
strm.total_out = 0;
/* Deflate mode */
deflateInit2(&strm, Z_DEFAULT_COMPRESSION,
Z_DEFLATED, -Z_DEFAULT_WINDOW_BITS, 9, Z_DEFAULT_STRATEGY);
/*
* Miniz don't support GZip format directly, instead we will:
*
* - append manual GZip magic bytes
* - deflate raw content
* - append manual CRC32 data
*/
gzip_header(out_buf);
/* Header offset */
pb = (uint8_t *) out_buf + FLB_GZIP_HEADER_OFFSET;
flush = Z_NO_FLUSH;
while (1) {
strm.next_out = pb + strm.total_out;
strm.avail_out = out_size - (pb - (uint8_t *) out_buf);
if (strm.avail_in == 0) {
flush = Z_FINISH;
}
status = deflate(&strm, flush);
if (status == Z_STREAM_END) {
break;
}
else if (status != Z_OK) {
deflateEnd(&strm);
return -1;
}
}
if (deflateEnd(&strm) != Z_OK) {
flb_free(out_buf);
return -1;
}
*out_len = strm.total_out;
/* Construct the gzip checksum (CRC32 footer) */
footer_start = FLB_GZIP_HEADER_OFFSET + *out_len;
pb = (uint8_t *) out_buf + footer_start;
crc = mz_crc32(MZ_CRC32_INIT, in_data, in_len);
*pb++ = crc & 0xFF;
*pb++ = (crc >> 8) & 0xFF;
*pb++ = (crc >> 16) & 0xFF;
*pb++ = (crc >> 24) & 0xFF;
*pb++ = in_len & 0xFF;
*pb++ = (in_len >> 8) & 0xFF;
*pb++ = (in_len >> 16) & 0xFF;
*pb++ = (in_len >> 24) & 0xFF;
/* Set the real buffer size for the caller */
*out_len += FLB_GZIP_HEADER_OFFSET + 8;
*out_data = out_buf;
return 0;
} | {
"deleted": [
{
"line_no": 13,
"char_start": 258,
"char_end": 286,
"line": " out_size = in_len + 32;\n"
}
],
"added": [
{
"line_no": 13,
"char_start": 258,
"char_end": 259,
"line": "\n"
},
{
"line_no": 14,
"char_start": 259,
"char_end": 266,
"line": " /*\n"
},
{
"line_no": 15,
"char_start": 266,
"char_end": 327,
"line": " * GZIP relies on an algorithm with worst-case expansion\n"
},
{
"line_no": 16,
"char_start": 327,
"char_end": 400,
"line": " * of 5 bytes per 32KB data. This means we need to create a variable\n"
},
{
"line_no": 17,
"char_start": 400,
"char_end": 456,
"line": " * length output, that depends on the input length.\n"
},
{
"line_no": 18,
"char_start": 456,
"char_end": 489,
"line": " * See RFC 1951 for details.\n"
},
{
"line_no": 19,
"char_start": 489,
"char_end": 497,
"line": " */\n"
},
{
"line_no": 20,
"char_start": 497,
"char_end": 560,
"line": " int max_input_expansion = ((int)(in_len / 32000) + 1) * 5;\n"
},
{
"line_no": 21,
"char_start": 560,
"char_end": 561,
"line": "\n"
},
{
"line_no": 22,
"char_start": 561,
"char_end": 568,
"line": " /*\n"
},
{
"line_no": 23,
"char_start": 568,
"char_end": 615,
"line": " * Max compressed size is equal to sum of:\n"
},
{
"line_no": 24,
"char_start": 615,
"char_end": 639,
"line": " * 10 byte header\n"
},
{
"line_no": 25,
"char_start": 639,
"char_end": 660,
"line": " * 8 byte foot\n"
},
{
"line_no": 26,
"char_start": 660,
"char_end": 689,
"line": " * max input expansion\n"
},
{
"line_no": 27,
"char_start": 689,
"char_end": 712,
"line": " * size of input\n"
},
{
"line_no": 28,
"char_start": 712,
"char_end": 720,
"line": " */\n"
},
{
"line_no": 29,
"char_start": 720,
"char_end": 774,
"line": " out_size = 10 + 8 + max_input_expansion + in_len;\n"
},
{
"line_no": 31,
"char_start": 810,
"char_end": 811,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 276,
"char_end": 277,
"chars": "l"
},
{
"char_start": 282,
"char_end": 284,
"chars": "32"
}
],
"added": [
{
"char_start": 258,
"char_end": 259,
"chars": "\n"
},
{
"char_start": 263,
"char_end": 324,
"chars": "/*\n * GZIP relies on an algorithm with worst-case expansi"
},
{
"char_start": 325,
"char_end": 418,
"chars": "n\n * of 5 bytes per 32KB data. This means we need to create a variable\n * length outp"
},
{
"char_start": 420,
"char_end": 433,
"chars": ", that depend"
},
{
"char_start": 434,
"char_end": 442,
"chars": " on the "
},
{
"char_start": 443,
"char_end": 465,
"chars": "nput length.\n * Se"
},
{
"char_start": 467,
"char_end": 525,
"chars": "RFC 1951 for details.\n */\n int max_input_expansion "
},
{
"char_start": 527,
"char_end": 534,
"chars": "((int)("
},
{
"char_start": 541,
"char_end": 542,
"chars": "/"
},
{
"char_start": 545,
"char_end": 772,
"chars": "000) + 1) * 5;\n\n /*\n * Max compressed size is equal to sum of:\n * 10 byte header\n * 8 byte foot\n * max input expansion\n * size of input\n */\n out_size = 10 + 8 + max_input_expansion + in_len"
},
{
"char_start": 809,
"char_end": 810,
"chars": "\n"
}
]
} | github.com/fluent/fluent-bit/commit/cadff53c093210404aed01c4cf586adb8caa07af | src/flb_gzip.c | cwe-787 |
sc_oberthur_read_file | sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path,
unsigned char **out, size_t *out_len,
int verify_pin)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_card *card = p15card->card;
struct sc_file *file = NULL;
struct sc_path path;
size_t sz;
int rv;
LOG_FUNC_CALLED(ctx);
if (!in_path || !out || !out_len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot read oberthur file");
sc_log(ctx, "read file '%s'; verify_pin:%i", in_path, verify_pin);
*out = NULL;
*out_len = 0;
sc_format_path(in_path, &path);
rv = sc_select_file(card, &path, &file);
if (rv != SC_SUCCESS) {
sc_file_free(file);
LOG_TEST_RET(ctx, rv, "Cannot select oberthur file to read");
}
if (file->ef_structure == SC_FILE_EF_TRANSPARENT)
sz = file->size;
else
sz = (file->record_length + 2) * file->record_count;
*out = calloc(sz, 1);
if (*out == NULL) {
sc_file_free(file);
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot read oberthur file");
}
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
rv = sc_read_binary(card, 0, *out, sz, 0);
}
else {
int rec;
int offs = 0;
int rec_len = file->record_length;
for (rec = 1; ; rec++) {
rv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR);
if (rv == SC_ERROR_RECORD_NOT_FOUND) {
rv = 0;
break;
}
else if (rv < 0) {
break;
}
rec_len = rv;
*(*out + offs) = 'R';
*(*out + offs + 1) = rv;
offs += rv + 2;
}
sz = offs;
}
sc_log(ctx, "read oberthur file result %i", rv);
if (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
struct sc_pkcs15_object *objs[0x10], *pin_obj = NULL;
const struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ);
int ii;
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10);
if (rv != SC_SUCCESS) {
sc_file_free(file);
LOG_TEST_RET(ctx, rv, "Cannot read oberthur file: get AUTH objects error");
}
for (ii=0; ii<rv; ii++) {
struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) objs[ii]->data;
sc_log(ctx, "compare PIN/ACL refs:%i/%i, method:%i/%i",
auth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method);
if (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) {
pin_obj = objs[ii];
break;
}
}
if (!pin_obj || !pin_obj->content.value) {
rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
}
else {
rv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len);
if (!rv)
rv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0);
}
};
sc_file_free(file);
if (rv < 0) {
free(*out);
*out = NULL;
*out_len = 0;
}
*out_len = sz;
LOG_FUNC_RETURN(ctx, rv);
} | sc_oberthur_read_file(struct sc_pkcs15_card *p15card, const char *in_path,
unsigned char **out, size_t *out_len,
int verify_pin)
{
struct sc_context *ctx = p15card->card->ctx;
struct sc_card *card = p15card->card;
struct sc_file *file = NULL;
struct sc_path path;
size_t sz;
int rv;
LOG_FUNC_CALLED(ctx);
if (!in_path || !out || !out_len)
LOG_TEST_RET(ctx, SC_ERROR_INVALID_ARGUMENTS, "Cannot read oberthur file");
sc_log(ctx, "read file '%s'; verify_pin:%i", in_path, verify_pin);
*out = NULL;
*out_len = 0;
sc_format_path(in_path, &path);
rv = sc_select_file(card, &path, &file);
if (rv != SC_SUCCESS) {
sc_file_free(file);
LOG_TEST_RET(ctx, rv, "Cannot select oberthur file to read");
}
if (file->ef_structure == SC_FILE_EF_TRANSPARENT)
sz = file->size;
else
sz = (file->record_length + 2) * file->record_count;
*out = calloc(sz, 1);
if (*out == NULL) {
sc_file_free(file);
LOG_TEST_RET(ctx, SC_ERROR_OUT_OF_MEMORY, "Cannot read oberthur file");
}
if (file->ef_structure == SC_FILE_EF_TRANSPARENT) {
rv = sc_read_binary(card, 0, *out, sz, 0);
}
else {
size_t rec;
size_t offs = 0;
size_t rec_len = file->record_length;
for (rec = 1; ; rec++) {
if (rec > file->record_count) {
rv = 0;
break;
}
rv = sc_read_record(card, rec, *out + offs + 2, rec_len, SC_RECORD_BY_REC_NR);
if (rv == SC_ERROR_RECORD_NOT_FOUND) {
rv = 0;
break;
}
else if (rv < 0) {
break;
}
rec_len = rv;
*(*out + offs) = 'R';
*(*out + offs + 1) = rv;
offs += rv + 2;
}
sz = offs;
}
sc_log(ctx, "read oberthur file result %i", rv);
if (verify_pin && rv == SC_ERROR_SECURITY_STATUS_NOT_SATISFIED) {
struct sc_pkcs15_object *objs[0x10], *pin_obj = NULL;
const struct sc_acl_entry *acl = sc_file_get_acl_entry(file, SC_AC_OP_READ);
int ii;
rv = sc_pkcs15_get_objects(p15card, SC_PKCS15_TYPE_AUTH_PIN, objs, 0x10);
if (rv != SC_SUCCESS) {
sc_file_free(file);
LOG_TEST_RET(ctx, rv, "Cannot read oberthur file: get AUTH objects error");
}
for (ii=0; ii<rv; ii++) {
struct sc_pkcs15_auth_info *auth_info = (struct sc_pkcs15_auth_info *) objs[ii]->data;
sc_log(ctx, "compare PIN/ACL refs:%i/%i, method:%i/%i",
auth_info->attrs.pin.reference, acl->key_ref, auth_info->auth_method, acl->method);
if (auth_info->attrs.pin.reference == (int)acl->key_ref && auth_info->auth_method == (unsigned)acl->method) {
pin_obj = objs[ii];
break;
}
}
if (!pin_obj || !pin_obj->content.value) {
rv = SC_ERROR_SECURITY_STATUS_NOT_SATISFIED;
}
else {
rv = sc_pkcs15_verify_pin(p15card, pin_obj, pin_obj->content.value, pin_obj->content.len);
if (!rv)
rv = sc_oberthur_read_file(p15card, in_path, out, out_len, 0);
}
};
sc_file_free(file);
if (rv < 0) {
free(*out);
*out = NULL;
*out_len = 0;
}
*out_len = sz;
LOG_FUNC_RETURN(ctx, rv);
} | {
"deleted": [
{
"line_no": 43,
"char_start": 1107,
"char_end": 1118,
"line": "\t\tint rec;\n"
},
{
"line_no": 44,
"char_start": 1118,
"char_end": 1134,
"line": "\t\tint offs = 0;\n"
},
{
"line_no": 45,
"char_start": 1134,
"char_end": 1171,
"line": "\t\tint rec_len = file->record_length;\n"
}
],
"added": [
{
"line_no": 43,
"char_start": 1107,
"char_end": 1121,
"line": "\t\tsize_t rec;\n"
},
{
"line_no": 44,
"char_start": 1121,
"char_end": 1140,
"line": "\t\tsize_t offs = 0;\n"
},
{
"line_no": 45,
"char_start": 1140,
"char_end": 1180,
"line": "\t\tsize_t rec_len = file->record_length;\n"
},
{
"line_no": 48,
"char_start": 1210,
"char_end": 1245,
"line": "\t\t\tif (rec > file->record_count) {\n"
},
{
"line_no": 49,
"char_start": 1245,
"char_end": 1257,
"line": "\t\t\t\trv = 0;\n"
},
{
"line_no": 50,
"char_start": 1257,
"char_end": 1268,
"line": "\t\t\t\tbreak;\n"
},
{
"line_no": 51,
"char_start": 1268,
"char_end": 1273,
"line": "\t\t\t}\n"
}
]
} | {
"deleted": [
{
"char_start": 1110,
"char_end": 1111,
"chars": "n"
},
{
"char_start": 1121,
"char_end": 1122,
"chars": "n"
},
{
"char_start": 1137,
"char_end": 1138,
"chars": "n"
}
],
"added": [
{
"char_start": 1109,
"char_end": 1110,
"chars": "s"
},
{
"char_start": 1111,
"char_end": 1114,
"chars": "ze_"
},
{
"char_start": 1123,
"char_end": 1124,
"chars": "s"
},
{
"char_start": 1125,
"char_end": 1128,
"chars": "ze_"
},
{
"char_start": 1142,
"char_end": 1143,
"chars": "s"
},
{
"char_start": 1144,
"char_end": 1147,
"chars": "ze_"
},
{
"char_start": 1209,
"char_end": 1272,
"chars": "\n\t\t\tif (rec > file->record_count) {\n\t\t\t\trv = 0;\n\t\t\t\tbreak;\n\t\t\t}"
}
]
} | github.com/OpenSC/OpenSC/commit/6903aebfddc466d966c7b865fae34572bf3ed23e | src/libopensc/pkcs15-oberthur.c | cwe-787 |
tflite::ops::builtin::segment_sum::ResizeOutputTensor | TfLiteStatus ResizeOutputTensor(TfLiteContext* context,
const TfLiteTensor* data,
const TfLiteTensor* segment_ids,
TfLiteTensor* output) {
int max_index = -1;
const int segment_id_size = segment_ids->dims->data[0];
if (segment_id_size > 0) {
max_index = segment_ids->data.i32[segment_id_size - 1];
}
const int data_rank = NumDimensions(data);
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));
output_shape->data[0] = max_index + 1;
for (int i = 1; i < data_rank; ++i) {
output_shape->data[i] = data->dims->data[i];
}
return context->ResizeTensor(context, output, output_shape);
} | TfLiteStatus ResizeOutputTensor(TfLiteContext* context,
const TfLiteTensor* data,
const TfLiteTensor* segment_ids,
TfLiteTensor* output) {
// Segment ids should be of same cardinality as first input dimension and they
// should be increasing by at most 1, from 0 (e.g., [0, 0, 1, 2, 3] is valid)
const int segment_id_size = segment_ids->dims->data[0];
TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);
int previous_segment_id = -1;
for (int i = 0; i < segment_id_size; i++) {
const int current_segment_id = GetTensorData<int32_t>(segment_ids)[i];
if (i == 0) {
TF_LITE_ENSURE_EQ(context, current_segment_id, 0);
} else {
int delta = current_segment_id - previous_segment_id;
TF_LITE_ENSURE(context, delta == 0 || delta == 1);
}
previous_segment_id = current_segment_id;
}
const int max_index = previous_segment_id;
const int data_rank = NumDimensions(data);
TfLiteIntArray* output_shape = TfLiteIntArrayCreate(NumDimensions(data));
output_shape->data[0] = max_index + 1;
for (int i = 1; i < data_rank; ++i) {
output_shape->data[i] = data->dims->data[i];
}
return context->ResizeTensor(context, output, output_shape);
} | {
"deleted": [
{
"line_no": 5,
"char_start": 235,
"char_end": 257,
"line": " int max_index = -1;\n"
},
{
"line_no": 7,
"char_start": 315,
"char_end": 344,
"line": " if (segment_id_size > 0) {\n"
},
{
"line_no": 8,
"char_start": 344,
"char_end": 404,
"line": " max_index = segment_ids->data.i32[segment_id_size - 1];\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 454,
"char_end": 522,
"line": " TF_LITE_ENSURE_EQ(context, segment_id_size, data->dims->data[0]);\n"
},
{
"line_no": 9,
"char_start": 522,
"char_end": 554,
"line": " int previous_segment_id = -1;\n"
},
{
"line_no": 10,
"char_start": 554,
"char_end": 600,
"line": " for (int i = 0; i < segment_id_size; i++) {\n"
},
{
"line_no": 11,
"char_start": 600,
"char_end": 675,
"line": " const int current_segment_id = GetTensorData<int32_t>(segment_ids)[i];\n"
},
{
"line_no": 12,
"char_start": 675,
"char_end": 693,
"line": " if (i == 0) {\n"
},
{
"line_no": 13,
"char_start": 693,
"char_end": 750,
"line": " TF_LITE_ENSURE_EQ(context, current_segment_id, 0);\n"
},
{
"line_no": 14,
"char_start": 750,
"char_end": 763,
"line": " } else {\n"
},
{
"line_no": 15,
"char_start": 763,
"char_end": 823,
"line": " int delta = current_segment_id - previous_segment_id;\n"
},
{
"line_no": 16,
"char_start": 823,
"char_end": 880,
"line": " TF_LITE_ENSURE(context, delta == 0 || delta == 1);\n"
},
{
"line_no": 17,
"char_start": 880,
"char_end": 886,
"line": " }\n"
},
{
"line_no": 18,
"char_start": 886,
"char_end": 932,
"line": " previous_segment_id = current_segment_id;\n"
},
{
"line_no": 20,
"char_start": 936,
"char_end": 937,
"line": "\n"
},
{
"line_no": 21,
"char_start": 937,
"char_end": 982,
"line": " const int max_index = previous_segment_id;\n"
},
{
"line_no": 22,
"char_start": 982,
"char_end": 983,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 237,
"char_end": 238,
"chars": "i"
},
{
"char_start": 243,
"char_end": 245,
"chars": "x_"
},
{
"char_start": 249,
"char_end": 250,
"chars": "x"
},
{
"char_start": 251,
"char_end": 252,
"chars": "="
},
{
"char_start": 253,
"char_end": 254,
"chars": "-"
},
{
"char_start": 255,
"char_end": 256,
"chars": ";"
},
{
"char_start": 349,
"char_end": 351,
"chars": "ax"
},
{
"char_start": 356,
"char_end": 357,
"chars": "x"
},
{
"char_start": 371,
"char_end": 373,
"chars": "->"
},
{
"char_start": 377,
"char_end": 378,
"chars": "."
},
{
"char_start": 379,
"char_end": 382,
"chars": "32["
},
{
"char_start": 395,
"char_end": 396,
"chars": "z"
},
{
"char_start": 398,
"char_end": 399,
"chars": "-"
},
{
"char_start": 400,
"char_end": 402,
"chars": "1]"
},
{
"char_start": 404,
"char_end": 407,
"chars": " }"
}
],
"added": [
{
"char_start": 237,
"char_end": 274,
"chars": "// Segment ids should be of same card"
},
{
"char_start": 276,
"char_end": 279,
"chars": "ali"
},
{
"char_start": 280,
"char_end": 284,
"chars": "y as"
},
{
"char_start": 285,
"char_end": 299,
"chars": "first input di"
},
{
"char_start": 300,
"char_end": 307,
"chars": "ension "
},
{
"char_start": 308,
"char_end": 338,
"chars": "nd they\n // should be increas"
},
{
"char_start": 340,
"char_end": 364,
"chars": "g by at most 1, from 0 ("
},
{
"char_start": 365,
"char_end": 369,
"chars": ".g.,"
},
{
"char_start": 370,
"char_end": 373,
"chars": "[0,"
},
{
"char_start": 374,
"char_end": 377,
"chars": "0, "
},
{
"char_start": 378,
"char_end": 395,
"chars": ", 2, 3] is valid)"
},
{
"char_start": 456,
"char_end": 491,
"chars": "TF_LITE_ENSURE_EQ(context, segment_"
},
{
"char_start": 492,
"char_end": 556,
"chars": "d_size, data->dims->data[0]);\n int previous_segment_id = -1;\n "
},
{
"char_start": 557,
"char_end": 559,
"chars": "or"
},
{
"char_start": 561,
"char_end": 576,
"chars": "int i = 0; i < "
},
{
"char_start": 591,
"char_end": 592,
"chars": ";"
},
{
"char_start": 593,
"char_end": 656,
"chars": "i++) {\n const int current_segment_id = GetTensorData<int32_t"
},
{
"char_start": 657,
"char_end": 687,
"chars": "(segment_ids)[i];\n if (i =="
},
{
"char_start": 697,
"char_end": 722,
"chars": " TF_LITE_ENSURE_EQ(conte"
},
{
"char_start": 723,
"char_end": 741,
"chars": "t, current_segment"
},
{
"char_start": 743,
"char_end": 770,
"chars": "d, 0);\n } else {\n i"
},
{
"char_start": 771,
"char_end": 773,
"chars": "t "
},
{
"char_start": 775,
"char_end": 778,
"chars": "lta"
},
{
"char_start": 781,
"char_end": 789,
"chars": "current_"
},
{
"char_start": 799,
"char_end": 809,
"chars": " - previou"
},
{
"char_start": 810,
"char_end": 820,
"chars": "_segment_i"
},
{
"char_start": 821,
"char_end": 857,
"chars": ";\n TF_LITE_ENSURE(context, delt"
},
{
"char_start": 858,
"char_end": 870,
"chars": " == 0 || del"
},
{
"char_start": 872,
"char_end": 894,
"chars": " == 1);\n }\n prev"
},
{
"char_start": 895,
"char_end": 899,
"chars": "ous_"
},
{
"char_start": 909,
"char_end": 919,
"chars": " = current"
},
{
"char_start": 922,
"char_end": 930,
"chars": "gment_id"
},
{
"char_start": 935,
"char_end": 982,
"chars": "\n\n const int max_index = previous_segment_id;\n"
}
]
} | github.com/tensorflow/tensorflow/commit/204945b19e44b57906c9344c0d00120eeeae178a | tensorflow/lite/kernels/segment_sum.cc | cwe-787 |
mwifiex_ret_wmm_get_status | int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,
const struct host_cmd_ds_command *resp)
{
u8 *curr = (u8 *) &resp->params.get_wmm_status;
uint16_t resp_len = le16_to_cpu(resp->size), tlv_len;
int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK;
bool valid = true;
struct mwifiex_ie_types_data *tlv_hdr;
struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus;
struct ieee_types_wmm_parameter *wmm_param_ie = NULL;
struct mwifiex_wmm_ac_status *ac_status;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: WMM_GET_STATUS cmdresp received: %d\n",
resp_len);
while ((resp_len >= sizeof(tlv_hdr->header)) && valid) {
tlv_hdr = (struct mwifiex_ie_types_data *) curr;
tlv_len = le16_to_cpu(tlv_hdr->header.len);
if (resp_len < tlv_len + sizeof(tlv_hdr->header))
break;
switch (le16_to_cpu(tlv_hdr->header.type)) {
case TLV_TYPE_WMMQSTATUS:
tlv_wmm_qstatus =
(struct mwifiex_ie_types_wmm_queue_status *)
tlv_hdr;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"QSTATUS TLV: %d, %d, %d\n",
tlv_wmm_qstatus->queue_index,
tlv_wmm_qstatus->flow_required,
tlv_wmm_qstatus->disabled);
ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus->
queue_index];
ac_status->disabled = tlv_wmm_qstatus->disabled;
ac_status->flow_required =
tlv_wmm_qstatus->flow_required;
ac_status->flow_created = tlv_wmm_qstatus->flow_created;
break;
case WLAN_EID_VENDOR_SPECIFIC:
/*
* Point the regular IEEE IE 2 bytes into the Marvell IE
* and setup the IEEE IE type and length byte fields
*/
wmm_param_ie =
(struct ieee_types_wmm_parameter *) (curr +
2);
wmm_param_ie->vend_hdr.len = (u8) tlv_len;
wmm_param_ie->vend_hdr.element_id =
WLAN_EID_VENDOR_SPECIFIC;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"WMM Parameter Set Count: %d\n",
wmm_param_ie->qos_info_bitmap & mask);
memcpy((u8 *) &priv->curr_bss_params.bss_descriptor.
wmm_ie, wmm_param_ie,
wmm_param_ie->vend_hdr.len + 2);
break;
default:
valid = false;
break;
}
curr += (tlv_len + sizeof(tlv_hdr->header));
resp_len -= (tlv_len + sizeof(tlv_hdr->header));
}
mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie);
mwifiex_wmm_setup_ac_downgrade(priv);
return 0;
} | int mwifiex_ret_wmm_get_status(struct mwifiex_private *priv,
const struct host_cmd_ds_command *resp)
{
u8 *curr = (u8 *) &resp->params.get_wmm_status;
uint16_t resp_len = le16_to_cpu(resp->size), tlv_len;
int mask = IEEE80211_WMM_IE_AP_QOSINFO_PARAM_SET_CNT_MASK;
bool valid = true;
struct mwifiex_ie_types_data *tlv_hdr;
struct mwifiex_ie_types_wmm_queue_status *tlv_wmm_qstatus;
struct ieee_types_wmm_parameter *wmm_param_ie = NULL;
struct mwifiex_wmm_ac_status *ac_status;
mwifiex_dbg(priv->adapter, INFO,
"info: WMM: WMM_GET_STATUS cmdresp received: %d\n",
resp_len);
while ((resp_len >= sizeof(tlv_hdr->header)) && valid) {
tlv_hdr = (struct mwifiex_ie_types_data *) curr;
tlv_len = le16_to_cpu(tlv_hdr->header.len);
if (resp_len < tlv_len + sizeof(tlv_hdr->header))
break;
switch (le16_to_cpu(tlv_hdr->header.type)) {
case TLV_TYPE_WMMQSTATUS:
tlv_wmm_qstatus =
(struct mwifiex_ie_types_wmm_queue_status *)
tlv_hdr;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"QSTATUS TLV: %d, %d, %d\n",
tlv_wmm_qstatus->queue_index,
tlv_wmm_qstatus->flow_required,
tlv_wmm_qstatus->disabled);
ac_status = &priv->wmm.ac_status[tlv_wmm_qstatus->
queue_index];
ac_status->disabled = tlv_wmm_qstatus->disabled;
ac_status->flow_required =
tlv_wmm_qstatus->flow_required;
ac_status->flow_created = tlv_wmm_qstatus->flow_created;
break;
case WLAN_EID_VENDOR_SPECIFIC:
/*
* Point the regular IEEE IE 2 bytes into the Marvell IE
* and setup the IEEE IE type and length byte fields
*/
wmm_param_ie =
(struct ieee_types_wmm_parameter *) (curr +
2);
wmm_param_ie->vend_hdr.len = (u8) tlv_len;
wmm_param_ie->vend_hdr.element_id =
WLAN_EID_VENDOR_SPECIFIC;
mwifiex_dbg(priv->adapter, CMD,
"info: CMD_RESP: WMM_GET_STATUS:\t"
"WMM Parameter Set Count: %d\n",
wmm_param_ie->qos_info_bitmap & mask);
if (wmm_param_ie->vend_hdr.len + 2 >
sizeof(struct ieee_types_wmm_parameter))
break;
memcpy((u8 *) &priv->curr_bss_params.bss_descriptor.
wmm_ie, wmm_param_ie,
wmm_param_ie->vend_hdr.len + 2);
break;
default:
valid = false;
break;
}
curr += (tlv_len + sizeof(tlv_hdr->header));
resp_len -= (tlv_len + sizeof(tlv_hdr->header));
}
mwifiex_wmm_setup_queue_priorities(priv, wmm_param_ie);
mwifiex_wmm_setup_ac_downgrade(priv);
return 0;
} | {
"deleted": [],
"added": [
{
"line_no": 63,
"char_start": 2014,
"char_end": 2054,
"line": "\t\t\tif (wmm_param_ie->vend_hdr.len + 2 >\n"
},
{
"line_no": 64,
"char_start": 2054,
"char_end": 2099,
"line": "\t\t\t\tsizeof(struct ieee_types_wmm_parameter))\n"
},
{
"line_no": 65,
"char_start": 2099,
"char_end": 2110,
"line": "\t\t\t\tbreak;\n"
},
{
"line_no": 66,
"char_start": 2110,
"char_end": 2111,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2017,
"char_end": 2114,
"chars": "if (wmm_param_ie->vend_hdr.len + 2 >\n\t\t\t\tsizeof(struct ieee_types_wmm_parameter))\n\t\t\t\tbreak;\n\n\t\t\t"
}
]
} | github.com/torvalds/linux/commit/3a9b153c5591548612c3955c9600a98150c81875 | drivers/net/wireless/marvell/mwifiex/wmm.c | cwe-787 |
patch | static PyObject* patch(PyObject* self, PyObject* args)
{
char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr;
Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength;
PyObject *controlTuples, *tuple, *results;
off_t oldpos, newpos, x, y, z;
int i, j, numTuples;
if (!PyArg_ParseTuple(args, "s#nO!s#s#",
&origData, &origDataLength, &newDataLength,
&PyList_Type, &controlTuples,
&diffBlock, &diffBlockLength,
&extraBlock, &extraBlockLength))
return NULL;
/* allocate the memory for the new data */
newData = PyMem_Malloc(newDataLength + 1);
if (!newData)
return PyErr_NoMemory();
oldpos = 0;
newpos = 0;
diffPtr = diffBlock;
extraPtr = extraBlock;
numTuples = PyList_GET_SIZE(controlTuples);
for (i = 0; i < numTuples; i++) {
tuple = PyList_GET_ITEM(controlTuples, i);
if (!PyTuple_Check(tuple)) {
PyMem_Free(newData);
PyErr_SetString(PyExc_TypeError, "expecting tuple");
return NULL;
}
if (PyTuple_GET_SIZE(tuple) != 3) {
PyMem_Free(newData);
PyErr_SetString(PyExc_TypeError, "expecting tuple of size 3");
return NULL;
}
x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));
y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));
z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2));
if (newpos + x > newDataLength ||
diffPtr + x > diffBlock + diffBlockLength ||
extraPtr + y > extraBlock + extraBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)");
return NULL;
}
memcpy(newData + newpos, diffPtr, x);
diffPtr += x;
for (j = 0; j < x; j++)
if ((oldpos + j >= 0) && (oldpos + j < origDataLength))
newData[newpos + j] += origData[oldpos + j];
newpos += x;
oldpos += x;
memcpy(newData + newpos, extraPtr, y);
extraPtr += y;
newpos += y;
oldpos += z;
}
/* confirm that a valid patch was applied */
if (newpos != newDataLength ||
diffPtr != diffBlock + diffBlockLength ||
extraPtr != extraBlock + extraBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (underflow)");
return NULL;
}
results = PyBytes_FromStringAndSize(newData, newDataLength);
PyMem_Free(newData);
return results;
} | static PyObject* patch(PyObject* self, PyObject* args)
{
char *origData, *newData, *diffBlock, *extraBlock, *diffPtr, *extraPtr;
Py_ssize_t origDataLength, newDataLength, diffBlockLength, extraBlockLength;
PyObject *controlTuples, *tuple, *results;
off_t oldpos, newpos, x, y, z;
int i, j, numTuples;
if (!PyArg_ParseTuple(args, "s#nO!s#s#",
&origData, &origDataLength, &newDataLength,
&PyList_Type, &controlTuples,
&diffBlock, &diffBlockLength,
&extraBlock, &extraBlockLength))
return NULL;
/* allocate the memory for the new data */
newData = PyMem_Malloc(newDataLength + 1);
if (!newData)
return PyErr_NoMemory();
oldpos = 0;
newpos = 0;
diffPtr = diffBlock;
extraPtr = extraBlock;
numTuples = PyList_GET_SIZE(controlTuples);
for (i = 0; i < numTuples; i++) {
tuple = PyList_GET_ITEM(controlTuples, i);
if (!PyTuple_Check(tuple)) {
PyMem_Free(newData);
PyErr_SetString(PyExc_TypeError, "expecting tuple");
return NULL;
}
if (PyTuple_GET_SIZE(tuple) != 3) {
PyMem_Free(newData);
PyErr_SetString(PyExc_TypeError, "expecting tuple of size 3");
return NULL;
}
x = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 0));
y = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 1));
z = PyLong_AsLong(PyTuple_GET_ITEM(tuple, 2));
if (newpos + x > newDataLength ||
diffPtr + x > diffBlock + diffBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)");
return NULL;
}
memcpy(newData + newpos, diffPtr, x);
diffPtr += x;
for (j = 0; j < x; j++)
if ((oldpos + j >= 0) && (oldpos + j < origDataLength))
newData[newpos + j] += origData[oldpos + j];
newpos += x;
oldpos += x;
if (newpos + y > newDataLength ||
extraPtr + y > extraBlock + extraBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (overflow)");
return NULL;
}
memcpy(newData + newpos, extraPtr, y);
extraPtr += y;
newpos += y;
oldpos += z;
}
/* confirm that a valid patch was applied */
if (newpos != newDataLength ||
diffPtr != diffBlock + diffBlockLength ||
extraPtr != extraBlock + extraBlockLength) {
PyMem_Free(newData);
PyErr_SetString(PyExc_ValueError, "corrupt patch (underflow)");
return NULL;
}
results = PyBytes_FromStringAndSize(newData, newDataLength);
PyMem_Free(newData);
return results;
} | {
"deleted": [
{
"line_no": 42,
"char_start": 1561,
"char_end": 1622,
"line": " diffPtr + x > diffBlock + diffBlockLength ||\n"
},
{
"line_no": 43,
"char_start": 1622,
"char_end": 1686,
"line": " extraPtr + y > extraBlock + extraBlockLength) {\n"
}
],
"added": [
{
"line_no": 42,
"char_start": 1561,
"char_end": 1622,
"line": " diffPtr + x > diffBlock + diffBlockLength) {\n"
},
{
"line_no": 54,
"char_start": 2036,
"char_end": 2078,
"line": " if (newpos + y > newDataLength ||\n"
},
{
"line_no": 55,
"char_start": 2078,
"char_end": 2142,
"line": " extraPtr + y > extraBlock + extraBlockLength) {\n"
},
{
"line_no": 56,
"char_start": 2142,
"char_end": 2175,
"line": " PyMem_Free(newData);\n"
},
{
"line_no": 57,
"char_start": 2175,
"char_end": 2250,
"line": " PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n"
},
{
"line_no": 58,
"char_start": 2250,
"char_end": 2275,
"line": " return NULL;\n"
},
{
"line_no": 59,
"char_start": 2275,
"char_end": 2285,
"line": " }\n"
}
]
} | {
"deleted": [
{
"char_start": 1618,
"char_end": 1682,
"chars": " ||\n extraPtr + y > extraBlock + extraBlockLength"
}
],
"added": [
{
"char_start": 2035,
"char_end": 2284,
"chars": "\n if (newpos + y > newDataLength ||\n extraPtr + y > extraBlock + extraBlockLength) {\n PyMem_Free(newData);\n PyErr_SetString(PyExc_ValueError, \"corrupt patch (overflow)\");\n return NULL;\n }"
}
]
} | github.com/ilanschnell/bsdiff4/commit/49a4cee2feef7deaf9d89e5e793a8824930284d7 | bsdiff4/core.c | cwe-787 |
HandleRFBServerMessage | HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
if (msg.sct.length > 1<<20) {
rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length);
return FALSE;
}
buffer = malloc((uint64_t)msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {
free(buffer);
return FALSE;
}
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
} | HandleRFBServerMessage(rfbClient* client)
{
rfbServerToClientMsg msg;
if (client->serverPort==-1)
client->vncRec->readTimestamp = TRUE;
if (!ReadFromRFBServer(client, (char *)&msg, 1))
return FALSE;
switch (msg.type) {
case rfbSetColourMapEntries:
{
/* TODO:
int i;
uint16_t rgb[3];
XColor xc;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbSetColourMapEntriesMsg - 1))
return FALSE;
msg.scme.firstColour = rfbClientSwap16IfLE(msg.scme.firstColour);
msg.scme.nColours = rfbClientSwap16IfLE(msg.scme.nColours);
for (i = 0; i < msg.scme.nColours; i++) {
if (!ReadFromRFBServer(client, (char *)rgb, 6))
return FALSE;
xc.pixel = msg.scme.firstColour + i;
xc.red = rfbClientSwap16IfLE(rgb[0]);
xc.green = rfbClientSwap16IfLE(rgb[1]);
xc.blue = rfbClientSwap16IfLE(rgb[2]);
xc.flags = DoRed|DoGreen|DoBlue;
XStoreColor(dpy, cmap, &xc);
}
*/
break;
}
case rfbFramebufferUpdate:
{
rfbFramebufferUpdateRectHeader rect;
int linesToRead;
int bytesPerLine;
int i;
if (!ReadFromRFBServer(client, ((char *)&msg.fu) + 1,
sz_rfbFramebufferUpdateMsg - 1))
return FALSE;
msg.fu.nRects = rfbClientSwap16IfLE(msg.fu.nRects);
for (i = 0; i < msg.fu.nRects; i++) {
if (!ReadFromRFBServer(client, (char *)&rect, sz_rfbFramebufferUpdateRectHeader))
return FALSE;
rect.encoding = rfbClientSwap32IfLE(rect.encoding);
if (rect.encoding == rfbEncodingLastRect)
break;
rect.r.x = rfbClientSwap16IfLE(rect.r.x);
rect.r.y = rfbClientSwap16IfLE(rect.r.y);
rect.r.w = rfbClientSwap16IfLE(rect.r.w);
rect.r.h = rfbClientSwap16IfLE(rect.r.h);
if (rect.encoding == rfbEncodingXCursor ||
rect.encoding == rfbEncodingRichCursor) {
if (!HandleCursorShape(client,
rect.r.x, rect.r.y, rect.r.w, rect.r.h,
rect.encoding)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingPointerPos) {
if (!client->HandleCursorPos(client,rect.r.x, rect.r.y)) {
return FALSE;
}
continue;
}
if (rect.encoding == rfbEncodingKeyboardLedState) {
/* OK! We have received a keyboard state message!!! */
client->KeyboardLedStateEnabled = 1;
if (client->HandleKeyboardLedState!=NULL)
client->HandleKeyboardLedState(client, rect.r.x, 0);
/* stash it for the future */
client->CurrentKeyboardLedState = rect.r.x;
continue;
}
if (rect.encoding == rfbEncodingNewFBSize) {
client->width = rect.r.w;
client->height = rect.r.h;
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, rect.r.w, rect.r.h, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", rect.r.w, rect.r.h);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingSupportedMessages) {
int loop;
if (!ReadFromRFBServer(client, (char *)&client->supportedMessages, sz_rfbSupportedMessages))
return FALSE;
/* msgs is two sets of bit flags of supported messages client2server[] and server2client[] */
/* currently ignored by this library */
rfbClientLog("client2server supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.client2server[loop], client->supportedMessages.client2server[loop+1],
client->supportedMessages.client2server[loop+2], client->supportedMessages.client2server[loop+3],
client->supportedMessages.client2server[loop+4], client->supportedMessages.client2server[loop+5],
client->supportedMessages.client2server[loop+6], client->supportedMessages.client2server[loop+7]);
rfbClientLog("server2client supported messages (bit flags)\n");
for (loop=0;loop<32;loop+=8)
rfbClientLog("%02X: %04x %04x %04x %04x - %04x %04x %04x %04x\n", loop,
client->supportedMessages.server2client[loop], client->supportedMessages.server2client[loop+1],
client->supportedMessages.server2client[loop+2], client->supportedMessages.server2client[loop+3],
client->supportedMessages.server2client[loop+4], client->supportedMessages.server2client[loop+5],
client->supportedMessages.server2client[loop+6], client->supportedMessages.server2client[loop+7]);
continue;
}
/* rect.r.w=byte count, rect.r.h=# of encodings */
if (rect.encoding == rfbEncodingSupportedEncodings) {
char *buffer;
buffer = malloc(rect.r.w);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
/* buffer now contains rect.r.h # of uint32_t encodings that the server supports */
/* currently ignored by this library */
free(buffer);
continue;
}
/* rect.r.w=byte count */
if (rect.encoding == rfbEncodingServerIdentity) {
char *buffer;
buffer = malloc(rect.r.w+1);
if (!ReadFromRFBServer(client, buffer, rect.r.w))
{
free(buffer);
return FALSE;
}
buffer[rect.r.w]=0; /* null terminate, just in case */
rfbClientLog("Connected to Server \"%s\"\n", buffer);
free(buffer);
continue;
}
/* rfbEncodingUltraZip is a collection of subrects. x = # of subrects, and h is always 0 */
if (rect.encoding != rfbEncodingUltraZip)
{
if ((rect.r.x + rect.r.w > client->width) ||
(rect.r.y + rect.r.h > client->height))
{
rfbClientLog("Rect too large: %dx%d at (%d, %d)\n",
rect.r.w, rect.r.h, rect.r.x, rect.r.y);
return FALSE;
}
/* UltraVNC with scaling, will send rectangles with a zero W or H
*
if ((rect.encoding != rfbEncodingTight) &&
(rect.r.h * rect.r.w == 0))
{
rfbClientLog("Zero size rect - ignoring (encoding=%d (0x%08x) %dx, %dy, %dw, %dh)\n", rect.encoding, rect.encoding, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
continue;
}
*/
/* If RichCursor encoding is used, we should prevent collisions
between framebuffer updates and cursor drawing operations. */
client->SoftCursorLockArea(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
switch (rect.encoding) {
case rfbEncodingRaw: {
int y=rect.r.y, h=rect.r.h;
bytesPerLine = rect.r.w * client->format.bitsPerPixel / 8;
/* RealVNC 4.x-5.x on OSX can induce bytesPerLine==0,
usually during GPU accel. */
/* Regardless of cause, do not divide by zero. */
linesToRead = bytesPerLine ? (RFB_BUFFER_SIZE / bytesPerLine) : 0;
while (linesToRead && h > 0) {
if (linesToRead > h)
linesToRead = h;
if (!ReadFromRFBServer(client, client->buffer,bytesPerLine * linesToRead))
return FALSE;
client->GotBitmap(client, (uint8_t *)client->buffer,
rect.r.x, y, rect.r.w,linesToRead);
h -= linesToRead;
y += linesToRead;
}
break;
}
case rfbEncodingCopyRect:
{
rfbCopyRect cr;
if (!ReadFromRFBServer(client, (char *)&cr, sz_rfbCopyRect))
return FALSE;
cr.srcX = rfbClientSwap16IfLE(cr.srcX);
cr.srcY = rfbClientSwap16IfLE(cr.srcY);
/* If RichCursor encoding is used, we should extend our
"cursor lock area" (previously set to destination
rectangle) to the source rectangle as well. */
client->SoftCursorLockArea(client,
cr.srcX, cr.srcY, rect.r.w, rect.r.h);
client->GotCopyRect(client, cr.srcX, cr.srcY, rect.r.w, rect.r.h,
rect.r.x, rect.r.y);
break;
}
case rfbEncodingRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingCoRRE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleCoRRE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleCoRRE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleCoRRE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingHextile:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleHextile8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleHextile16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleHextile32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltra:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltra8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltra16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltra32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingUltraZip:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleUltraZip8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleUltraZip16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleUltraZip32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
case rfbEncodingTRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTRLE8(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleTRLE16(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else {
if (!HandleTRLE15(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
}
break;
case 32: {
uint32_t maxColor =
(client->format.redMax << client->format.redShift) |
(client->format.greenMax << client->format.greenShift) |
(client->format.blueMax << client->format.blueShift);
if ((client->format.bigEndian && (maxColor & 0xff) == 0) ||
(!client->format.bigEndian && (maxColor & 0xff000000) == 0)) {
if (!HandleTRLE24(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor & 0xff) == 0) {
if (!HandleTRLE24Up(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor & 0xff000000) == 0) {
if (!HandleTRLE24Down(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
} else if (!HandleTRLE32(client, rect.r.x, rect.r.y, rect.r.w,
rect.r.h))
return FALSE;
break;
}
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBZ
case rfbEncodingZlib:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZlib8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleZlib16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleZlib32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#ifdef LIBVNCSERVER_HAVE_LIBJPEG
case rfbEncodingTight:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleTight8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (!HandleTight16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 32:
if (!HandleTight32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
break;
}
#endif
case rfbEncodingZRLE:
/* Fail safe for ZYWRLE unsupport VNC server. */
client->appData.qualityLevel = 9;
/* fall through */
case rfbEncodingZYWRLE:
{
switch (client->format.bitsPerPixel) {
case 8:
if (!HandleZRLE8(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
case 16:
if (client->si.format.greenMax > 0x1F) {
if (!HandleZRLE16(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else {
if (!HandleZRLE15(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
}
break;
case 32:
{
uint32_t maxColor=(client->format.redMax<<client->format.redShift)|
(client->format.greenMax<<client->format.greenShift)|
(client->format.blueMax<<client->format.blueShift);
if ((client->format.bigEndian && (maxColor&0xff)==0) ||
(!client->format.bigEndian && (maxColor&0xff000000)==0)) {
if (!HandleZRLE24(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!client->format.bigEndian && (maxColor&0xff)==0) {
if (!HandleZRLE24Up(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (client->format.bigEndian && (maxColor&0xff000000)==0) {
if (!HandleZRLE24Down(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
} else if (!HandleZRLE32(client, rect.r.x,rect.r.y,rect.r.w,rect.r.h))
return FALSE;
break;
}
}
break;
}
#endif
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleEncoding && e->handleEncoding(client, &rect))
handled = TRUE;
if(!handled) {
rfbClientLog("Unknown rect encoding %d\n",
(int)rect.encoding);
return FALSE;
}
}
}
/* Now we may discard "soft cursor locks". */
client->SoftCursorUnlockScreen(client);
client->GotFrameBufferUpdate(client, rect.r.x, rect.r.y, rect.r.w, rect.r.h);
}
if (!SendIncrementalFramebufferUpdateRequest(client))
return FALSE;
if (client->FinishedFrameBufferUpdate)
client->FinishedFrameBufferUpdate(client);
break;
}
case rfbBell:
{
client->Bell(client);
break;
}
case rfbServerCutText:
{
char *buffer;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbServerCutTextMsg - 1))
return FALSE;
msg.sct.length = rfbClientSwap32IfLE(msg.sct.length);
if (msg.sct.length > 1<<20) {
rfbClientErr("Ignoring too big cut text length sent by server: %u B > 1 MB\n", (unsigned int)msg.sct.length);
return FALSE;
}
buffer = malloc(msg.sct.length+1);
if (!ReadFromRFBServer(client, buffer, msg.sct.length)) {
free(buffer);
return FALSE;
}
buffer[msg.sct.length] = 0;
if (client->GotXCutText)
client->GotXCutText(client, buffer, msg.sct.length);
free(buffer);
break;
}
case rfbTextChat:
{
char *buffer=NULL;
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbTextChatMsg- 1))
return FALSE;
msg.tc.length = rfbClientSwap32IfLE(msg.sct.length);
switch(msg.tc.length) {
case rfbTextChatOpen:
rfbClientLog("Received TextChat Open\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatOpen, NULL);
break;
case rfbTextChatClose:
rfbClientLog("Received TextChat Close\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatClose, NULL);
break;
case rfbTextChatFinished:
rfbClientLog("Received TextChat Finished\n");
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)rfbTextChatFinished, NULL);
break;
default:
buffer=malloc(msg.tc.length+1);
if (!ReadFromRFBServer(client, buffer, msg.tc.length))
{
free(buffer);
return FALSE;
}
/* Null Terminate <just in case> */
buffer[msg.tc.length]=0;
rfbClientLog("Received TextChat \"%s\"\n", buffer);
if (client->HandleTextChat!=NULL)
client->HandleTextChat(client, (int)msg.tc.length, buffer);
free(buffer);
break;
}
break;
}
case rfbXvp:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbXvpMsg -1))
return FALSE;
SetClient2Server(client, rfbXvp);
/* technically, we only care what we can *send* to the server
* but, we set Server2Client Just in case it ever becomes useful
*/
SetServer2Client(client, rfbXvp);
if(client->HandleXvpMsg)
client->HandleXvpMsg(client, msg.xvp.version, msg.xvp.code);
break;
}
case rfbResizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbResizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.rsfb.framebufferWidth);
client->height = rfbClientSwap16IfLE(msg.rsfb.framebufferHeigth);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
case rfbPalmVNCReSizeFrameBuffer:
{
if (!ReadFromRFBServer(client, ((char *)&msg) + 1,
sz_rfbPalmVNCReSizeFrameBufferMsg -1))
return FALSE;
client->width = rfbClientSwap16IfLE(msg.prsfb.buffer_w);
client->height = rfbClientSwap16IfLE(msg.prsfb.buffer_h);
client->updateRect.x = client->updateRect.y = 0;
client->updateRect.w = client->width;
client->updateRect.h = client->height;
if (!client->MallocFrameBuffer(client))
return FALSE;
SendFramebufferUpdateRequest(client, 0, 0, client->width, client->height, FALSE);
rfbClientLog("Got new framebuffer size: %dx%d\n", client->width, client->height);
break;
}
default:
{
rfbBool handled = FALSE;
rfbClientProtocolExtension* e;
for(e = rfbClientExtensions; !handled && e; e = e->next)
if(e->handleMessage && e->handleMessage(client, &msg))
handled = TRUE;
if(!handled) {
char buffer[256];
rfbClientLog("Unknown message type %d from VNC server\n",msg.type);
ReadFromRFBServer(client, buffer, 256);
return FALSE;
}
}
}
return TRUE;
} | {
"deleted": [
{
"line_no": 517,
"char_start": 15578,
"char_end": 15627,
"line": " buffer = malloc((uint64_t)msg.sct.length+1);\n"
}
],
"added": [
{
"line_no": 517,
"char_start": 15578,
"char_end": 15617,
"line": " buffer = malloc(msg.sct.length+1);\n"
}
]
} | {
"deleted": [
{
"char_start": 15598,
"char_end": 15608,
"chars": "(uint64_t)"
}
],
"added": []
} | github.com/LibVNC/libvncserver/commit/a64c3b37af9a6c8f8009d7516874b8d266b42bae | libvncclient/rfbproto.c | cwe-787 |
enc_untrusted_create_wait_queue | int32_t *enc_untrusted_create_wait_queue() {
MessageWriter input;
MessageReader output;
input.Push<uint64_t>(sizeof(int32_t));
const auto status = NonSystemCallDispatcher(
::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);
CheckStatusAndParamCount(status, output, "enc_untrusted_create_wait_queue",
2);
int32_t *queue = reinterpret_cast<int32_t *>(output.next<uintptr_t>());
int klinux_errno = output.next<int>();
if (queue == nullptr) {
errno = FromkLinuxErrorNumber(klinux_errno);
}
enc_untrusted_disable_waiting(queue);
return queue;
} | int32_t *enc_untrusted_create_wait_queue() {
MessageWriter input;
MessageReader output;
input.Push<uint64_t>(sizeof(int32_t));
const auto status = NonSystemCallDispatcher(
::asylo::host_call::kLocalLifetimeAllocHandler, &input, &output);
CheckStatusAndParamCount(status, output, "enc_untrusted_create_wait_queue",
2);
int32_t *queue = reinterpret_cast<int32_t *>(output.next<uintptr_t>());
if (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {
TrustedPrimitives::BestEffortAbort(
"enc_untrusted_create_wait_queue: queue should be in untrusted memory");
}
int klinux_errno = output.next<int>();
if (queue == nullptr) {
errno = FromkLinuxErrorNumber(klinux_errno);
}
enc_untrusted_disable_waiting(queue);
return queue;
} | {
"deleted": [],
"added": [
{
"line_no": 10,
"char_start": 435,
"char_end": 505,
"line": " if (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {\n"
},
{
"line_no": 11,
"char_start": 505,
"char_end": 545,
"line": " TrustedPrimitives::BestEffortAbort(\n"
},
{
"line_no": 12,
"char_start": 545,
"char_end": 626,
"line": " \"enc_untrusted_create_wait_queue: queue should be in untrusted memory\");\n"
},
{
"line_no": 13,
"char_start": 626,
"char_end": 630,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 438,
"char_end": 633,
"chars": "f (!TrustedPrimitives::IsOutsideEnclave(queue, sizeof(int32_t))) {\n TrustedPrimitives::BestEffortAbort(\n \"enc_untrusted_create_wait_queue: queue should be in untrusted memory\");\n }\n i"
}
]
} | github.com/google/asylo/commit/a37fb6a0e7daf30134dbbf357c9a518a1026aa02 | asylo/platform/host_call/trusted/concurrency.cc | cwe-787 |
FromkLinuxSockAddr | bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,
socklen_t input_len, struct sockaddr *output,
socklen_t *output_len,
void (*abort_handler)(const char *)) {
if (!input || !output || !output_len || input_len == 0) {
output = nullptr;
return false;
}
int16_t klinux_family = input->klinux_sa_family;
if (klinux_family == kLinux_AF_UNIX) {
struct klinux_sockaddr_un *klinux_sockaddr_un_in =
const_cast<struct klinux_sockaddr_un *>(
reinterpret_cast<const struct klinux_sockaddr_un *>(input));
struct sockaddr_un sockaddr_un_out;
sockaddr_un_out.sun_family = AF_UNIX;
InitializeToZeroArray(sockaddr_un_out.sun_path);
ReinterpretCopyArray(
sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,
std::min(sizeof(sockaddr_un_out.sun_path),
sizeof(klinux_sockaddr_un_in->klinux_sun_path)));
CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);
} else if (klinux_family == kLinux_AF_INET) {
struct klinux_sockaddr_in *klinux_sockaddr_in_in =
const_cast<struct klinux_sockaddr_in *>(
reinterpret_cast<const struct klinux_sockaddr_in *>(input));
struct sockaddr_in sockaddr_in_out;
sockaddr_in_out.sin_family = AF_INET;
sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;
InitializeToZeroSingle(&sockaddr_in_out.sin_addr);
ReinterpretCopySingle(&sockaddr_in_out.sin_addr,
&klinux_sockaddr_in_in->klinux_sin_addr);
InitializeToZeroArray(sockaddr_in_out.sin_zero);
ReinterpretCopyArray(sockaddr_in_out.sin_zero,
klinux_sockaddr_in_in->klinux_sin_zero);
CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);
} else if (klinux_family == kLinux_AF_INET6) {
struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =
const_cast<struct klinux_sockaddr_in6 *>(
reinterpret_cast<const struct klinux_sockaddr_in6 *>(input));
struct sockaddr_in6 sockaddr_in6_out;
sockaddr_in6_out.sin6_family = AF_INET6;
sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;
sockaddr_in6_out.sin6_flowinfo =
klinux_sockaddr_in6_in->klinux_sin6_flowinfo;
sockaddr_in6_out.sin6_scope_id =
klinux_sockaddr_in6_in->klinux_sin6_scope_id;
InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);
ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,
&klinux_sockaddr_in6_in->klinux_sin6_addr);
CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,
output_len);
} else if (klinux_family == kLinux_AF_UNSPEC) {
output = nullptr;
*output_len = 0;
} else {
if (abort_handler != nullptr) {
std::string message = absl::StrCat(
"Type conversion error - Unsupported AF family: ", klinux_family);
abort_handler(message.c_str());
} else {
abort();
}
}
return true;
} | bool FromkLinuxSockAddr(const struct klinux_sockaddr *input,
socklen_t input_len, struct sockaddr *output,
socklen_t *output_len,
void (*abort_handler)(const char *)) {
if (!input || !output || !output_len || input_len == 0) {
output = nullptr;
return false;
}
int16_t klinux_family = input->klinux_sa_family;
if (klinux_family == kLinux_AF_UNIX) {
if (input_len < sizeof(struct klinux_sockaddr_un)) {
return false;
}
struct klinux_sockaddr_un *klinux_sockaddr_un_in =
const_cast<struct klinux_sockaddr_un *>(
reinterpret_cast<const struct klinux_sockaddr_un *>(input));
struct sockaddr_un sockaddr_un_out;
sockaddr_un_out.sun_family = AF_UNIX;
InitializeToZeroArray(sockaddr_un_out.sun_path);
ReinterpretCopyArray(
sockaddr_un_out.sun_path, klinux_sockaddr_un_in->klinux_sun_path,
std::min(sizeof(sockaddr_un_out.sun_path),
sizeof(klinux_sockaddr_un_in->klinux_sun_path)));
CopySockaddr(&sockaddr_un_out, sizeof(sockaddr_un_out), output, output_len);
} else if (klinux_family == kLinux_AF_INET) {
if (input_len < sizeof(struct klinux_sockaddr_in)) {
return false;
}
struct klinux_sockaddr_in *klinux_sockaddr_in_in =
const_cast<struct klinux_sockaddr_in *>(
reinterpret_cast<const struct klinux_sockaddr_in *>(input));
struct sockaddr_in sockaddr_in_out;
sockaddr_in_out.sin_family = AF_INET;
sockaddr_in_out.sin_port = klinux_sockaddr_in_in->klinux_sin_port;
InitializeToZeroSingle(&sockaddr_in_out.sin_addr);
ReinterpretCopySingle(&sockaddr_in_out.sin_addr,
&klinux_sockaddr_in_in->klinux_sin_addr);
InitializeToZeroArray(sockaddr_in_out.sin_zero);
ReinterpretCopyArray(sockaddr_in_out.sin_zero,
klinux_sockaddr_in_in->klinux_sin_zero);
CopySockaddr(&sockaddr_in_out, sizeof(sockaddr_in_out), output, output_len);
} else if (klinux_family == kLinux_AF_INET6) {
if (input_len < sizeof(struct klinux_sockaddr_in6)) {
return false;
}
struct klinux_sockaddr_in6 *klinux_sockaddr_in6_in =
const_cast<struct klinux_sockaddr_in6 *>(
reinterpret_cast<const struct klinux_sockaddr_in6 *>(input));
struct sockaddr_in6 sockaddr_in6_out;
sockaddr_in6_out.sin6_family = AF_INET6;
sockaddr_in6_out.sin6_port = klinux_sockaddr_in6_in->klinux_sin6_port;
sockaddr_in6_out.sin6_flowinfo =
klinux_sockaddr_in6_in->klinux_sin6_flowinfo;
sockaddr_in6_out.sin6_scope_id =
klinux_sockaddr_in6_in->klinux_sin6_scope_id;
InitializeToZeroSingle(&sockaddr_in6_out.sin6_addr);
ReinterpretCopySingle(&sockaddr_in6_out.sin6_addr,
&klinux_sockaddr_in6_in->klinux_sin6_addr);
CopySockaddr(&sockaddr_in6_out, sizeof(sockaddr_in6_out), output,
output_len);
} else if (klinux_family == kLinux_AF_UNSPEC) {
output = nullptr;
*output_len = 0;
} else {
if (abort_handler != nullptr) {
std::string message = absl::StrCat(
"Type conversion error - Unsupported AF family: ", klinux_family);
abort_handler(message.c_str());
} else {
abort();
}
}
return true;
} | {
"deleted": [],
"added": [
{
"line_no": 12,
"char_start": 438,
"char_end": 495,
"line": " if (input_len < sizeof(struct klinux_sockaddr_un)) {\n"
},
{
"line_no": 13,
"char_start": 495,
"char_end": 515,
"line": " return false;\n"
},
{
"line_no": 14,
"char_start": 515,
"char_end": 521,
"line": " }\n"
},
{
"line_no": 15,
"char_start": 521,
"char_end": 522,
"line": "\n"
},
{
"line_no": 29,
"char_start": 1182,
"char_end": 1239,
"line": " if (input_len < sizeof(struct klinux_sockaddr_in)) {\n"
},
{
"line_no": 30,
"char_start": 1239,
"char_end": 1259,
"line": " return false;\n"
},
{
"line_no": 31,
"char_start": 1259,
"char_end": 1265,
"line": " }\n"
},
{
"line_no": 47,
"char_start": 2072,
"char_end": 2130,
"line": " if (input_len < sizeof(struct klinux_sockaddr_in6)) {\n"
},
{
"line_no": 48,
"char_start": 2130,
"char_end": 2150,
"line": " return false;\n"
},
{
"line_no": 49,
"char_start": 2150,
"char_end": 2156,
"line": " }\n"
},
{
"line_no": 50,
"char_start": 2156,
"char_end": 2157,
"line": "\n"
}
]
} | {
"deleted": [
{
"char_start": 493,
"char_end": 493,
"chars": ""
},
{
"char_start": 1856,
"char_end": 1856,
"chars": ""
}
],
"added": [
{
"char_start": 442,
"char_end": 526,
"chars": "if (input_len < sizeof(struct klinux_sockaddr_un)) {\n return false;\n }\n\n "
},
{
"char_start": 1182,
"char_end": 1265,
"chars": " if (input_len < sizeof(struct klinux_sockaddr_in)) {\n return false;\n }\n"
},
{
"char_start": 2071,
"char_end": 2156,
"chars": "\n if (input_len < sizeof(struct klinux_sockaddr_in6)) {\n return false;\n }\n"
}
]
} | github.com/google/asylo/commit/bda9772e7872b0d2b9bee32930cf7a4983837b39 | asylo/platform/system_call/type_conversions/manual_types_functions.cc | cwe-787 |
opj_pi_create_decode | opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
} | opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
opj_cp_t *p_cp,
OPJ_UINT32 p_tile_no)
{
/* loop */
OPJ_UINT32 pino;
OPJ_UINT32 compno, resno;
/* to store w, h, dx and dy fro all components and resolutions */
OPJ_UINT32 * l_tmp_data;
OPJ_UINT32 ** l_tmp_ptr;
/* encoding prameters to set */
OPJ_UINT32 l_max_res;
OPJ_UINT32 l_max_prec;
OPJ_INT32 l_tx0,l_tx1,l_ty0,l_ty1;
OPJ_UINT32 l_dx_min,l_dy_min;
OPJ_UINT32 l_bound;
OPJ_UINT32 l_step_p , l_step_c , l_step_r , l_step_l ;
OPJ_UINT32 l_data_stride;
/* pointers */
opj_pi_iterator_t *l_pi = 00;
opj_tcp_t *l_tcp = 00;
const opj_tccp_t *l_tccp = 00;
opj_pi_comp_t *l_current_comp = 00;
opj_image_comp_t * l_img_comp = 00;
opj_pi_iterator_t * l_current_pi = 00;
OPJ_UINT32 * l_encoding_value_ptr = 00;
/* preconditions in debug */
assert(p_cp != 00);
assert(p_image != 00);
assert(p_tile_no < p_cp->tw * p_cp->th);
/* initializations */
l_tcp = &p_cp->tcps[p_tile_no];
l_bound = l_tcp->numpocs+1;
l_data_stride = 4 * OPJ_J2K_MAXRLVLS;
l_tmp_data = (OPJ_UINT32*)opj_malloc(
l_data_stride * p_image->numcomps * sizeof(OPJ_UINT32));
if
(! l_tmp_data)
{
return 00;
}
l_tmp_ptr = (OPJ_UINT32**)opj_malloc(
p_image->numcomps * sizeof(OPJ_UINT32 *));
if
(! l_tmp_ptr)
{
opj_free(l_tmp_data);
return 00;
}
/* memory allocation for pi */
l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
if (!l_pi) {
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
return 00;
}
l_encoding_value_ptr = l_tmp_data;
/* update pointer array */
for
(compno = 0; compno < p_image->numcomps; ++compno)
{
l_tmp_ptr[compno] = l_encoding_value_ptr;
l_encoding_value_ptr += l_data_stride;
}
/* get encoding parameters */
opj_get_all_encoding_parameters(p_image,p_cp,p_tile_no,&l_tx0,&l_tx1,&l_ty0,&l_ty1,&l_dx_min,&l_dy_min,&l_max_prec,&l_max_res,l_tmp_ptr);
/* step calculations */
l_step_p = 1;
l_step_c = l_max_prec * l_step_p;
l_step_r = p_image->numcomps * l_step_c;
l_step_l = l_max_res * l_step_r;
/* set values for first packet iterator */
l_current_pi = l_pi;
/* memory allocation for include */
/* prevent an integer overflow issue */
l_current_pi->include = 00;
if (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))
{
l_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));
}
if
(!l_current_pi->include)
{
opj_free(l_tmp_data);
opj_free(l_tmp_ptr);
opj_pi_destroy(l_pi, l_bound);
return 00;
}
/* special treatment for the first packet iterator */
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_img_comp->dx;*/
/*l_current_pi->dy = l_img_comp->dy;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
++l_current_pi;
for (pino = 1 ; pino<l_bound ; ++pino )
{
l_current_comp = l_current_pi->comps;
l_img_comp = p_image->comps;
l_tccp = l_tcp->tccps;
l_current_pi->tx0 = l_tx0;
l_current_pi->ty0 = l_ty0;
l_current_pi->tx1 = l_tx1;
l_current_pi->ty1 = l_ty1;
/*l_current_pi->dx = l_dx_min;*/
/*l_current_pi->dy = l_dy_min;*/
l_current_pi->step_p = l_step_p;
l_current_pi->step_c = l_step_c;
l_current_pi->step_r = l_step_r;
l_current_pi->step_l = l_step_l;
/* allocation for components and number of components has already been calculated by opj_pi_create */
for
(compno = 0; compno < l_current_pi->numcomps; ++compno)
{
opj_pi_resolution_t *l_res = l_current_comp->resolutions;
l_encoding_value_ptr = l_tmp_ptr[compno];
l_current_comp->dx = l_img_comp->dx;
l_current_comp->dy = l_img_comp->dy;
/* resolutions have already been initialized */
for
(resno = 0; resno < l_current_comp->numresolutions; resno++)
{
l_res->pdx = *(l_encoding_value_ptr++);
l_res->pdy = *(l_encoding_value_ptr++);
l_res->pw = *(l_encoding_value_ptr++);
l_res->ph = *(l_encoding_value_ptr++);
++l_res;
}
++l_current_comp;
++l_img_comp;
++l_tccp;
}
/* special treatment*/
l_current_pi->include = (l_current_pi-1)->include;
++l_current_pi;
}
opj_free(l_tmp_data);
l_tmp_data = 00;
opj_free(l_tmp_ptr);
l_tmp_ptr = 00;
if
(l_tcp->POC)
{
opj_pi_update_decode_poc (l_pi,l_tcp,l_max_prec,l_max_res);
}
else
{
opj_pi_update_decode_not_poc(l_pi,l_tcp,l_max_prec,l_max_res);
}
return l_pi;
} | {
"deleted": [
{
"line_no": 86,
"char_start": 2139,
"char_end": 2242,
"line": "\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\n"
}
],
"added": [
{
"line_no": 86,
"char_start": 2139,
"char_end": 2180,
"line": "\t/* prevent an integer overflow issue */\n"
},
{
"line_no": 87,
"char_start": 2180,
"char_end": 2209,
"line": "\tl_current_pi->include = 00;\n"
},
{
"line_no": 88,
"char_start": 2209,
"char_end": 2264,
"line": "\tif (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))\n"
},
{
"line_no": 89,
"char_start": 2264,
"char_end": 2267,
"line": "\t{\n"
},
{
"line_no": 90,
"char_start": 2267,
"char_end": 2371,
"line": "\t\tl_current_pi->include = (OPJ_INT16*) opj_calloc((l_tcp->numlayers +1) * l_step_l, sizeof(OPJ_INT16));\n"
},
{
"line_no": 91,
"char_start": 2371,
"char_end": 2374,
"line": "\t}\n"
},
{
"line_no": 92,
"char_start": 2374,
"char_end": 2375,
"line": "\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 2140,
"char_end": 2269,
"chars": "/* prevent an integer overflow issue */\n\tl_current_pi->include = 00;\n\tif (l_step_l <= (SIZE_MAX / (l_tcp->numlayers + 1U)))\n\t{\n\t\t"
},
{
"char_start": 2370,
"char_end": 2374,
"chars": "\n\t}\n"
}
]
} | github.com/uclouvain/openjpeg/commit/c16bc057ba3f125051c9966cf1f5b68a05681de4 | src/lib/openjp2/pi.c | cwe-787 |
opj_j2k_set_cinema_parameters | static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager)
{
/* Configure cinema parameters */
int i;
/* No tiling */
parameters->tile_size_on = OPJ_FALSE;
parameters->cp_tdx = 1;
parameters->cp_tdy = 1;
/* One tile part for each component */
parameters->tp_flag = 'C';
parameters->tp_on = 1;
/* Tile and Image shall be at (0,0) */
parameters->cp_tx0 = 0;
parameters->cp_ty0 = 0;
parameters->image_offset_x0 = 0;
parameters->image_offset_y0 = 0;
/* Codeblock size= 32*32 */
parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
/* Codeblock style: no mode switch enabled */
parameters->mode = 0;
/* No ROI */
parameters->roi_compno = -1;
/* No subsampling */
parameters->subsampling_dx = 1;
parameters->subsampling_dy = 1;
/* 9-7 transform */
parameters->irreversible = 1;
/* Number of layers */
if (parameters->tcp_numlayers > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"1 single quality layer"
"-> Number of layers forced to 1 (rather than %d)\n"
"-> Rate of the last layer (%3.1f) will be used",
parameters->tcp_numlayers,
parameters->tcp_rates[parameters->tcp_numlayers - 1]);
parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1];
parameters->tcp_numlayers = 1;
}
/* Resolution levels */
switch (parameters->rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (parameters->numresolution > 6) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Number of decomposition levels <= 5\n"
"-> Number of decomposition levels forced to 5 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 6;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (parameters->numresolution < 2) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 1 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 1;
} else if (parameters->numresolution > 7) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 6 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 7;
}
break;
default :
break;
}
/* Precincts */
parameters->csty |= 0x01;
parameters->res_spec = parameters->numresolution - 1;
for (i = 0; i < parameters->res_spec; i++) {
parameters->prcw_init[i] = 256;
parameters->prch_init[i] = 256;
}
/* The progression order shall be CPRL */
parameters->prog_order = OPJ_CPRL;
/* Progression order changes for 4K, disallowed for 2K */
if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,
parameters->numresolution);
} else {
parameters->numpocs = 0;
}
/* Limited bit-rate */
parameters->cp_disto_alloc = 1;
if (parameters->max_cs_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_cs_size = OPJ_CINEMA_24_CS;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
parameters->max_cs_size = OPJ_CINEMA_24_CS;
}
if (parameters->max_comp_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
}
parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
} | static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
opj_image_t *image, opj_event_mgr_t *p_manager)
{
/* Configure cinema parameters */
int i;
/* No tiling */
parameters->tile_size_on = OPJ_FALSE;
parameters->cp_tdx = 1;
parameters->cp_tdy = 1;
/* One tile part for each component */
parameters->tp_flag = 'C';
parameters->tp_on = 1;
/* Tile and Image shall be at (0,0) */
parameters->cp_tx0 = 0;
parameters->cp_ty0 = 0;
parameters->image_offset_x0 = 0;
parameters->image_offset_y0 = 0;
/* Codeblock size= 32*32 */
parameters->cblockw_init = 32;
parameters->cblockh_init = 32;
/* Codeblock style: no mode switch enabled */
parameters->mode = 0;
/* No ROI */
parameters->roi_compno = -1;
/* No subsampling */
parameters->subsampling_dx = 1;
parameters->subsampling_dy = 1;
/* 9-7 transform */
parameters->irreversible = 1;
/* Number of layers */
if (parameters->tcp_numlayers > 1) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"1 single quality layer"
"-> Number of layers forced to 1 (rather than %d)\n"
"-> Rate of the last layer (%3.1f) will be used",
parameters->tcp_numlayers,
parameters->tcp_rates[parameters->tcp_numlayers - 1]);
parameters->tcp_rates[0] = parameters->tcp_rates[parameters->tcp_numlayers - 1];
parameters->tcp_numlayers = 1;
}
/* Resolution levels */
switch (parameters->rsiz) {
case OPJ_PROFILE_CINEMA_2K:
if (parameters->numresolution > 6) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 (2k dc profile) requires:\n"
"Number of decomposition levels <= 5\n"
"-> Number of decomposition levels forced to 5 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 6;
}
break;
case OPJ_PROFILE_CINEMA_4K:
if (parameters->numresolution < 2) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 1 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 1;
} else if (parameters->numresolution > 7) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-4 (4k dc profile) requires:\n"
"Number of decomposition levels >= 1 && <= 6\n"
"-> Number of decomposition levels forced to 6 (rather than %d)\n",
parameters->numresolution + 1);
parameters->numresolution = 7;
}
break;
default :
break;
}
/* Precincts */
parameters->csty |= 0x01;
if (parameters->numresolution == 1) {
parameters->res_spec = 1;
parameters->prcw_init[0] = 128;
parameters->prch_init[0] = 128;
} else {
parameters->res_spec = parameters->numresolution - 1;
for (i = 0; i < parameters->res_spec; i++) {
parameters->prcw_init[i] = 256;
parameters->prch_init[i] = 256;
}
}
/* The progression order shall be CPRL */
parameters->prog_order = OPJ_CPRL;
/* Progression order changes for 4K, disallowed for 2K */
if (parameters->rsiz == OPJ_PROFILE_CINEMA_4K) {
parameters->numpocs = (OPJ_UINT32)opj_j2k_initialise_4K_poc(parameters->POC,
parameters->numresolution);
} else {
parameters->numpocs = 0;
}
/* Limited bit-rate */
parameters->cp_disto_alloc = 1;
if (parameters->max_cs_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_cs_size = OPJ_CINEMA_24_CS;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_cs_size > OPJ_CINEMA_24_CS) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1302083 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1302083 bytes.\n");
parameters->max_cs_size = OPJ_CINEMA_24_CS;
}
if (parameters->max_comp_size <= 0) {
/* No rate has been introduced, 24 fps is assumed */
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"As no rate has been given, this limit will be used.\n");
} else if (parameters->max_comp_size > OPJ_CINEMA_24_COMP) {
opj_event_msg(p_manager, EVT_WARNING,
"JPEG 2000 Profile-3 and 4 (2k/4k dc profile) requires:\n"
"Maximum 1041666 compressed bytes @ 24fps\n"
"-> Specified rate exceeds this limit. Rate will be forced to 1041666 bytes.\n");
parameters->max_comp_size = OPJ_CINEMA_24_COMP;
}
parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
image->comps[0].h * image->comps[0].prec) /
(OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
image->comps[0].dy);
} | {
"deleted": [
{
"line_no": 87,
"char_start": 3193,
"char_end": 3251,
"line": " parameters->res_spec = parameters->numresolution - 1;\n"
},
{
"line_no": 88,
"char_start": 3251,
"char_end": 3300,
"line": " for (i = 0; i < parameters->res_spec; i++) {\n"
},
{
"line_no": 89,
"char_start": 3300,
"char_end": 3340,
"line": " parameters->prcw_init[i] = 256;\n"
},
{
"line_no": 90,
"char_start": 3340,
"char_end": 3380,
"line": " parameters->prch_init[i] = 256;\n"
}
],
"added": [
{
"line_no": 87,
"char_start": 3193,
"char_end": 3235,
"line": " if (parameters->numresolution == 1) {\n"
},
{
"line_no": 88,
"char_start": 3235,
"char_end": 3269,
"line": " parameters->res_spec = 1;\n"
},
{
"line_no": 89,
"char_start": 3269,
"char_end": 3309,
"line": " parameters->prcw_init[0] = 128;\n"
},
{
"line_no": 90,
"char_start": 3309,
"char_end": 3349,
"line": " parameters->prch_init[0] = 128;\n"
},
{
"line_no": 91,
"char_start": 3349,
"char_end": 3362,
"line": " } else {\n"
},
{
"line_no": 92,
"char_start": 3362,
"char_end": 3424,
"line": " parameters->res_spec = parameters->numresolution - 1;\n"
},
{
"line_no": 93,
"char_start": 3424,
"char_end": 3477,
"line": " for (i = 0; i < parameters->res_spec; i++) {\n"
},
{
"line_no": 94,
"char_start": 3477,
"char_end": 3521,
"line": " parameters->prcw_init[i] = 256;\n"
},
{
"line_no": 95,
"char_start": 3521,
"char_end": 3565,
"line": " parameters->prch_init[i] = 256;\n"
},
{
"line_no": 96,
"char_start": 3565,
"char_end": 3575,
"line": " }\n"
}
]
} | {
"deleted": [],
"added": [
{
"char_start": 3197,
"char_end": 3370,
"chars": "if (parameters->numresolution == 1) {\n parameters->res_spec = 1;\n parameters->prcw_init[0] = 128;\n parameters->prch_init[0] = 128;\n } else {\n "
},
{
"char_start": 3424,
"char_end": 3428,
"chars": " "
},
{
"char_start": 3485,
"char_end": 3489,
"chars": " "
},
{
"char_start": 3521,
"char_end": 3523,
"chars": " "
},
{
"char_start": 3531,
"char_end": 3533,
"chars": " "
},
{
"char_start": 3564,
"char_end": 3574,
"chars": "\n }"
}
]
} | github.com/uclouvain/openjpeg/commit/4241ae6fbbf1de9658764a80944dc8108f2b4154 | src/lib/openjp2/j2k.c | cwe-787 |
adminchild | void * adminchild(struct clientparam* param) {
int i, res;
char * buf;
char username[256];
char *sb;
char *req = NULL;
struct printparam pp;
int contentlen = 0;
int isform = 0;
pp.inbuf = 0;
pp.cp = param;
buf = myalloc(LINESIZE);
if(!buf) {RETURN(555);}
i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]);
if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') &&
(buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/')))
{
RETURN(701);
}
buf[i] = 0;
sb = strchr(buf+5, ' ');
if(!sb){
RETURN(702);
}
*sb = 0;
req = mystrdup(buf + ((*buf == 'P')? 6 : 5));
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){
buf[i] = 0;
if(i > 19 && (!strncasecmp(buf, "authorization", 13))){
sb = strchr(buf, ':');
if(!sb)continue;
++sb;
while(isspace(*sb))sb++;
if(!*sb || strncasecmp(sb, "basic", 5)){
continue;
}
sb+=5;
while(isspace(*sb))sb++;
i = de64((unsigned char *)sb, (unsigned char *)username, 255);
if(i<=0)continue;
username[i] = 0;
sb = strchr((char *)username, ':');
if(sb){
*sb = 0;
if(param->password)myfree(param->password);
param->password = (unsigned char *)mystrdup(sb+1);
}
if(param->username) myfree(param->username);
param->username = (unsigned char *)mystrdup(username);
continue;
}
else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){
sb = buf + 15;
while(isspace(*sb))sb++;
contentlen = atoi(sb);
}
else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){
sb = buf + 13;
while(isspace(*sb))sb++;
if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1;
}
}
param->operation = ADMIN;
if(isform && contentlen) {
printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n");
stdpr(&pp, NULL, 0);
}
res = (*param->srv->authfunc)(param);
if(res && res != 10) {
printstr(&pp, authreq);
RETURN(res);
}
if(param->srv->singlepacket || param->redirected){
if(*req == 'C') req[1] = 0;
else *req = 0;
}
sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:"");
if(*req != 'S') printstr(&pp, buf);
switch(*req){
case 'C':
printstr(&pp, counters);
{
struct trafcount *cp;
int num = 0;
for(cp = conf.trafcounter; cp; cp = cp->next, num++){
int inbuf = 0;
if(cp->ace && (param->srv->singlepacket || param->redirected)){
if(!ACLmatches(cp->ace, param))continue;
}
if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0;
if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1;
inbuf += sprintf(buf, "<tr>"
"<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>",
(cp->comment)?cp->comment:" ",
(cp->disabled)?'S':'D',
num,
(cp->disabled)?"NO":"YES"
);
if(!cp->ace || !cp->ace->users){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->src){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->dst){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->ports){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n");
}
if(cp->type == NONE) {
inbuf += sprintf(buf+inbuf,
"</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n"
);
}
else {
inbuf += sprintf(buf+inbuf,
"</td><td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>MB%s</td>"
"<td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>%s</td>",
cp->traflim64 / (1024 * 1024),
rotations[cp->type],
cp->traf64,
cp->cleared?ctime(&cp->cleared):"never"
);
inbuf += sprintf(buf + inbuf,
"<td>%s</td>"
"<td>%i</td>"
"</tr>\r\n",
cp->updated?ctime(&cp->updated):"never",
cp->number
);
}
printstr(&pp, buf);
}
}
printstr(&pp, counterstail);
break;
case 'R':
conf.needreload = 1;
printstr(&pp, "<h3>Reload scheduled</h3>");
break;
case 'S':
{
if(req[1] == 'X'){
printstr(&pp, style);
break;
}
printstr(&pp, xml);
printval(conf.services, TYPE_SERVER, 0, &pp);
printstr(&pp, postxml);
}
break;
case 'F':
{
FILE *fp;
char buf[256];
fp = confopen();
if(!fp){
printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>");
break;
}
printstr(&pp, "<h3>Please be careful editing config file remotely</h3>");
printstr(&pp, "<form method=\"POST\" action=\"/U\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">");
while(fgets(buf, 256, fp)){
printstr(&pp, buf);
}
if(!writable) fclose(fp);
printstr(&pp, "</textarea><br><input type=\"Submit\"></form>");
break;
}
case 'U':
{
int l=0;
int error = 0;
if(!writable || fseek(writable, 0, 0)){
error = 1;
}
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){
if(i > (contentlen - l)) i = (contentlen - l);
buf[i] = 0;
if(!l){
if(strncasecmp(buf, "conffile=", 9)) error = 1;
}
if(!error){
decodeurl((unsigned char *)buf, 1);
fprintf(writable, "%s", l? buf : buf + 9);
}
l += i;
if(l >= contentlen) break;
}
if(writable && !error){
fflush(writable);
#ifndef _WINCE
ftruncate(fileno(writable), ftell(writable));
#endif
}
printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file":
"<h3>Configuration updated</h3>");
}
break;
default:
printstr(&pp, (char *)conf.stringtable[WEBBANNERS]);
break;
}
if(*req != 'S') printstr(&pp, tail);
CLEANRET:
printstr(&pp, NULL);
if(buf) myfree(buf);
(*param->srv->logfunc)(param, (unsigned char *)req);
if(req)myfree(req);
freeparam(param);
return (NULL);
} | void * adminchild(struct clientparam* param) {
int i, res;
char * buf;
char username[256];
char *sb;
char *req = NULL;
struct printparam pp;
unsigned contentlen = 0;
int isform = 0;
pp.inbuf = 0;
pp.cp = param;
buf = myalloc(LINESIZE);
if(!buf) {RETURN(555);}
i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S]);
if(i<5 || ((buf[0]!='G' || buf[1]!='E' || buf[2]!='T' || buf[3]!=' ' || buf[4]!='/') &&
(buf[0]!='P' || buf[1]!='O' || buf[2]!='S' || buf[3]!='T' || buf[4]!=' ' || buf[5]!='/')))
{
RETURN(701);
}
buf[i] = 0;
sb = strchr(buf+5, ' ');
if(!sb){
RETURN(702);
}
*sb = 0;
req = mystrdup(buf + ((*buf == 'P')? 6 : 5));
while((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '\n', conf.timeouts[STRING_S])) > 2){
buf[i] = 0;
if(i > 19 && (!strncasecmp(buf, "authorization", 13))){
sb = strchr(buf, ':');
if(!sb)continue;
++sb;
while(isspace(*sb))sb++;
if(!*sb || strncasecmp(sb, "basic", 5)){
continue;
}
sb+=5;
while(isspace(*sb))sb++;
i = de64((unsigned char *)sb, (unsigned char *)username, 255);
if(i<=0)continue;
username[i] = 0;
sb = strchr((char *)username, ':');
if(sb){
*sb = 0;
if(param->password)myfree(param->password);
param->password = (unsigned char *)mystrdup(sb+1);
}
if(param->username) myfree(param->username);
param->username = (unsigned char *)mystrdup(username);
continue;
}
else if(i > 15 && (!strncasecmp(buf, "content-length:", 15))){
sb = buf + 15;
while(isspace(*sb))sb++;
sscanf(sb, "%u", &contentlen);
if(contentlen > LINESIZE*1024) contentlen = 0;
}
else if(i > 13 && (!strncasecmp(buf, "content-type:", 13))){
sb = buf + 13;
while(isspace(*sb))sb++;
if(!strncasecmp(sb, "x-www-form-urlencoded", 21)) isform = 1;
}
}
param->operation = ADMIN;
if(isform && contentlen) {
printstr(&pp, "HTTP/1.0 100 Continue\r\n\r\n");
stdpr(&pp, NULL, 0);
}
res = (*param->srv->authfunc)(param);
if(res && res != 10) {
printstr(&pp, authreq);
RETURN(res);
}
if(param->srv->singlepacket || param->redirected){
if(*req == 'C') req[1] = 0;
else *req = 0;
}
sprintf(buf, ok, conf.stringtable?(char *)conf.stringtable[2]:"3proxy", conf.stringtable?(char *)conf.stringtable[2]:"3[APA3A] tiny proxy", conf.stringtable?(char *)conf.stringtable[3]:"");
if(*req != 'S') printstr(&pp, buf);
switch(*req){
case 'C':
printstr(&pp, counters);
{
struct trafcount *cp;
int num = 0;
for(cp = conf.trafcounter; cp; cp = cp->next, num++){
int inbuf = 0;
if(cp->ace && (param->srv->singlepacket || param->redirected)){
if(!ACLmatches(cp->ace, param))continue;
}
if(req[1] == 'S' && atoi(req+2) == num) cp->disabled=0;
if(req[1] == 'D' && atoi(req+2) == num) cp->disabled=1;
inbuf += sprintf(buf, "<tr>"
"<td>%s</td><td><A HREF=\'/C%c%d\'>%s</A></td><td>",
(cp->comment)?cp->comment:" ",
(cp->disabled)?'S':'D',
num,
(cp->disabled)?"NO":"YES"
);
if(!cp->ace || !cp->ace->users){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printuserlist(buf+inbuf, LINESIZE-800, cp->ace->users, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->src){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->src, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->dst){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printiplist(buf+inbuf, LINESIZE-512, cp->ace->dst, ",<br />\r\n");
}
inbuf += sprintf(buf+inbuf, "</td><td>");
if(!cp->ace || !cp->ace->ports){
inbuf += sprintf(buf+inbuf, "<center>ANY</center>");
}
else {
inbuf += printportlist(buf+inbuf, LINESIZE-128, cp->ace->ports, ",<br />\r\n");
}
if(cp->type == NONE) {
inbuf += sprintf(buf+inbuf,
"</td><td colspan=\'6\' align=\'center\'>exclude from limitation</td></tr>\r\n"
);
}
else {
inbuf += sprintf(buf+inbuf,
"</td><td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>MB%s</td>"
"<td>%"PRINTF_INT64_MODIFIER"u</td>"
"<td>%s</td>",
cp->traflim64 / (1024 * 1024),
rotations[cp->type],
cp->traf64,
cp->cleared?ctime(&cp->cleared):"never"
);
inbuf += sprintf(buf + inbuf,
"<td>%s</td>"
"<td>%i</td>"
"</tr>\r\n",
cp->updated?ctime(&cp->updated):"never",
cp->number
);
}
printstr(&pp, buf);
}
}
printstr(&pp, counterstail);
break;
case 'R':
conf.needreload = 1;
printstr(&pp, "<h3>Reload scheduled</h3>");
break;
case 'S':
{
if(req[1] == 'X'){
printstr(&pp, style);
break;
}
printstr(&pp, xml);
printval(conf.services, TYPE_SERVER, 0, &pp);
printstr(&pp, postxml);
}
break;
case 'F':
{
FILE *fp;
char buf[256];
fp = confopen();
if(!fp){
printstr(&pp, "<h3><font color=\"red\">Failed to open config file</font></h3>");
break;
}
printstr(&pp, "<h3>Please be careful editing config file remotely</h3>");
printstr(&pp, "<form method=\"POST\" action=\"/U\" enctype=\"application/x-www-form-urlencoded\"><textarea cols=\"80\" rows=\"30\" name=\"conffile\">");
while(fgets(buf, 256, fp)){
printstr(&pp, buf);
}
if(!writable) fclose(fp);
printstr(&pp, "</textarea><br><input type=\"Submit\"></form>");
break;
}
case 'U':
{
unsigned l=0;
int error = 0;
if(!writable || !contentlen || fseek(writable, 0, 0)){
error = 1;
}
while(l < contentlen && (i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, (contentlen - l) > LINESIZE - 1?LINESIZE - 1:contentlen - l, '+', conf.timeouts[STRING_S])) > 0){
if(i > (contentlen - l)) i = (contentlen - l);
if(!l){
if(i<9 || strncasecmp(buf, "conffile=", 9)) error = 1;
}
if(!error){
buf[i] = 0;
decodeurl((unsigned char *)buf, 1);
fprintf(writable, "%s", l? buf : buf + 9);
}
l += i;
}
if(writable && !error){
fflush(writable);
#ifndef _WINCE
ftruncate(fileno(writable), ftell(writable));
#endif
}
printstr(&pp, error? "<h3><font color=\"red\">Config file is not writable</font></h3>Make sure you have \"writable\" command in configuration file":
"<h3>Configuration updated</h3>");
}
break;
default:
printstr(&pp, (char *)conf.stringtable[WEBBANNERS]);
break;
}
if(*req != 'S') printstr(&pp, tail);
CLEANRET:
printstr(&pp, NULL);
if(buf) myfree(buf);
(*param->srv->logfunc)(param, (unsigned char *)req);
if(req)myfree(req);
freeparam(param);
return (NULL);
} | {
"deleted": [
{
"line_no": 8,
"char_start": 147,
"char_end": 168,
"line": " int contentlen = 0;\n"
},
{
"line_no": 57,
"char_start": 1557,
"char_end": 1582,
"line": "\t\tcontentlen = atoi(sb);\n"
},
{
"line_no": 187,
"char_start": 5131,
"char_end": 5242,
"line": "\t\t\t\tprintstr(&pp, \"<form method=\\\"POST\\\" action=\\\"/U\\\"><textarea cols=\\\"80\\\" rows=\\\"30\\\" name=\\\"conffile\\\">\");\n"
},
{
"line_no": 197,
"char_start": 5432,
"char_end": 5444,
"line": "\t\t\tint l=0;\n"
},
{
"line_no": 200,
"char_start": 5463,
"char_end": 5506,
"line": "\t\t\tif(!writable || fseek(writable, 0, 0)){\n"
},
{
"line_no": 203,
"char_start": 5526,
"char_end": 5643,
"line": "\t\t\twhile((i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, LINESIZE - 1, '+', conf.timeouts[STRING_S])) > 0){\n"
},
{
"line_no": 205,
"char_start": 5694,
"char_end": 5710,
"line": "\t\t\t\tbuf[i] = 0;\n"
},
{
"line_no": 207,
"char_start": 5722,
"char_end": 5775,
"line": "\t\t\t\t\tif(strncasecmp(buf, \"conffile=\", 9)) error = 1;\n"
},
{
"line_no": 214,
"char_start": 5904,
"char_end": 5935,
"line": "\t\t\t\tif(l >= contentlen) break;\n"
}
],
"added": [
{
"line_no": 8,
"char_start": 147,
"char_end": 173,
"line": " unsigned contentlen = 0;\n"
},
{
"line_no": 57,
"char_start": 1562,
"char_end": 1595,
"line": "\t\tsscanf(sb, \"%u\", &contentlen);\n"
},
{
"line_no": 58,
"char_start": 1595,
"char_end": 1644,
"line": "\t\tif(contentlen > LINESIZE*1024) contentlen = 0;\n"
},
{
"line_no": 188,
"char_start": 5193,
"char_end": 5350,
"line": "\t\t\t\tprintstr(&pp, \"<form method=\\\"POST\\\" action=\\\"/U\\\" enctype=\\\"application/x-www-form-urlencoded\\\"><textarea cols=\\\"80\\\" rows=\\\"30\\\" name=\\\"conffile\\\">\");\n"
},
{
"line_no": 198,
"char_start": 5540,
"char_end": 5557,
"line": "\t\t\tunsigned l=0;\n"
},
{
"line_no": 201,
"char_start": 5576,
"char_end": 5634,
"line": "\t\t\tif(!writable || !contentlen || fseek(writable, 0, 0)){\n"
},
{
"line_no": 204,
"char_start": 5654,
"char_end": 5836,
"line": "\t\t\twhile(l < contentlen && (i = sockgetlinebuf(param, CLIENT, (unsigned char *)buf, (contentlen - l) > LINESIZE - 1?LINESIZE - 1:contentlen - l, '+', conf.timeouts[STRING_S])) > 0){\n"
},
{
"line_no": 207,
"char_start": 5899,
"char_end": 5959,
"line": "\t\t\t\t\tif(i<9 || strncasecmp(buf, \"conffile=\", 9)) error = 1;\n"
},
{
"line_no": 210,
"char_start": 5981,
"char_end": 5998,
"line": "\t\t\t\t\tbuf[i] = 0;\n"
}
]
} | {
"deleted": [
{
"char_start": 150,
"char_end": 151,
"chars": "t"
},
{
"char_start": 1570,
"char_end": 1571,
"chars": "="
},
{
"char_start": 1572,
"char_end": 1579,
"chars": "atoi(sb"
},
{
"char_start": 5437,
"char_end": 5438,
"chars": "t"
},
{
"char_start": 5698,
"char_end": 5714,
"chars": "buf[i] = 0;\n\t\t\t\t"
},
{
"char_start": 5902,
"char_end": 5933,
"chars": ";\n\t\t\t\tif(l >= contentlen) break"
}
],
"added": [
{
"char_start": 148,
"char_end": 151,
"chars": "uns"
},
{
"char_start": 152,
"char_end": 153,
"chars": "g"
},
{
"char_start": 154,
"char_end": 156,
"chars": "ed"
},
{
"char_start": 1564,
"char_end": 1582,
"chars": "sscanf(sb, \"%u\", &"
},
{
"char_start": 1592,
"char_end": 1597,
"chars": ");\n\t\t"
},
{
"char_start": 1598,
"char_end": 1599,
"chars": "f"
},
{
"char_start": 1600,
"char_end": 1626,
"chars": "contentlen > LINESIZE*1024"
},
{
"char_start": 1627,
"char_end": 1642,
"chars": " contentlen = 0"
},
{
"char_start": 5247,
"char_end": 5293,
"chars": " enctype=\\\"application/x-www-form-urlencoded\\\""
},
{
"char_start": 5543,
"char_end": 5546,
"chars": "uns"
},
{
"char_start": 5547,
"char_end": 5548,
"chars": "g"
},
{
"char_start": 5549,
"char_end": 5551,
"chars": "ed"
},
{
"char_start": 5595,
"char_end": 5610,
"chars": "!contentlen || "
},
{
"char_start": 5663,
"char_end": 5681,
"chars": "l < contentlen && "
},
{
"char_start": 5737,
"char_end": 5756,
"chars": " (contentlen - l) >"
},
{
"char_start": 5769,
"char_end": 5797,
"chars": "?LINESIZE - 1:contentlen - l"
},
{
"char_start": 5907,
"char_end": 5914,
"chars": "i<9 || "
},
{
"char_start": 5981,
"char_end": 5998,
"chars": "\t\t\t\t\tbuf[i] = 0;\n"
}
]
} | github.com/z3APA3A/3proxy/commit/3b67dc844789dc0f00e934270c7b349bcb547865 | src/webadmin.c | cwe-787 |