text
stringlengths
478
483k
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fts3DoIncrmerge( Fts3Table *p, /* FTS3 table handle */ const char *zParam /* Nul-terminated string containing "A,B" */ ){ int rc; int nMin = (FTS3_MERGE_COUNT / 2); int nMerge = 0; const char *z = zParam; /* Read the first integer value */ nMerge = fts3Getint(&z); /* If the first integer value is followed by a ',', read the second ** integer value. */ if( z[0]==',' && z[1]!='\0' ){ z++; nMin = fts3Getint(&z); } if( z[0]!='\0' || nMin<2 ){ rc = SQLITE_ERROR; }else{ rc = SQLITE_OK; if( !p->bHasStat ){ assert( p->bFts4==0 ); sqlite3Fts3CreateStatTable(&rc, p); } if( rc==SQLITE_OK ){ rc = sqlite3Fts3Incrmerge(p, nMerge, nMin); } sqlite3Fts3SegmentsClose(p); } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'More improvements to shadow table corruption detection in FTS3. FossilOrigin-Name: 51525f9c3235967bc00a090e84c70a6400698c897aa4742e817121c725b8c99d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ int rc = SQLITE_ERROR; /* Return Code */ const char *zVal = (const char *)sqlite3_value_text(pVal); int nVal = sqlite3_value_bytes(pVal); if( !zVal ){ return SQLITE_NOMEM; }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ rc = fts3DoOptimize(p, 0); }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ rc = fts3DoRebuild(p); }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ rc = fts3DoIntegrityCheck(p); }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ rc = fts3DoIncrmerge(p, &zVal[6]); }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ rc = fts3DoAutoincrmerge(p, &zVal[10]); #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) }else{ int v; if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ v = atoi(&zVal[9]); if( v>=24 && v<=p->nPgsz-35 ) p->nNodeSize = v; rc = SQLITE_OK; }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ v = atoi(&zVal[11]); if( v>=64 && v<=FTS3_MAX_PENDING_DATA ) p->nMaxPendingData = v; rc = SQLITE_OK; }else if( nVal>21 && 0==sqlite3_strnicmp(zVal,"test-no-incr-doclist=",21) ){ p->bNoIncrDoclist = atoi(&zVal[21]); rc = SQLITE_OK; } #endif } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'More improvements to shadow table corruption detection in FTS3. FossilOrigin-Name: 51525f9c3235967bc00a090e84c70a6400698c897aa4742e817121c725b8c99d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fts3AllocateSegdirIdx( Fts3Table *p, int iLangid, /* Language id */ int iIndex, /* Index for p->aIndex */ int iLevel, int *piIdx ){ int rc; /* Return Code */ sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */ int iNext = 0; /* Result of query pNextIdx */ assert( iLangid>=0 ); assert( p->nIndex>=1 ); /* Set variable iNext to the next available segdir index at level iLevel. */ rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0); if( rc==SQLITE_OK ){ sqlite3_bind_int64( pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel) ); if( SQLITE_ROW==sqlite3_step(pNextIdx) ){ iNext = sqlite3_column_int(pNextIdx, 0); } rc = sqlite3_reset(pNextIdx); } if( rc==SQLITE_OK ){ /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already ** full, merge all segments in level iLevel into a single iLevel+1 ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise, ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext. */ if( iNext>=FTS3_MERGE_COUNT ){ fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel)); rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel); *piIdx = 0; }else{ *piIdx = iNext; } } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'More improvements to shadow table corruption detection in FTS3. FossilOrigin-Name: 51525f9c3235967bc00a090e84c70a6400698c897aa4742e817121c725b8c99d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fts3SelectLeaf( Fts3Table *p, /* Virtual table handle */ const char *zTerm, /* Term to select leaves for */ int nTerm, /* Size of term zTerm in bytes */ const char *zNode, /* Buffer containing segment interior node */ int nNode, /* Size of buffer at zNode */ sqlite3_int64 *piLeaf, /* Selected leaf node */ sqlite3_int64 *piLeaf2 /* Selected leaf node */ ){ int rc = SQLITE_OK; /* Return code */ int iHeight; /* Height of this node in tree */ assert( piLeaf || piLeaf2 ); fts3GetVarint32(zNode, &iHeight); rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2); assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) ); if( rc==SQLITE_OK && iHeight>1 ){ char *zBlob = 0; /* Blob read from %_segments table */ int nBlob = 0; /* Size of zBlob in bytes */ if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){ rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0); if( rc==SQLITE_OK ){ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0); } sqlite3_free(zBlob); piLeaf = 0; zBlob = 0; } if( rc==SQLITE_OK ){ rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0); } if( rc==SQLITE_OK ){ int iNewHeight = 0; fts3GetVarint32(zBlob, &iNewHeight); if( iNewHeight<=iHeight ){ rc = FTS_CORRUPT_VTAB; }else{ rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2); } } sqlite3_free(zBlob); } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908'], 'message': 'Further improve detection of corrupt records in fts3. FossilOrigin-Name: a0f6d526baecd061a5e2bec5eb698fb5dfb10122ac79c853d7b3f4a48bc9f49b'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){ Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab; int rc = SQLITE_OK; /* Error code */ int i; /* Determine if doclists may be loaded from disk incrementally. This is ** possible if the bOptOk argument is true, the FTS doclists will be ** scanned in forward order, and the phrase consists of ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first" ** tokens or prefix tokens that cannot use a prefix-index. */ int bHaveIncr = 0; int bIncrOk = (bOptOk && pCsr->bDesc==pTab->bDescIdx && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0 #ifdef SQLITE_TEST && pTab->bNoIncrDoclist==0 #endif ); for(i=0; bIncrOk==1 && i<p->nToken; i++){ Fts3PhraseToken *pToken = &p->aToken[i]; if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){ bIncrOk = 0; } if( pToken->pSegcsr ) bHaveIncr = 1; } if( bIncrOk && bHaveIncr ){ /* Use the incremental approach. */ int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn); for(i=0; rc==SQLITE_OK && i<p->nToken; i++){ Fts3PhraseToken *pToken = &p->aToken[i]; Fts3MultiSegReader *pSegcsr = pToken->pSegcsr; if( pSegcsr ){ rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n); } } p->bIncr = 1; }else{ /* Load the full doclist for the phrase into memory. */ rc = fts3EvalPhraseLoad(pCsr, p); p->bIncr = 0; } assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr ); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Improved detection of corrupt shadow tables in FTS3. Enable the debugging special-inserts for FTS3 for both SQLITE_DEBUG and SQLITE_TEST. FossilOrigin-Name: 04b2873be5aedeb1c4325cf36c4b5d180f929a641caf1e3829c03778adb29c8e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){ int rc; /* Return Code */ const char *zVal = (const char *)sqlite3_value_text(pVal); int nVal = sqlite3_value_bytes(pVal); if( !zVal ){ return SQLITE_NOMEM; }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){ rc = fts3DoOptimize(p, 0); }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){ rc = fts3DoRebuild(p); }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){ rc = fts3DoIntegrityCheck(p); }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){ rc = fts3DoIncrmerge(p, &zVal[6]); }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){ rc = fts3DoAutoincrmerge(p, &zVal[10]); #ifdef SQLITE_TEST }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){ p->nNodeSize = atoi(&zVal[9]); rc = SQLITE_OK; }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){ p->nMaxPendingData = atoi(&zVal[11]); rc = SQLITE_OK; }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){ p->bNoIncrDoclist = atoi(&zVal[21]); rc = SQLITE_OK; #endif }else{ rc = SQLITE_ERROR; } return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Improved detection of corrupt shadow tables in FTS3. Enable the debugging special-inserts for FTS3 for both SQLITE_DEBUG and SQLITE_TEST. FossilOrigin-Name: 04b2873be5aedeb1c4325cf36c4b5d180f929a641caf1e3829c03778adb29c8e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int fts3MsrBufferData( Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */ char *pList, int nList ){ if( nList>pMsr->nBuffer ){ char *pNew; pMsr->nBuffer = nList*2; pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer); if( !pNew ) return SQLITE_NOMEM; pMsr->aBuffer = pNew; } memcpy(pMsr->aBuffer, pList, nList); return SQLITE_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Improved detection of corrupt shadow tables in FTS3. Enable the debugging special-inserts for FTS3 for both SQLITE_DEBUG and SQLITE_TEST. FossilOrigin-Name: 04b2873be5aedeb1c4325cf36c4b5d180f929a641caf1e3829c03778adb29c8e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void parse_sec_attr_44(sc_file_t *file, const u8 *buf, size_t len) { /* OpenSc Operation values for each command operation-type */ const int df_idx[8] = { /* byte 1 = OpenSC type of AC Bit0, byte 2 = OpenSC type of AC Bit1 ...*/ SC_AC_OP_DELETE, SC_AC_OP_CREATE, SC_AC_OP_CREATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, SC_AC_OP_LOCK, SC_AC_OP_DELETE, -1}; const int ef_idx[8] = { SC_AC_OP_READ, SC_AC_OP_UPDATE, SC_AC_OP_WRITE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; const int efi_idx[8] = { /* internal EF used for RSA keys */ SC_AC_OP_READ, SC_AC_OP_ERASE, SC_AC_OP_UPDATE, SC_AC_OP_INVALIDATE, SC_AC_OP_REHABILITATE, -1, SC_AC_OP_ERASE, -1}; u8 bValue; int i; int iKeyRef = 0; int iMethod; int iPinCount; int iOffset = 0; int iOperation; const int* p_idx; /* Check all sub-AC definitions within the total AC */ while (len > 1) { /* minimum length = 2 */ size_t iACLen = buf[iOffset] & 0x0F; if (iACLen > len) break; iMethod = SC_AC_NONE; /* default no authentication required */ if (buf[iOffset] & 0X80) { /* AC in adaptive coding */ /* Evaluates only the command-byte, not the optional P1/P2/Option bytes */ size_t iParmLen = 1; /* command-byte is always present */ size_t iKeyLen = 0; /* Encryption key is optional */ if (buf[iOffset] & 0x20) iKeyLen++; if (buf[iOffset+1] & 0x40) iParmLen++; if (buf[iOffset+1] & 0x20) iParmLen++; if (buf[iOffset+1] & 0x10) iParmLen++; if (buf[iOffset+1] & 0x08) iParmLen++; /* Get KeyNumber if available */ if(iKeyLen) { int iSC; if (len < 1+(size_t)iACLen) break; iSC = buf[iOffset+iACLen]; switch( (iSC>>5) & 0x03 ){ case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ } /* Get PinNumber if available */ if (iACLen > (1+iParmLen+iKeyLen)) { /* check via total length if pin is present */ if (len < 1+1+1+(size_t)iParmLen) break; iKeyRef = buf[iOffset+1+1+iParmLen]; /* PTL + AM-header + parameter-bytes */ iMethod = SC_AC_CHV; } /* Convert SETCOS command to OpenSC command group */ if (len < 1+2) break; switch(buf[iOffset+2]){ case 0x2A: /* crypto operation */ iOperation = SC_AC_OP_CRYPTO; break; case 0x46: /* key-generation operation */ iOperation = SC_AC_OP_UPDATE; break; default: iOperation = SC_AC_OP_SELECT; break; } sc_file_add_acl_entry(file, iOperation, iMethod, iKeyRef); } else { /* AC in simple coding */ /* Initial AC is treated as an operational AC */ /* Get specific Cmd groups for specified file-type */ switch (file->type) { case SC_FILE_TYPE_DF: /* DF */ p_idx = df_idx; break; case SC_FILE_TYPE_INTERNAL_EF: /* EF for RSA keys */ p_idx = efi_idx; break; default: /* EF */ p_idx = ef_idx; break; } /* Encryption key present ? */ iPinCount = iACLen - 1; if (buf[iOffset] & 0x20) { int iSC; if (len < 1 + (size_t)iACLen) break; iSC = buf[iOffset + iACLen]; switch( (iSC>>5) & 0x03 ) { case 0: iMethod = SC_AC_TERM; /* key authentication */ break; case 1: iMethod = SC_AC_AUT; /* key authentication */ break; case 2: case 3: iMethod = SC_AC_PRO; /* secure messaging */ break; } iKeyRef = iSC & 0x1F; /* get key number */ iPinCount--; /* one byte used for keyReference */ } /* Pin present ? */ if ( iPinCount > 0 ) { if (len < 1 + 2) break; iKeyRef = buf[iOffset + 2]; /* pin ref */ iMethod = SC_AC_CHV; } /* Add AC for each command-operationType into OpenSc structure */ bValue = buf[iOffset + 1]; for (i = 0; i < 8; i++) { if((bValue & 1) && (p_idx[i] >= 0)) sc_file_add_acl_entry(file, p_idx[i], iMethod, iKeyRef); bValue >>= 1; } } /* Current field treated, get next AC sub-field */ iOffset += iACLen +1; /* AC + PTL-byte */ len -= iACLen +1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fixed UNKNOWN READ Reported by OSS-Fuzz https://oss-fuzz.com/testcase-detail/5681169970757632'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int sc_pkcs15_decode_prkdf_entry(struct sc_pkcs15_card *p15card, struct sc_pkcs15_object *obj, const u8 ** buf, size_t *buflen) { sc_context_t *ctx = p15card->card->ctx; struct sc_pkcs15_prkey_info info; int r, i, gostr3410_params[3]; struct sc_pkcs15_keyinfo_gostparams *keyinfo_gostparams; size_t usage_len = sizeof(info.usage); size_t af_len = sizeof(info.access_flags); struct sc_asn1_entry asn1_com_key_attr[C_ASN1_COM_KEY_ATTR_SIZE]; struct sc_asn1_entry asn1_com_prkey_attr[C_ASN1_COM_PRKEY_ATTR_SIZE]; struct sc_asn1_entry asn1_rsakey_attr[C_ASN1_RSAKEY_ATTR_SIZE]; struct sc_asn1_entry asn1_prk_rsa_attr[C_ASN1_PRK_RSA_ATTR_SIZE]; struct sc_asn1_entry asn1_dsakey_attr[C_ASN1_DSAKEY_ATTR_SIZE]; struct sc_asn1_entry asn1_prk_dsa_attr[C_ASN1_PRK_DSA_ATTR_SIZE]; struct sc_asn1_entry asn1_dsakey_i_p_attr[C_ASN1_DSAKEY_I_P_ATTR_SIZE]; struct sc_asn1_entry asn1_dsakey_value_attr[C_ASN1_DSAKEY_VALUE_ATTR_SIZE]; struct sc_asn1_entry asn1_gostr3410key_attr[C_ASN1_GOSTR3410KEY_ATTR_SIZE]; struct sc_asn1_entry asn1_prk_gostr3410_attr[C_ASN1_PRK_GOSTR3410_ATTR_SIZE]; struct sc_asn1_entry asn1_ecckey_attr[C_ASN1_ECCKEY_ATTR]; struct sc_asn1_entry asn1_prk_ecc_attr[C_ASN1_PRK_ECC_ATTR]; struct sc_asn1_entry asn1_prkey[C_ASN1_PRKEY_SIZE]; struct sc_asn1_entry asn1_supported_algorithms[C_ASN1_SUPPORTED_ALGORITHMS_SIZE]; struct sc_asn1_pkcs15_object rsa_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_rsa_attr}; struct sc_asn1_pkcs15_object dsa_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_dsa_attr}; struct sc_asn1_pkcs15_object gostr3410_prkey_obj = {obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_gostr3410_attr}; struct sc_asn1_pkcs15_object ecc_prkey_obj = { obj, asn1_com_key_attr, asn1_com_prkey_attr, asn1_prk_ecc_attr }; sc_copy_asn1_entry(c_asn1_prkey, asn1_prkey); sc_copy_asn1_entry(c_asn1_supported_algorithms, asn1_supported_algorithms); sc_copy_asn1_entry(c_asn1_prk_rsa_attr, asn1_prk_rsa_attr); sc_copy_asn1_entry(c_asn1_rsakey_attr, asn1_rsakey_attr); sc_copy_asn1_entry(c_asn1_prk_dsa_attr, asn1_prk_dsa_attr); sc_copy_asn1_entry(c_asn1_dsakey_attr, asn1_dsakey_attr); sc_copy_asn1_entry(c_asn1_dsakey_value_attr, asn1_dsakey_value_attr); sc_copy_asn1_entry(c_asn1_dsakey_i_p_attr, asn1_dsakey_i_p_attr); sc_copy_asn1_entry(c_asn1_prk_gostr3410_attr, asn1_prk_gostr3410_attr); sc_copy_asn1_entry(c_asn1_gostr3410key_attr, asn1_gostr3410key_attr); sc_copy_asn1_entry(c_asn1_prk_ecc_attr, asn1_prk_ecc_attr); sc_copy_asn1_entry(c_asn1_ecckey_attr, asn1_ecckey_attr); sc_copy_asn1_entry(c_asn1_com_prkey_attr, asn1_com_prkey_attr); sc_copy_asn1_entry(c_asn1_com_key_attr, asn1_com_key_attr); sc_format_asn1_entry(asn1_prkey + 0, &rsa_prkey_obj, NULL, 0); sc_format_asn1_entry(asn1_prkey + 1, &ecc_prkey_obj, NULL, 0); sc_format_asn1_entry(asn1_prkey + 2, &dsa_prkey_obj, NULL, 0); sc_format_asn1_entry(asn1_prkey + 3, &gostr3410_prkey_obj, NULL, 0); sc_format_asn1_entry(asn1_prk_rsa_attr + 0, asn1_rsakey_attr, NULL, 0); sc_format_asn1_entry(asn1_prk_dsa_attr + 0, asn1_dsakey_attr, NULL, 0); sc_format_asn1_entry(asn1_prk_gostr3410_attr + 0, asn1_gostr3410key_attr, NULL, 0); sc_format_asn1_entry(asn1_prk_ecc_attr + 0, asn1_ecckey_attr, NULL, 0); sc_format_asn1_entry(asn1_rsakey_attr + 0, &info.path, NULL, 0); sc_format_asn1_entry(asn1_rsakey_attr + 1, &info.modulus_length, NULL, 0); sc_format_asn1_entry(asn1_dsakey_attr + 0, asn1_dsakey_value_attr, NULL, 0); sc_format_asn1_entry(asn1_dsakey_value_attr + 0, &info.path, NULL, 0); sc_format_asn1_entry(asn1_dsakey_value_attr + 1, asn1_dsakey_i_p_attr, NULL, 0); sc_format_asn1_entry(asn1_dsakey_i_p_attr + 0, &info.path, NULL, 0); sc_format_asn1_entry(asn1_gostr3410key_attr + 0, &info.path, NULL, 0); sc_format_asn1_entry(asn1_gostr3410key_attr + 1, &gostr3410_params[0], NULL, 0); sc_format_asn1_entry(asn1_gostr3410key_attr + 2, &gostr3410_params[1], NULL, 0); sc_format_asn1_entry(asn1_gostr3410key_attr + 3, &gostr3410_params[2], NULL, 0); sc_format_asn1_entry(asn1_ecckey_attr + 0, &info.path, NULL, 0); sc_format_asn1_entry(asn1_ecckey_attr + 1, &info.field_length, NULL, 0); sc_format_asn1_entry(asn1_com_key_attr + 0, &info.id, NULL, 0); sc_format_asn1_entry(asn1_com_key_attr + 1, &info.usage, &usage_len, 0); sc_format_asn1_entry(asn1_com_key_attr + 2, &info.native, NULL, 0); sc_format_asn1_entry(asn1_com_key_attr + 3, &info.access_flags, &af_len, 0); sc_format_asn1_entry(asn1_com_key_attr + 4, &info.key_reference, NULL, 0); for (i=0; i<SC_MAX_SUPPORTED_ALGORITHMS && (asn1_supported_algorithms + i)->name; i++) sc_format_asn1_entry(asn1_supported_algorithms + i, &info.algo_refs[i], NULL, 0); sc_format_asn1_entry(asn1_com_key_attr + 5, asn1_supported_algorithms, NULL, 0); sc_format_asn1_entry(asn1_com_prkey_attr + 0, &info.subject.value, &info.subject.len, 0); /* Fill in defaults */ memset(&info, 0, sizeof(info)); info.key_reference = -1; info.native = 1; memset(gostr3410_params, 0, sizeof(gostr3410_params)); r = sc_asn1_decode_choice(ctx, asn1_prkey, *buf, *buflen, buf, buflen); if (r == SC_ERROR_ASN1_END_OF_CONTENTS) return r; LOG_TEST_RET(ctx, r, "PrKey DF ASN.1 decoding failed"); if (asn1_prkey[0].flags & SC_ASN1_PRESENT) { obj->type = SC_PKCS15_TYPE_PRKEY_RSA; } else if (asn1_prkey[1].flags & SC_ASN1_PRESENT) { obj->type = SC_PKCS15_TYPE_PRKEY_EC; } else if (asn1_prkey[2].flags & SC_ASN1_PRESENT) { obj->type = SC_PKCS15_TYPE_PRKEY_DSA; /* If the value was indirect-protected, mark the path */ if (asn1_dsakey_i_p_attr[0].flags & SC_ASN1_PRESENT) info.path.type = SC_PATH_TYPE_PATH_PROT; } else if (asn1_prkey[3].flags & SC_ASN1_PRESENT) { obj->type = SC_PKCS15_TYPE_PRKEY_GOSTR3410; assert(info.modulus_length == 0); info.modulus_length = SC_PKCS15_GOSTR3410_KEYSIZE; assert(info.params.len == 0); info.params.len = sizeof(struct sc_pkcs15_keyinfo_gostparams); info.params.data = malloc(info.params.len); if (info.params.data == NULL) LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); assert(sizeof(*keyinfo_gostparams) == info.params.len); keyinfo_gostparams = info.params.data; keyinfo_gostparams->gostr3410 = gostr3410_params[0]; keyinfo_gostparams->gostr3411 = gostr3410_params[1]; keyinfo_gostparams->gost28147 = gostr3410_params[2]; } else { sc_log(ctx, "Neither RSA or DSA or GOSTR3410 or ECC key in PrKDF entry."); LOG_FUNC_RETURN(ctx, SC_ERROR_INVALID_ASN1_OBJECT); } if (!p15card->app || !p15card->app->ddo.aid.len) { r = sc_pkcs15_make_absolute_path(&p15card->file_app->path, &info.path); if (r < 0) { sc_pkcs15_free_key_params(&info.params); return r; } } else { info.path.aid = p15card->app->ddo.aid; } sc_log(ctx, "PrivKey path '%s'", sc_print_path(&info.path)); /* OpenSC 0.11.4 and older encoded "keyReference" as a negative value. * Fixed in 0.11.5 we need to add a hack, so old cards continue to work. */ if (info.key_reference < -1) info.key_reference += 256; /* Check the auth_id - if not present, try and find it in access rules */ if ((obj->flags & SC_PKCS15_CO_FLAG_PRIVATE) && (obj->auth_id.len == 0)) { sc_log(ctx, "Private key %s has no auth ID - checking AccessControlRules", sc_pkcs15_print_id(&info.id)); /* Search in the access_rules for an appropriate auth ID */ for (i = 0; i < SC_PKCS15_MAX_ACCESS_RULES; i++) { /* If access_mode is one of the private key usage modes */ if (obj->access_rules[i].access_mode & (SC_PKCS15_ACCESS_RULE_MODE_EXECUTE | SC_PKCS15_ACCESS_RULE_MODE_PSO_CDS | SC_PKCS15_ACCESS_RULE_MODE_PSO_DECRYPT | SC_PKCS15_ACCESS_RULE_MODE_INT_AUTH)) { if (obj->access_rules[i].auth_id.len != 0) { /* Found an auth ID to use for private key access */ obj->auth_id = obj->access_rules[i].auth_id; sc_log(ctx, "Auth ID found - %s", sc_pkcs15_print_id(&obj->auth_id)); break; } } } /* No auth ID found */ if (i == SC_PKCS15_MAX_ACCESS_RULES) sc_log(ctx, "Warning: No auth ID found"); } obj->data = malloc(sizeof(info)); if (obj->data == NULL) { sc_pkcs15_free_key_params(&info.params); LOG_FUNC_RETURN(ctx, SC_ERROR_OUT_OF_MEMORY); } memcpy(obj->data, &info, sizeof(info)); sc_log(ctx, "Key Subject %s", sc_dump_hex(info.subject.value, info.subject.len)); sc_log(ctx, "Key path %s", sc_print_path(&info.path)); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-672'], 'message': 'pkcs15-prkey: Avoid memory leak https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=16625'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int cac_cac1_get_certificate(sc_card_t *card, u8 **out_buf, size_t *out_len) { u8 buf[CAC_MAX_SIZE]; u8 *out_ptr; size_t size = 0; size_t left = 0; size_t len, next_len; sc_apdu_t apdu; int r = SC_SUCCESS; SC_FUNC_CALLED(card->ctx, SC_LOG_DEBUG_VERBOSE); /* get the size */ size = left = *out_buf ? *out_len : sizeof(buf); out_ptr = *out_buf ? *out_buf : buf; sc_format_apdu(card, &apdu, SC_APDU_CASE_2_SHORT, CAC_INS_GET_CERTIFICATE, 0, 0 ); next_len = MIN(left, 100); for (; left > 0; left -= len, out_ptr += len) { len = next_len; apdu.resp = out_ptr; apdu.le = len; apdu.resplen = left; r = sc_transmit_apdu(card, &apdu); if (r < 0) { break; } if (apdu.resplen == 0) { r = SC_ERROR_INTERNAL; break; } /* in the old CAC-1, 0x63 means 'more data' in addition to 'pin failed' */ if (apdu.sw1 != 0x63 || apdu.sw2 < 1) { /* we've either finished reading, or hit an error, break */ r = sc_check_sw(card, apdu.sw1, apdu.sw2); left -= len; break; } next_len = MIN(left, apdu.sw2); } if (r < 0) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } r = size - left; if (*out_buf == NULL) { *out_buf = malloc(r); if (*out_buf == NULL) { SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, SC_ERROR_OUT_OF_MEMORY); } memcpy(*out_buf, buf, r); } *out_len = r; SC_FUNC_RETURN(card->ctx, SC_LOG_DEBUG_VERBOSE, r); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'cac1: Correctly handle the buffer limits Found by oss-fuzz https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=18618 and others'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void renameTableFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ sqlite3 *db = sqlite3_context_db_handle(context); const char *zDb = (const char*)sqlite3_value_text(argv[0]); const char *zInput = (const char*)sqlite3_value_text(argv[3]); const char *zOld = (const char*)sqlite3_value_text(argv[4]); const char *zNew = (const char*)sqlite3_value_text(argv[5]); int bTemp = sqlite3_value_int(argv[6]); UNUSED_PARAMETER(NotUsed); if( zInput && zOld && zNew ){ Parse sParse; int rc; int bQuote = 1; RenameCtx sCtx; Walker sWalker; #ifndef SQLITE_OMIT_AUTHORIZATION sqlite3_xauth xAuth = db->xAuth; db->xAuth = 0; #endif sqlite3BtreeEnterAll(db); memset(&sCtx, 0, sizeof(RenameCtx)); sCtx.pTab = sqlite3FindTable(db, zOld, zDb); memset(&sWalker, 0, sizeof(Walker)); sWalker.pParse = &sParse; sWalker.xExprCallback = renameTableExprCb; sWalker.xSelectCallback = renameTableSelectCb; sWalker.u.pRename = &sCtx; rc = renameParseSql(&sParse, zDb, 1, db, zInput, bTemp); if( rc==SQLITE_OK ){ int isLegacy = (db->flags & SQLITE_LegacyAlter); if( sParse.pNewTable ){ Table *pTab = sParse.pNewTable; if( pTab->pSelect ){ if( isLegacy==0 ){ NameContext sNC; memset(&sNC, 0, sizeof(sNC)); sNC.pParse = &sParse; sqlite3SelectPrep(&sParse, pTab->pSelect, &sNC); if( sParse.nErr ) rc = sParse.rc; sqlite3WalkSelect(&sWalker, pTab->pSelect); } }else{ /* Modify any FK definitions to point to the new table. */ #ifndef SQLITE_OMIT_FOREIGN_KEY if( isLegacy==0 || (db->flags & SQLITE_ForeignKeys) ){ FKey *pFKey; for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){ if( sqlite3_stricmp(pFKey->zTo, zOld)==0 ){ renameTokenFind(&sParse, &sCtx, (void*)pFKey->zTo); } } } #endif /* If this is the table being altered, fix any table refs in CHECK ** expressions. Also update the name that appears right after the ** "CREATE [VIRTUAL] TABLE" bit. */ if( sqlite3_stricmp(zOld, pTab->zName)==0 ){ sCtx.pTab = pTab; if( isLegacy==0 ){ sqlite3WalkExprList(&sWalker, pTab->pCheck); } renameTokenFind(&sParse, &sCtx, pTab->zName); } } } else if( sParse.pNewIndex ){ renameTokenFind(&sParse, &sCtx, sParse.pNewIndex->zName); if( isLegacy==0 ){ sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); } } #ifndef SQLITE_OMIT_TRIGGER else{ Trigger *pTrigger = sParse.pNewTrigger; TriggerStep *pStep; if( 0==sqlite3_stricmp(sParse.pNewTrigger->table, zOld) && sCtx.pTab->pSchema==pTrigger->pTabSchema ){ renameTokenFind(&sParse, &sCtx, sParse.pNewTrigger->table); } if( isLegacy==0 ){ rc = renameResolveTrigger(&sParse, bTemp ? 0 : zDb); if( rc==SQLITE_OK ){ renameWalkTrigger(&sWalker, pTrigger); for(pStep=pTrigger->step_list; pStep; pStep=pStep->pNext){ if( pStep->zTarget && 0==sqlite3_stricmp(pStep->zTarget, zOld) ){ renameTokenFind(&sParse, &sCtx, pStep->zTarget); } } } } } #endif } if( rc==SQLITE_OK ){ rc = renameEditSql(context, &sCtx, zInput, zNew, bQuote); } if( rc!=SQLITE_OK ){ if( sParse.zErrMsg ){ renameColumnParseError(context, 0, argv[1], argv[2], &sParse); }else{ sqlite3_result_error_code(context, rc); } } renameParseCleanup(&sParse); renameTokenFree(db, sCtx.pList); sqlite3BtreeLeaveAll(db); #ifndef SQLITE_OMIT_AUTHORIZATION db->xAuth = xAuth; #endif } return; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Avoid infinite recursion in the ALTER TABLE code when a view contains an unused CTE that references, directly or indirectly, the view itself. FossilOrigin-Name: 1d2e53a39b87e364685e21de137655b6eee725e4c6d27fc90865072d7c5892b5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int renameColumnSelectCb(Walker *pWalker, Select *p){ renameWalkWith(pWalker, p); return WRC_Continue; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Avoid infinite recursion in the ALTER TABLE code when a view contains an unused CTE that references, directly or indirectly, the view itself. FossilOrigin-Name: 1d2e53a39b87e364685e21de137655b6eee725e4c6d27fc90865072d7c5892b5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void renameColumnFunc( sqlite3_context *context, int NotUsed, sqlite3_value **argv ){ sqlite3 *db = sqlite3_context_db_handle(context); RenameCtx sCtx; const char *zSql = (const char*)sqlite3_value_text(argv[0]); const char *zDb = (const char*)sqlite3_value_text(argv[3]); const char *zTable = (const char*)sqlite3_value_text(argv[4]); int iCol = sqlite3_value_int(argv[5]); const char *zNew = (const char*)sqlite3_value_text(argv[6]); int bQuote = sqlite3_value_int(argv[7]); int bTemp = sqlite3_value_int(argv[8]); const char *zOld; int rc; Parse sParse; Walker sWalker; Index *pIdx; int i; Table *pTab; #ifndef SQLITE_OMIT_AUTHORIZATION sqlite3_xauth xAuth = db->xAuth; #endif UNUSED_PARAMETER(NotUsed); if( zSql==0 ) return; if( zTable==0 ) return; if( zNew==0 ) return; if( iCol<0 ) return; sqlite3BtreeEnterAll(db); pTab = sqlite3FindTable(db, zTable, zDb); if( pTab==0 || iCol>=pTab->nCol ){ sqlite3BtreeLeaveAll(db); return; } zOld = pTab->aCol[iCol].zName; memset(&sCtx, 0, sizeof(sCtx)); sCtx.iCol = ((iCol==pTab->iPKey) ? -1 : iCol); #ifndef SQLITE_OMIT_AUTHORIZATION db->xAuth = 0; #endif rc = renameParseSql(&sParse, zDb, 0, db, zSql, bTemp); /* Find tokens that need to be replaced. */ memset(&sWalker, 0, sizeof(Walker)); sWalker.pParse = &sParse; sWalker.xExprCallback = renameColumnExprCb; sWalker.xSelectCallback = renameColumnSelectCb; sWalker.u.pRename = &sCtx; sCtx.pTab = pTab; if( rc!=SQLITE_OK ) goto renameColumnFunc_done; if( sParse.pNewTable ){ Select *pSelect = sParse.pNewTable->pSelect; if( pSelect ){ sParse.rc = SQLITE_OK; sqlite3SelectPrep(&sParse, sParse.pNewTable->pSelect, 0); rc = (db->mallocFailed ? SQLITE_NOMEM : sParse.rc); if( rc==SQLITE_OK ){ sqlite3WalkSelect(&sWalker, pSelect); } if( rc!=SQLITE_OK ) goto renameColumnFunc_done; }else{ /* A regular table */ int bFKOnly = sqlite3_stricmp(zTable, sParse.pNewTable->zName); FKey *pFKey; assert( sParse.pNewTable->pSelect==0 ); sCtx.pTab = sParse.pNewTable; if( bFKOnly==0 ){ renameTokenFind( &sParse, &sCtx, (void*)sParse.pNewTable->aCol[iCol].zName ); if( sCtx.iCol<0 ){ renameTokenFind(&sParse, &sCtx, (void*)&sParse.pNewTable->iPKey); } sqlite3WalkExprList(&sWalker, sParse.pNewTable->pCheck); for(pIdx=sParse.pNewTable->pIndex; pIdx; pIdx=pIdx->pNext){ sqlite3WalkExprList(&sWalker, pIdx->aColExpr); } for(pIdx=sParse.pNewIndex; pIdx; pIdx=pIdx->pNext){ sqlite3WalkExprList(&sWalker, pIdx->aColExpr); } } #ifndef SQLITE_OMIT_GENERATED_COLUMNS for(i=0; i<sParse.pNewTable->nCol; i++){ sqlite3WalkExpr(&sWalker, sParse.pNewTable->aCol[i].pDflt); } #endif for(pFKey=sParse.pNewTable->pFKey; pFKey; pFKey=pFKey->pNextFrom){ for(i=0; i<pFKey->nCol; i++){ if( bFKOnly==0 && pFKey->aCol[i].iFrom==iCol ){ renameTokenFind(&sParse, &sCtx, (void*)&pFKey->aCol[i]); } if( 0==sqlite3_stricmp(pFKey->zTo, zTable) && 0==sqlite3_stricmp(pFKey->aCol[i].zCol, zOld) ){ renameTokenFind(&sParse, &sCtx, (void*)pFKey->aCol[i].zCol); } } } } }else if( sParse.pNewIndex ){ sqlite3WalkExprList(&sWalker, sParse.pNewIndex->aColExpr); sqlite3WalkExpr(&sWalker, sParse.pNewIndex->pPartIdxWhere); }else{ /* A trigger */ TriggerStep *pStep; rc = renameResolveTrigger(&sParse, (bTemp ? 0 : zDb)); if( rc!=SQLITE_OK ) goto renameColumnFunc_done; for(pStep=sParse.pNewTrigger->step_list; pStep; pStep=pStep->pNext){ if( pStep->zTarget ){ Table *pTarget = sqlite3LocateTable(&sParse, 0, pStep->zTarget, zDb); if( pTarget==pTab ){ if( pStep->pUpsert ){ ExprList *pUpsertSet = pStep->pUpsert->pUpsertSet; renameColumnElistNames(&sParse, &sCtx, pUpsertSet, zOld); } renameColumnIdlistNames(&sParse, &sCtx, pStep->pIdList, zOld); renameColumnElistNames(&sParse, &sCtx, pStep->pExprList, zOld); } } } /* Find tokens to edit in UPDATE OF clause */ if( sParse.pTriggerTab==pTab ){ renameColumnIdlistNames(&sParse, &sCtx,sParse.pNewTrigger->pColumns,zOld); } /* Find tokens to edit in various expressions and selects */ renameWalkTrigger(&sWalker, sParse.pNewTrigger); } assert( rc==SQLITE_OK ); rc = renameEditSql(context, &sCtx, zSql, zNew, bQuote); renameColumnFunc_done: if( rc!=SQLITE_OK ){ if( sParse.zErrMsg ){ renameColumnParseError(context, 0, argv[1], argv[2], &sParse); }else{ sqlite3_result_error_code(context, rc); } } renameParseCleanup(&sParse); renameTokenFree(db, sCtx.pList); #ifndef SQLITE_OMIT_AUTHORIZATION db->xAuth = xAuth; #endif sqlite3BtreeLeaveAll(db); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-674', 'CWE-787'], 'message': 'Avoid infinite recursion in the ALTER TABLE code when a view contains an unused CTE that references, directly or indirectly, the view itself. FossilOrigin-Name: 1d2e53a39b87e364685e21de137655b6eee725e4c6d27fc90865072d7c5892b5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ml_ff_destroy(struct ff_device *ff) { struct ml_device *ml = ff->private; kfree(ml->private); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Input: ff-memless - kill timer in destroy() No timer must be left running when the device goes away. Signed-off-by: Oliver Neukum <oneukum@suse.com> Reported-and-tested-by: syzbot+b6c55daa701fc389e286@syzkaller.appspotmail.com Cc: stable@vger.kernel.org Link: https://lore.kernel.org/r/1573726121.17351.3.camel@suse.com Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pn533_usb_probe(struct usb_interface *interface, const struct usb_device_id *id) { struct pn533 *priv; struct pn533_usb_phy *phy; struct usb_host_interface *iface_desc; struct usb_endpoint_descriptor *endpoint; int in_endpoint = 0; int out_endpoint = 0; int rc = -ENOMEM; int i; u32 protocols; enum pn533_protocol_type protocol_type = PN533_PROTO_REQ_ACK_RESP; struct pn533_frame_ops *fops = NULL; unsigned char *in_buf; int in_buf_len = PN533_EXT_FRAME_HEADER_LEN + PN533_STD_FRAME_MAX_PAYLOAD_LEN + PN533_STD_FRAME_TAIL_LEN; phy = devm_kzalloc(&interface->dev, sizeof(*phy), GFP_KERNEL); if (!phy) return -ENOMEM; in_buf = kzalloc(in_buf_len, GFP_KERNEL); if (!in_buf) return -ENOMEM; phy->udev = usb_get_dev(interface_to_usbdev(interface)); phy->interface = interface; iface_desc = interface->cur_altsetting; for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) { endpoint = &iface_desc->endpoint[i].desc; if (!in_endpoint && usb_endpoint_is_bulk_in(endpoint)) in_endpoint = endpoint->bEndpointAddress; if (!out_endpoint && usb_endpoint_is_bulk_out(endpoint)) out_endpoint = endpoint->bEndpointAddress; } if (!in_endpoint || !out_endpoint) { nfc_err(&interface->dev, "Could not find bulk-in or bulk-out endpoint\n"); rc = -ENODEV; goto error; } phy->in_urb = usb_alloc_urb(0, GFP_KERNEL); phy->out_urb = usb_alloc_urb(0, GFP_KERNEL); phy->ack_urb = usb_alloc_urb(0, GFP_KERNEL); if (!phy->in_urb || !phy->out_urb || !phy->ack_urb) goto error; usb_fill_bulk_urb(phy->in_urb, phy->udev, usb_rcvbulkpipe(phy->udev, in_endpoint), in_buf, in_buf_len, NULL, phy); usb_fill_bulk_urb(phy->out_urb, phy->udev, usb_sndbulkpipe(phy->udev, out_endpoint), NULL, 0, pn533_send_complete, phy); usb_fill_bulk_urb(phy->ack_urb, phy->udev, usb_sndbulkpipe(phy->udev, out_endpoint), NULL, 0, pn533_send_complete, phy); switch (id->driver_info) { case PN533_DEVICE_STD: protocols = PN533_ALL_PROTOCOLS; break; case PN533_DEVICE_PASORI: protocols = PN533_NO_TYPE_B_PROTOCOLS; break; case PN533_DEVICE_ACR122U: protocols = PN533_NO_TYPE_B_PROTOCOLS; fops = &pn533_acr122_frame_ops; protocol_type = PN533_PROTO_REQ_RESP, rc = pn533_acr122_poweron_rdr(phy); if (rc < 0) { nfc_err(&interface->dev, "Couldn't poweron the reader (error %d)\n", rc); goto error; } break; default: nfc_err(&interface->dev, "Unknown device type %lu\n", id->driver_info); rc = -EINVAL; goto error; } priv = pn533_register_device(id->driver_info, protocols, protocol_type, phy, &usb_phy_ops, fops, &phy->udev->dev, &interface->dev); if (IS_ERR(priv)) { rc = PTR_ERR(priv); goto error; } phy->priv = priv; rc = pn533_finalize_setup(priv); if (rc) goto error; usb_set_intfdata(interface, phy); return 0; error: usb_free_urb(phy->in_urb); usb_free_urb(phy->out_urb); usb_free_urb(phy->ack_urb); usb_put_dev(phy->udev); kfree(in_buf); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'NFC: pn533: fix use-after-free and memleaks The driver would fail to deregister and its class device and free related resources on late probe errors. Reported-by: syzbot+cb035c75c03dbe34b796@syzkaller.appspotmail.com Fixes: 32ecc75ded72 ("NFC: pn533: change order operations in dev registation") Signed-off-by: Johan Hovold <johan@kernel.org> Signed-off-by: Jakub Kicinski <jakub.kicinski@netronome.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int hiddev_open(struct inode *inode, struct file *file) { struct hiddev_list *list; struct usb_interface *intf; struct hid_device *hid; struct hiddev *hiddev; int res; intf = usbhid_find_interface(iminor(inode)); if (!intf) return -ENODEV; hid = usb_get_intfdata(intf); hiddev = hid->hiddev; if (!(list = vzalloc(sizeof(struct hiddev_list)))) return -ENOMEM; mutex_init(&list->thread_lock); list->hiddev = hiddev; file->private_data = list; /* * no need for locking because the USB major number * is shared which usbcore guards against disconnect */ if (list->hiddev->exist) { if (!list->hiddev->open++) { res = hid_hw_open(hiddev->hid); if (res < 0) goto bail; } } else { res = -ENODEV; goto bail; } spin_lock_irq(&list->hiddev->list_lock); list_add_tail(&list->node, &hiddev->list); spin_unlock_irq(&list->hiddev->list_lock); mutex_lock(&hiddev->existancelock); if (!list->hiddev->open++) if (list->hiddev->exist) { struct hid_device *hid = hiddev->hid; res = hid_hw_power(hid, PM_HINT_FULLON); if (res < 0) goto bail_unlock; res = hid_hw_open(hid); if (res < 0) goto bail_normal_power; } mutex_unlock(&hiddev->existancelock); return 0; bail_normal_power: hid_hw_power(hid, PM_HINT_NORMAL); bail_unlock: mutex_unlock(&hiddev->existancelock); bail: file->private_data = NULL; vfree(list); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'HID: hiddev: avoid opening a disconnected device syzbot found the following crash on: HEAD commit: e96407b4 usb-fuzzer: main usb gadget fuzzer driver git tree: https://github.com/google/kasan.git usb-fuzzer console output: https://syzkaller.appspot.com/x/log.txt?x=147ac20c600000 kernel config: https://syzkaller.appspot.com/x/.config?x=792eb47789f57810 dashboard link: https://syzkaller.appspot.com/bug?extid=62a1e04fd3ec2abf099e compiler: gcc (GCC) 9.0.0 20181231 (experimental) ================================================================== BUG: KASAN: use-after-free in __lock_acquire+0x302a/0x3b50 kernel/locking/lockdep.c:3753 Read of size 8 at addr ffff8881cf591a08 by task syz-executor.1/26260 CPU: 1 PID: 26260 Comm: syz-executor.1 Not tainted 5.3.0-rc2+ #24 Hardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 01/01/2011 Call Trace: __dump_stack lib/dump_stack.c:77 [inline] dump_stack+0xca/0x13e lib/dump_stack.c:113 print_address_description+0x6a/0x32c mm/kasan/report.c:351 __kasan_report.cold+0x1a/0x33 mm/kasan/report.c:482 kasan_report+0xe/0x12 mm/kasan/common.c:612 __lock_acquire+0x302a/0x3b50 kernel/locking/lockdep.c:3753 lock_acquire+0x127/0x320 kernel/locking/lockdep.c:4412 __raw_spin_lock_irqsave include/linux/spinlock_api_smp.h:110 [inline] _raw_spin_lock_irqsave+0x32/0x50 kernel/locking/spinlock.c:159 hiddev_release+0x82/0x520 drivers/hid/usbhid/hiddev.c:221 __fput+0x2d7/0x840 fs/file_table.c:280 task_work_run+0x13f/0x1c0 kernel/task_work.c:113 exit_task_work include/linux/task_work.h:22 [inline] do_exit+0x8ef/0x2c50 kernel/exit.c:878 do_group_exit+0x125/0x340 kernel/exit.c:982 get_signal+0x466/0x23d0 kernel/signal.c:2728 do_signal+0x88/0x14e0 arch/x86/kernel/signal.c:815 exit_to_usermode_loop+0x1a2/0x200 arch/x86/entry/common.c:159 prepare_exit_to_usermode arch/x86/entry/common.c:194 [inline] syscall_return_slowpath arch/x86/entry/common.c:274 [inline] do_syscall_64+0x45f/0x580 arch/x86/entry/common.c:299 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x459829 Code: fd b7 fb ff c3 66 2e 0f 1f 84 00 00 00 00 00 66 90 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 0f 83 cb b7 fb ff c3 66 2e 0f 1f 84 00 00 00 00 RSP: 002b:00007f75b2a6ccf8 EFLAGS: 00000246 ORIG_RAX: 00000000000000ca RAX: fffffffffffffe00 RBX: 000000000075c078 RCX: 0000000000459829 RDX: 0000000000000000 RSI: 0000000000000080 RDI: 000000000075c078 RBP: 000000000075c070 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 000000000075c07c R13: 00007ffcdfe1023f R14: 00007f75b2a6d9c0 R15: 000000000075c07c Allocated by task 104: save_stack+0x1b/0x80 mm/kasan/common.c:69 set_track mm/kasan/common.c:77 [inline] __kasan_kmalloc mm/kasan/common.c:487 [inline] __kasan_kmalloc.constprop.0+0xbf/0xd0 mm/kasan/common.c:460 kmalloc include/linux/slab.h:552 [inline] kzalloc include/linux/slab.h:748 [inline] hiddev_connect+0x242/0x5b0 drivers/hid/usbhid/hiddev.c:900 hid_connect+0x239/0xbb0 drivers/hid/hid-core.c:1882 hid_hw_start drivers/hid/hid-core.c:1981 [inline] hid_hw_start+0xa2/0x130 drivers/hid/hid-core.c:1972 appleir_probe+0x13e/0x1a0 drivers/hid/hid-appleir.c:308 hid_device_probe+0x2be/0x3f0 drivers/hid/hid-core.c:2209 really_probe+0x281/0x650 drivers/base/dd.c:548 driver_probe_device+0x101/0x1b0 drivers/base/dd.c:709 __device_attach_driver+0x1c2/0x220 drivers/base/dd.c:816 bus_for_each_drv+0x15c/0x1e0 drivers/base/bus.c:454 __device_attach+0x217/0x360 drivers/base/dd.c:882 bus_probe_device+0x1e4/0x290 drivers/base/bus.c:514 device_add+0xae6/0x16f0 drivers/base/core.c:2114 hid_add_device+0x33c/0x990 drivers/hid/hid-core.c:2365 usbhid_probe+0xa81/0xfa0 drivers/hid/usbhid/hid-core.c:1386 usb_probe_interface+0x305/0x7a0 drivers/usb/core/driver.c:361 really_probe+0x281/0x650 drivers/base/dd.c:548 driver_probe_device+0x101/0x1b0 drivers/base/dd.c:709 __device_attach_driver+0x1c2/0x220 drivers/base/dd.c:816 bus_for_each_drv+0x15c/0x1e0 drivers/base/bus.c:454 __device_attach+0x217/0x360 drivers/base/dd.c:882 bus_probe_device+0x1e4/0x290 drivers/base/bus.c:514 device_add+0xae6/0x16f0 drivers/base/core.c:2114 usb_set_configuration+0xdf6/0x1670 drivers/usb/core/message.c:2023 generic_probe+0x9d/0xd5 drivers/usb/core/generic.c:210 usb_probe_device+0x99/0x100 drivers/usb/core/driver.c:266 really_probe+0x281/0x650 drivers/base/dd.c:548 driver_probe_device+0x101/0x1b0 drivers/base/dd.c:709 __device_attach_driver+0x1c2/0x220 drivers/base/dd.c:816 bus_for_each_drv+0x15c/0x1e0 drivers/base/bus.c:454 __device_attach+0x217/0x360 drivers/base/dd.c:882 bus_probe_device+0x1e4/0x290 drivers/base/bus.c:514 device_add+0xae6/0x16f0 drivers/base/core.c:2114 usb_new_device.cold+0x6a4/0xe79 drivers/usb/core/hub.c:2536 hub_port_connect drivers/usb/core/hub.c:5098 [inline] hub_port_connect_change drivers/usb/core/hub.c:5213 [inline] port_event drivers/usb/core/hub.c:5359 [inline] hub_event+0x1b5c/0x3640 drivers/usb/core/hub.c:5441 process_one_work+0x92b/0x1530 kernel/workqueue.c:2269 worker_thread+0x96/0xe20 kernel/workqueue.c:2415 kthread+0x318/0x420 kernel/kthread.c:255 ret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352 Freed by task 104: save_stack+0x1b/0x80 mm/kasan/common.c:69 set_track mm/kasan/common.c:77 [inline] __kasan_slab_free+0x130/0x180 mm/kasan/common.c:449 slab_free_hook mm/slub.c:1423 [inline] slab_free_freelist_hook mm/slub.c:1470 [inline] slab_free mm/slub.c:3012 [inline] kfree+0xe4/0x2f0 mm/slub.c:3953 hiddev_connect.cold+0x45/0x5c drivers/hid/usbhid/hiddev.c:914 hid_connect+0x239/0xbb0 drivers/hid/hid-core.c:1882 hid_hw_start drivers/hid/hid-core.c:1981 [inline] hid_hw_start+0xa2/0x130 drivers/hid/hid-core.c:1972 appleir_probe+0x13e/0x1a0 drivers/hid/hid-appleir.c:308 hid_device_probe+0x2be/0x3f0 drivers/hid/hid-core.c:2209 really_probe+0x281/0x650 drivers/base/dd.c:548 driver_probe_device+0x101/0x1b0 drivers/base/dd.c:709 __device_attach_driver+0x1c2/0x220 drivers/base/dd.c:816 bus_for_each_drv+0x15c/0x1e0 drivers/base/bus.c:454 __device_attach+0x217/0x360 drivers/base/dd.c:882 bus_probe_device+0x1e4/0x290 drivers/base/bus.c:514 device_add+0xae6/0x16f0 drivers/base/core.c:2114 hid_add_device+0x33c/0x990 drivers/hid/hid-core.c:2365 usbhid_probe+0xa81/0xfa0 drivers/hid/usbhid/hid-core.c:1386 usb_probe_interface+0x305/0x7a0 drivers/usb/core/driver.c:361 really_probe+0x281/0x650 drivers/base/dd.c:548 driver_probe_device+0x101/0x1b0 drivers/base/dd.c:709 __device_attach_driver+0x1c2/0x220 drivers/base/dd.c:816 bus_for_each_drv+0x15c/0x1e0 drivers/base/bus.c:454 __device_attach+0x217/0x360 drivers/base/dd.c:882 bus_probe_device+0x1e4/0x290 drivers/base/bus.c:514 device_add+0xae6/0x16f0 drivers/base/core.c:2114 usb_set_configuration+0xdf6/0x1670 drivers/usb/core/message.c:2023 generic_probe+0x9d/0xd5 drivers/usb/core/generic.c:210 usb_probe_device+0x99/0x100 drivers/usb/core/driver.c:266 really_probe+0x281/0x650 drivers/base/dd.c:548 driver_probe_device+0x101/0x1b0 drivers/base/dd.c:709 __device_attach_driver+0x1c2/0x220 drivers/base/dd.c:816 bus_for_each_drv+0x15c/0x1e0 drivers/base/bus.c:454 __device_attach+0x217/0x360 drivers/base/dd.c:882 bus_probe_device+0x1e4/0x290 drivers/base/bus.c:514 device_add+0xae6/0x16f0 drivers/base/core.c:2114 usb_new_device.cold+0x6a4/0xe79 drivers/usb/core/hub.c:2536 hub_port_connect drivers/usb/core/hub.c:5098 [inline] hub_port_connect_change drivers/usb/core/hub.c:5213 [inline] port_event drivers/usb/core/hub.c:5359 [inline] hub_event+0x1b5c/0x3640 drivers/usb/core/hub.c:5441 process_one_work+0x92b/0x1530 kernel/workqueue.c:2269 worker_thread+0x96/0xe20 kernel/workqueue.c:2415 kthread+0x318/0x420 kernel/kthread.c:255 ret_from_fork+0x24/0x30 arch/x86/entry/entry_64.S:352 The buggy address belongs to the object at ffff8881cf591900 which belongs to the cache kmalloc-512 of size 512 The buggy address is located 264 bytes inside of 512-byte region [ffff8881cf591900, ffff8881cf591b00) The buggy address belongs to the page: page:ffffea00073d6400 refcount:1 mapcount:0 mapping:ffff8881da002500 index:0x0 compound_mapcount: 0 flags: 0x200000000010200(slab|head) raw: 0200000000010200 0000000000000000 0000000100000001 ffff8881da002500 raw: 0000000000000000 00000000000c000c 00000001ffffffff 0000000000000000 page dumped because: kasan: bad access detected Memory state around the buggy address: ffff8881cf591900: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8881cf591980: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb > ffff8881cf591a00: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ^ ffff8881cf591a80: fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb fb ffff8881cf591b00: fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc fc ================================================================== In order to avoid opening a disconnected device, we need to check exist again after acquiring the existance lock, and bail out if necessary. Reported-by: syzbot <syzbot+62a1e04fd3ec2abf099e@syzkaller.appspotmail.com> Cc: Andrey Konovalov <andreyknvl@google.com> Signed-off-by: Hillf Danton <hdanton@sina.com> Signed-off-by: Jiri Kosina <jkosina@suse.cz>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void iowarrior_disconnect(struct usb_interface *interface) { struct iowarrior *dev; int minor; dev = usb_get_intfdata(interface); mutex_lock(&iowarrior_open_disc_lock); usb_set_intfdata(interface, NULL); minor = dev->minor; /* give back our minor */ usb_deregister_dev(interface, &iowarrior_class); mutex_lock(&dev->mutex); /* prevent device read, write and ioctl */ dev->present = 0; mutex_unlock(&dev->mutex); mutex_unlock(&iowarrior_open_disc_lock); if (dev->opened) { /* There is a process that holds a filedescriptor to the device , so we only shutdown read-/write-ops going on. Deleting the device is postponed until close() was called. */ usb_kill_urb(dev->int_in_urb); wake_up_interruptible(&dev->read_wait); wake_up_interruptible(&dev->write_wait); } else { /* no process is using the device, cleanup now */ iowarrior_delete(dev); } dev_info(&interface->dev, "I/O-Warror #%d now disconnected\n", minor - IOWARRIOR_MINOR_BASE); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'usb: iowarrior: fix deadlock on disconnect We have to drop the mutex before we close() upon disconnect() as close() needs the lock. This is safe to do by dropping the mutex as intfdata is already set to NULL, so open() will fail. Fixes: 03f36e885fc26 ("USB: open disconnect race in iowarrior") Reported-by: syzbot+a64a382964bf6c71a9c0@syzkaller.appspotmail.com Cc: stable <stable@vger.kernel.org> Signed-off-by: Oliver Neukum <oneukum@suse.com> Link: https://lore.kernel.org/r/20190808092728.23417-1-oneukum@suse.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int acm_probe(struct usb_interface *intf, const struct usb_device_id *id) { struct usb_cdc_union_desc *union_header = NULL; struct usb_cdc_call_mgmt_descriptor *cmgmd = NULL; unsigned char *buffer = intf->altsetting->extra; int buflen = intf->altsetting->extralen; struct usb_interface *control_interface; struct usb_interface *data_interface; struct usb_endpoint_descriptor *epctrl = NULL; struct usb_endpoint_descriptor *epread = NULL; struct usb_endpoint_descriptor *epwrite = NULL; struct usb_device *usb_dev = interface_to_usbdev(intf); struct usb_cdc_parsed_header h; struct acm *acm; int minor; int ctrlsize, readsize; u8 *buf; int call_intf_num = -1; int data_intf_num = -1; unsigned long quirks; int num_rx_buf; int i; int combined_interfaces = 0; struct device *tty_dev; int rv = -ENOMEM; int res; /* normal quirks */ quirks = (unsigned long)id->driver_info; if (quirks == IGNORE_DEVICE) return -ENODEV; memset(&h, 0x00, sizeof(struct usb_cdc_parsed_header)); num_rx_buf = (quirks == SINGLE_RX_URB) ? 1 : ACM_NR; /* handle quirks deadly to normal probing*/ if (quirks == NO_UNION_NORMAL) { data_interface = usb_ifnum_to_if(usb_dev, 1); control_interface = usb_ifnum_to_if(usb_dev, 0); /* we would crash */ if (!data_interface || !control_interface) return -ENODEV; goto skip_normal_probe; } /* normal probing*/ if (!buffer) { dev_err(&intf->dev, "Weird descriptor references\n"); return -EINVAL; } if (!intf->cur_altsetting) return -EINVAL; if (!buflen) { if (intf->cur_altsetting->endpoint && intf->cur_altsetting->endpoint->extralen && intf->cur_altsetting->endpoint->extra) { dev_dbg(&intf->dev, "Seeking extra descriptors on endpoint\n"); buflen = intf->cur_altsetting->endpoint->extralen; buffer = intf->cur_altsetting->endpoint->extra; } else { dev_err(&intf->dev, "Zero length descriptor references\n"); return -EINVAL; } } cdc_parse_cdc_header(&h, intf, buffer, buflen); union_header = h.usb_cdc_union_desc; cmgmd = h.usb_cdc_call_mgmt_descriptor; if (cmgmd) call_intf_num = cmgmd->bDataInterface; if (!union_header) { if (call_intf_num > 0) { dev_dbg(&intf->dev, "No union descriptor, using call management descriptor\n"); /* quirks for Droids MuIn LCD */ if (quirks & NO_DATA_INTERFACE) { data_interface = usb_ifnum_to_if(usb_dev, 0); } else { data_intf_num = call_intf_num; data_interface = usb_ifnum_to_if(usb_dev, data_intf_num); } control_interface = intf; } else { if (intf->cur_altsetting->desc.bNumEndpoints != 3) { dev_dbg(&intf->dev,"No union descriptor, giving up\n"); return -ENODEV; } else { dev_warn(&intf->dev,"No union descriptor, testing for castrated device\n"); combined_interfaces = 1; control_interface = data_interface = intf; goto look_for_collapsed_interface; } } } else { data_intf_num = union_header->bSlaveInterface0; control_interface = usb_ifnum_to_if(usb_dev, union_header->bMasterInterface0); data_interface = usb_ifnum_to_if(usb_dev, data_intf_num); } if (!control_interface || !data_interface) { dev_dbg(&intf->dev, "no interfaces\n"); return -ENODEV; } if (!data_interface->cur_altsetting || !control_interface->cur_altsetting) return -ENODEV; if (data_intf_num != call_intf_num) dev_dbg(&intf->dev, "Separate call control interface. That is not fully supported.\n"); if (control_interface == data_interface) { /* some broken devices designed for windows work this way */ dev_warn(&intf->dev,"Control and data interfaces are not separated!\n"); combined_interfaces = 1; /* a popular other OS doesn't use it */ quirks |= NO_CAP_LINE; if (data_interface->cur_altsetting->desc.bNumEndpoints != 3) { dev_err(&intf->dev, "This needs exactly 3 endpoints\n"); return -EINVAL; } look_for_collapsed_interface: res = usb_find_common_endpoints(data_interface->cur_altsetting, &epread, &epwrite, &epctrl, NULL); if (res) return res; goto made_compressed_probe; } skip_normal_probe: /*workaround for switched interfaces */ if (data_interface->cur_altsetting->desc.bInterfaceClass != CDC_DATA_INTERFACE_TYPE) { if (control_interface->cur_altsetting->desc.bInterfaceClass == CDC_DATA_INTERFACE_TYPE) { dev_dbg(&intf->dev, "Your device has switched interfaces.\n"); swap(control_interface, data_interface); } else { return -EINVAL; } } /* Accept probe requests only for the control interface */ if (!combined_interfaces && intf != control_interface) return -ENODEV; if (!combined_interfaces && usb_interface_claimed(data_interface)) { /* valid in this context */ dev_dbg(&intf->dev, "The data interface isn't available\n"); return -EBUSY; } if (data_interface->cur_altsetting->desc.bNumEndpoints < 2 || control_interface->cur_altsetting->desc.bNumEndpoints == 0) return -EINVAL; epctrl = &control_interface->cur_altsetting->endpoint[0].desc; epread = &data_interface->cur_altsetting->endpoint[0].desc; epwrite = &data_interface->cur_altsetting->endpoint[1].desc; /* workaround for switched endpoints */ if (!usb_endpoint_dir_in(epread)) { /* descriptors are swapped */ dev_dbg(&intf->dev, "The data interface has switched endpoints\n"); swap(epread, epwrite); } made_compressed_probe: dev_dbg(&intf->dev, "interfaces are valid\n"); acm = kzalloc(sizeof(struct acm), GFP_KERNEL); if (acm == NULL) goto alloc_fail; tty_port_init(&acm->port); acm->port.ops = &acm_port_ops; minor = acm_alloc_minor(acm); if (minor < 0) goto alloc_fail1; ctrlsize = usb_endpoint_maxp(epctrl); readsize = usb_endpoint_maxp(epread) * (quirks == SINGLE_RX_URB ? 1 : 2); acm->combined_interfaces = combined_interfaces; acm->writesize = usb_endpoint_maxp(epwrite) * 20; acm->control = control_interface; acm->data = data_interface; acm->minor = minor; acm->dev = usb_dev; if (h.usb_cdc_acm_descriptor) acm->ctrl_caps = h.usb_cdc_acm_descriptor->bmCapabilities; if (quirks & NO_CAP_LINE) acm->ctrl_caps &= ~USB_CDC_CAP_LINE; acm->ctrlsize = ctrlsize; acm->readsize = readsize; acm->rx_buflimit = num_rx_buf; INIT_WORK(&acm->work, acm_softint); init_waitqueue_head(&acm->wioctl); spin_lock_init(&acm->write_lock); spin_lock_init(&acm->read_lock); mutex_init(&acm->mutex); if (usb_endpoint_xfer_int(epread)) { acm->bInterval = epread->bInterval; acm->in = usb_rcvintpipe(usb_dev, epread->bEndpointAddress); } else { acm->in = usb_rcvbulkpipe(usb_dev, epread->bEndpointAddress); } if (usb_endpoint_xfer_int(epwrite)) acm->out = usb_sndintpipe(usb_dev, epwrite->bEndpointAddress); else acm->out = usb_sndbulkpipe(usb_dev, epwrite->bEndpointAddress); init_usb_anchor(&acm->delayed); acm->quirks = quirks; buf = usb_alloc_coherent(usb_dev, ctrlsize, GFP_KERNEL, &acm->ctrl_dma); if (!buf) goto alloc_fail1; acm->ctrl_buffer = buf; if (acm_write_buffers_alloc(acm) < 0) goto alloc_fail2; acm->ctrlurb = usb_alloc_urb(0, GFP_KERNEL); if (!acm->ctrlurb) goto alloc_fail3; for (i = 0; i < num_rx_buf; i++) { struct acm_rb *rb = &(acm->read_buffers[i]); struct urb *urb; rb->base = usb_alloc_coherent(acm->dev, readsize, GFP_KERNEL, &rb->dma); if (!rb->base) goto alloc_fail4; rb->index = i; rb->instance = acm; urb = usb_alloc_urb(0, GFP_KERNEL); if (!urb) goto alloc_fail4; urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; urb->transfer_dma = rb->dma; if (usb_endpoint_xfer_int(epread)) usb_fill_int_urb(urb, acm->dev, acm->in, rb->base, acm->readsize, acm_read_bulk_callback, rb, acm->bInterval); else usb_fill_bulk_urb(urb, acm->dev, acm->in, rb->base, acm->readsize, acm_read_bulk_callback, rb); acm->read_urbs[i] = urb; __set_bit(i, &acm->read_urbs_free); } for (i = 0; i < ACM_NW; i++) { struct acm_wb *snd = &(acm->wb[i]); snd->urb = usb_alloc_urb(0, GFP_KERNEL); if (snd->urb == NULL) goto alloc_fail5; if (usb_endpoint_xfer_int(epwrite)) usb_fill_int_urb(snd->urb, usb_dev, acm->out, NULL, acm->writesize, acm_write_bulk, snd, epwrite->bInterval); else usb_fill_bulk_urb(snd->urb, usb_dev, acm->out, NULL, acm->writesize, acm_write_bulk, snd); snd->urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; if (quirks & SEND_ZERO_PACKET) snd->urb->transfer_flags |= URB_ZERO_PACKET; snd->instance = acm; } usb_set_intfdata(intf, acm); i = device_create_file(&intf->dev, &dev_attr_bmCapabilities); if (i < 0) goto alloc_fail5; if (h.usb_cdc_country_functional_desc) { /* export the country data */ struct usb_cdc_country_functional_desc * cfd = h.usb_cdc_country_functional_desc; acm->country_codes = kmalloc(cfd->bLength - 4, GFP_KERNEL); if (!acm->country_codes) goto skip_countries; acm->country_code_size = cfd->bLength - 4; memcpy(acm->country_codes, (u8 *)&cfd->wCountyCode0, cfd->bLength - 4); acm->country_rel_date = cfd->iCountryCodeRelDate; i = device_create_file(&intf->dev, &dev_attr_wCountryCodes); if (i < 0) { kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } i = device_create_file(&intf->dev, &dev_attr_iCountryCodeRelDate); if (i < 0) { device_remove_file(&intf->dev, &dev_attr_wCountryCodes); kfree(acm->country_codes); acm->country_codes = NULL; acm->country_code_size = 0; goto skip_countries; } } skip_countries: usb_fill_int_urb(acm->ctrlurb, usb_dev, usb_rcvintpipe(usb_dev, epctrl->bEndpointAddress), acm->ctrl_buffer, ctrlsize, acm_ctrl_irq, acm, /* works around buggy devices */ epctrl->bInterval ? epctrl->bInterval : 16); acm->ctrlurb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP; acm->ctrlurb->transfer_dma = acm->ctrl_dma; acm->notification_buffer = NULL; acm->nb_index = 0; acm->nb_size = 0; dev_info(&intf->dev, "ttyACM%d: USB ACM device\n", minor); acm->line.dwDTERate = cpu_to_le32(9600); acm->line.bDataBits = 8; acm_set_line(acm, &acm->line); usb_driver_claim_interface(&acm_driver, data_interface, acm); usb_set_intfdata(data_interface, acm); usb_get_intf(control_interface); tty_dev = tty_port_register_device(&acm->port, acm_tty_driver, minor, &control_interface->dev); if (IS_ERR(tty_dev)) { rv = PTR_ERR(tty_dev); goto alloc_fail6; } if (quirks & CLEAR_HALT_CONDITIONS) { usb_clear_halt(usb_dev, acm->in); usb_clear_halt(usb_dev, acm->out); } return 0; alloc_fail6: if (acm->country_codes) { device_remove_file(&acm->control->dev, &dev_attr_wCountryCodes); device_remove_file(&acm->control->dev, &dev_attr_iCountryCodeRelDate); kfree(acm->country_codes); } device_remove_file(&acm->control->dev, &dev_attr_bmCapabilities); alloc_fail5: usb_set_intfdata(intf, NULL); for (i = 0; i < ACM_NW; i++) usb_free_urb(acm->wb[i].urb); alloc_fail4: for (i = 0; i < num_rx_buf; i++) usb_free_urb(acm->read_urbs[i]); acm_read_buffers_free(acm); usb_free_urb(acm->ctrlurb); alloc_fail3: acm_write_buffers_free(acm); alloc_fail2: usb_free_coherent(usb_dev, ctrlsize, acm->ctrl_buffer, acm->ctrl_dma); alloc_fail1: tty_port_put(&acm->port); alloc_fail: return rv; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'usb: cdc-acm: make sure a refcount is taken early enough destroy() will decrement the refcount on the interface, so that it needs to be taken so early that it never undercounts. Fixes: 7fb57a019f94e ("USB: cdc-acm: Fix potential deadlock (lockdep warning)") Cc: stable <stable@vger.kernel.org> Reported-and-tested-by: syzbot+1b2449b7b5dc240d107a@syzkaller.appspotmail.com Signed-off-by: Oliver Neukum <oneukum@suse.com> Link: https://lore.kernel.org/r/20190808142119.7998-1-oneukum@suse.com Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ttusb_dec_send_command(struct ttusb_dec *dec, const u8 command, int param_length, const u8 params[], int *result_length, u8 cmd_result[]) { int result, actual_len; u8 *b; dprintk("%s\n", __func__); b = kmalloc(COMMAND_PACKET_SIZE + 4, GFP_KERNEL); if (!b) return -ENOMEM; if ((result = mutex_lock_interruptible(&dec->usb_mutex))) { kfree(b); printk("%s: Failed to lock usb mutex.\n", __func__); return result; } b[0] = 0xaa; b[1] = ++dec->trans_count; b[2] = command; b[3] = param_length; if (params) memcpy(&b[4], params, param_length); if (debug) { printk(KERN_DEBUG "%s: command: %*ph\n", __func__, param_length, b); } result = usb_bulk_msg(dec->udev, dec->command_pipe, b, COMMAND_PACKET_SIZE + 4, &actual_len, 1000); if (result) { printk("%s: command bulk message failed: error %d\n", __func__, result); mutex_unlock(&dec->usb_mutex); kfree(b); return result; } result = usb_bulk_msg(dec->udev, dec->result_pipe, b, COMMAND_PACKET_SIZE + 4, &actual_len, 1000); if (result) { printk("%s: result bulk message failed: error %d\n", __func__, result); mutex_unlock(&dec->usb_mutex); kfree(b); return result; } else { if (debug) { printk(KERN_DEBUG "%s: result: %*ph\n", __func__, actual_len, b); } if (result_length) *result_length = b[3]; if (cmd_result && b[3] > 0) memcpy(cmd_result, &b[4], b[3]); mutex_unlock(&dec->usb_mutex); kfree(b); return 0; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-772'], 'message': 'media: ttusb-dec: Fix info-leak in ttusb_dec_send_command() The function at issue does not always initialize each byte allocated for 'b' and can therefore leak uninitialized memory to a USB device in the call to usb_bulk_msg() Use kzalloc() instead of kmalloc() Signed-off-by: Tomas Bortoli <tomasbortoli@gmail.com> Reported-by: syzbot+0522702e9d67142379f1@syzkaller.appspotmail.com Signed-off-by: Sean Young <sean@mess.org> Signed-off-by: Mauro Carvalho Chehab <mchehab+samsung@kernel.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int pcan_usb_fd_init(struct peak_usb_device *dev) { struct pcan_usb_fd_device *pdev = container_of(dev, struct pcan_usb_fd_device, dev); int i, err = -ENOMEM; /* do this for 1st channel only */ if (!dev->prev_siblings) { /* allocate netdevices common structure attached to first one */ pdev->usb_if = kzalloc(sizeof(*pdev->usb_if), GFP_KERNEL); if (!pdev->usb_if) goto err_out; /* allocate command buffer once for all for the interface */ pdev->cmd_buffer_addr = kmalloc(PCAN_UFD_CMD_BUFFER_SIZE, GFP_KERNEL); if (!pdev->cmd_buffer_addr) goto err_out_1; /* number of ts msgs to ignore before taking one into account */ pdev->usb_if->cm_ignore_count = 5; err = pcan_usb_pro_send_req(dev, PCAN_USBPRO_REQ_INFO, PCAN_USBPRO_INFO_FW, &pdev->usb_if->fw_info, sizeof(pdev->usb_if->fw_info)); if (err) { dev_err(dev->netdev->dev.parent, "unable to read %s firmware info (err %d)\n", dev->adapter->name, err); goto err_out_2; } /* explicit use of dev_xxx() instead of netdev_xxx() here: * information displayed are related to the device itself, not * to the canx (channel) device. */ dev_info(dev->netdev->dev.parent, "PEAK-System %s v%u fw v%u.%u.%u (%u channels)\n", dev->adapter->name, pdev->usb_if->fw_info.hw_version, pdev->usb_if->fw_info.fw_version[0], pdev->usb_if->fw_info.fw_version[1], pdev->usb_if->fw_info.fw_version[2], dev->adapter->ctrl_count); /* check for ability to switch between ISO/non-ISO modes */ if (pdev->usb_if->fw_info.fw_version[0] >= 2) { /* firmware >= 2.x supports ISO/non-ISO switching */ dev->can.ctrlmode_supported |= CAN_CTRLMODE_FD_NON_ISO; } else { /* firmware < 2.x only supports fixed(!) non-ISO */ dev->can.ctrlmode |= CAN_CTRLMODE_FD_NON_ISO; } /* tell the hardware the can driver is running */ err = pcan_usb_fd_drv_loaded(dev, 1); if (err) { dev_err(dev->netdev->dev.parent, "unable to tell %s driver is loaded (err %d)\n", dev->adapter->name, err); goto err_out_2; } } else { /* otherwise, simply copy previous sibling's values */ struct pcan_usb_fd_device *ppdev = container_of(dev->prev_siblings, struct pcan_usb_fd_device, dev); pdev->usb_if = ppdev->usb_if; pdev->cmd_buffer_addr = ppdev->cmd_buffer_addr; /* do a copy of the ctrlmode[_supported] too */ dev->can.ctrlmode = ppdev->dev.can.ctrlmode; dev->can.ctrlmode_supported = ppdev->dev.can.ctrlmode_supported; } pdev->usb_if->dev[dev->ctrl_idx] = dev; dev->device_number = le32_to_cpu(pdev->usb_if->fw_info.dev_id[dev->ctrl_idx]); /* set clock domain */ for (i = 0; i < ARRAY_SIZE(pcan_usb_fd_clk_freq); i++) if (dev->adapter->clock.freq == pcan_usb_fd_clk_freq[i]) break; if (i >= ARRAY_SIZE(pcan_usb_fd_clk_freq)) { dev_warn(dev->netdev->dev.parent, "incompatible clock frequencies\n"); err = -EINVAL; goto err_out_2; } pcan_usb_fd_set_clock_domain(dev, i); /* set LED in default state (end of init phase) */ pcan_usb_fd_set_can_led(dev, PCAN_UFD_LED_DEF); return 0; err_out_2: kfree(pdev->cmd_buffer_addr); err_out_1: kfree(pdev->usb_if); err_out: return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-908'], 'message': 'can: peak_usb: pcan_usb_fd: Fix info-leaks to USB devices Uninitialized Kernel memory can leak to USB devices. Fix by using kzalloc() instead of kmalloc() on the affected buffers. Signed-off-by: Tomas Bortoli <tomasbortoli@gmail.com> Reported-by: syzbot+513e4d0985298538bf9b@syzkaller.appspotmail.com Fixes: 0a25e1f4f185 ("can: peak_usb: add support for PEAK new CANFD USB adapters") Cc: linux-stable <stable@vger.kernel.org> Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void usb_deregister_dev(struct usb_interface *intf, struct usb_class_driver *class_driver) { if (intf->minor == -1) return; dev_dbg(&intf->dev, "removing %d minor\n", intf->minor); down_write(&minor_rwsem); usb_minors[intf->minor] = NULL; up_write(&minor_rwsem); device_destroy(usb_class->class, MKDEV(USB_MAJOR, intf->minor)); intf->usb_dev = NULL; intf->minor = -1; destroy_usb_class(); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-362'], 'message': 'USB: core: Fix races in character device registration and deregistraion The syzbot fuzzer has found two (!) races in the USB character device registration and deregistration routines. This patch fixes the races. The first race results from the fact that usb_deregister_dev() sets usb_minors[intf->minor] to NULL before calling device_destroy() on the class device. This leaves a window during which another thread can allocate the same minor number but will encounter a duplicate name error when it tries to register its own class device. A typical error message in the system log would look like: sysfs: cannot create duplicate filename '/class/usbmisc/ldusb0' The patch fixes this race by destroying the class device first. The second race is in usb_register_dev(). When that routine runs, it first allocates a minor number, then drops minor_rwsem, and then creates the class device. If the device creation fails, the minor number is deallocated and the whole routine returns an error. But during the time while minor_rwsem was dropped, there is a window in which the minor number is allocated and so another thread can successfully open the device file. Typically this results in use-after-free errors or invalid accesses when the other thread closes its open file reference, because the kernel then tries to release resources that were already deallocated when usb_register_dev() failed. The patch fixes this race by keeping minor_rwsem locked throughout the entire routine. Reported-and-tested-by: syzbot+30cf45ebfe0b0c4847a1@syzkaller.appspotmail.com Signed-off-by: Alan Stern <stern@rowland.harvard.edu> CC: <stable@vger.kernel.org> Link: https://lore.kernel.org/r/Pine.LNX.4.44L0.1908121607590.1659-100000@iolanthe.rowland.org Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int lookupName( Parse *pParse, /* The parsing context */ const char *zDb, /* Name of the database containing table, or NULL */ const char *zTab, /* Name of table containing column, or NULL */ const char *zCol, /* Name of the column. */ NameContext *pNC, /* The name context used to resolve the name */ Expr *pExpr /* Make this EXPR node point to the selected column */ ){ int i, j; /* Loop counters */ int cnt = 0; /* Number of matching column names */ int cntTab = 0; /* Number of matching table names */ int nSubquery = 0; /* How many levels of subquery */ sqlite3 *db = pParse->db; /* The database connection */ struct SrcList_item *pItem; /* Use for looping over pSrcList items */ struct SrcList_item *pMatch = 0; /* The matching pSrcList item */ NameContext *pTopNC = pNC; /* First namecontext in the list */ Schema *pSchema = 0; /* Schema of the expression */ int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */ Table *pTab = 0; /* Table hold the row */ Column *pCol; /* A column of pTab */ assert( pNC ); /* the name context cannot be NULL. */ assert( zCol ); /* The Z in X.Y.Z cannot be NULL */ assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) ); /* Initialize the node to no-match */ pExpr->iTable = -1; ExprSetVVAProperty(pExpr, EP_NoReduce); /* Translate the schema name in zDb into a pointer to the corresponding ** schema. If not found, pSchema will remain NULL and nothing will match ** resulting in an appropriate error message toward the end of this routine */ if( zDb ){ testcase( pNC->ncFlags & NC_PartIdx ); testcase( pNC->ncFlags & NC_IsCheck ); if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){ /* Silently ignore database qualifiers inside CHECK constraints and ** partial indices. Do not raise errors because that might break ** legacy and because it does not hurt anything to just ignore the ** database name. */ zDb = 0; }else{ for(i=0; i<db->nDb; i++){ assert( db->aDb[i].zDbSName ); if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){ pSchema = db->aDb[i].pSchema; break; } } } } /* Start at the inner-most context and move outward until a match is found */ assert( pNC && cnt==0 ); do{ ExprList *pEList; SrcList *pSrcList = pNC->pSrcList; if( pSrcList ){ for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){ pTab = pItem->pTab; assert( pTab!=0 && pTab->zName!=0 ); assert( pTab->nCol>0 ); if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){ int hit = 0; pEList = pItem->pSelect->pEList; for(j=0; j<pEList->nExpr; j++){ if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){ cnt++; cntTab = 2; pMatch = pItem; pExpr->iColumn = j; hit = 1; } } if( hit || zTab==0 ) continue; } if( zDb && pTab->pSchema!=pSchema ){ continue; } if( zTab ){ const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName; assert( zTabName!=0 ); if( sqlite3StrICmp(zTabName, zTab)!=0 ){ continue; } if( IN_RENAME_OBJECT && pItem->zAlias ){ sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab); } } if( 0==(cntTab++) ){ pMatch = pItem; } for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ /* If there has been exactly one prior match and this match ** is for the right-hand table of a NATURAL JOIN or is in a ** USING clause, then skip this match. */ if( cnt==1 ){ if( pItem->fg.jointype & JT_NATURAL ) continue; if( nameInUsingClause(pItem->pUsing, zCol) ) continue; } cnt++; pMatch = pItem; /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */ pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j; break; } } } if( pMatch ){ pExpr->iTable = pMatch->iCursor; pExpr->y.pTab = pMatch->pTab; /* RIGHT JOIN not (yet) supported */ assert( (pMatch->fg.jointype & JT_RIGHT)==0 ); if( (pMatch->fg.jointype & JT_LEFT)!=0 ){ ExprSetProperty(pExpr, EP_CanBeNull); } pSchema = pExpr->y.pTab->pSchema; } } /* if( pSrcList ) */ #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) /* If we have not already resolved the name, then maybe ** it is a new.* or old.* trigger argument reference. Or ** maybe it is an excluded.* from an upsert. */ if( zDb==0 && zTab!=0 && cntTab==0 ){ pTab = 0; #ifndef SQLITE_OMIT_TRIGGER if( pParse->pTriggerTab!=0 ){ int op = pParse->eTriggerOp; assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT ); if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){ pExpr->iTable = 1; pTab = pParse->pTriggerTab; }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){ pExpr->iTable = 0; pTab = pParse->pTriggerTab; } } #endif /* SQLITE_OMIT_TRIGGER */ #ifndef SQLITE_OMIT_UPSERT if( (pNC->ncFlags & NC_UUpsert)!=0 ){ Upsert *pUpsert = pNC->uNC.pUpsert; if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){ pTab = pUpsert->pUpsertSrc->a[0].pTab; pExpr->iTable = 2; } } #endif /* SQLITE_OMIT_UPSERT */ if( pTab ){ int iCol; pSchema = pTab->pSchema; cntTab++; for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){ if( sqlite3StrICmp(pCol->zName, zCol)==0 ){ if( iCol==pTab->iPKey ){ iCol = -1; } break; } } if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){ /* IMP: R-51414-32910 */ iCol = -1; } if( iCol<pTab->nCol ){ cnt++; #ifndef SQLITE_OMIT_UPSERT if( pExpr->iTable==2 ){ testcase( iCol==(-1) ); if( IN_RENAME_OBJECT ){ pExpr->iColumn = iCol; pExpr->y.pTab = pTab; eNewExprOp = TK_COLUMN; }else{ pExpr->iTable = pNC->uNC.pUpsert->regData + iCol; eNewExprOp = TK_REGISTER; ExprSetProperty(pExpr, EP_Alias); } }else #endif /* SQLITE_OMIT_UPSERT */ { #ifndef SQLITE_OMIT_TRIGGER if( iCol<0 ){ pExpr->affExpr = SQLITE_AFF_INTEGER; }else if( pExpr->iTable==0 ){ testcase( iCol==31 ); testcase( iCol==32 ); pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); }else{ testcase( iCol==31 ); testcase( iCol==32 ); pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol)); } pExpr->y.pTab = pTab; pExpr->iColumn = (i16)iCol; eNewExprOp = TK_TRIGGER; #endif /* SQLITE_OMIT_TRIGGER */ } } } } #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */ /* ** Perhaps the name is a reference to the ROWID */ if( cnt==0 && cntTab==1 && pMatch && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0 && sqlite3IsRowid(zCol) && VisibleRowid(pMatch->pTab) ){ cnt = 1; pExpr->iColumn = -1; pExpr->affExpr = SQLITE_AFF_INTEGER; } /* ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z ** might refer to an result-set alias. This happens, for example, when ** we are resolving names in the WHERE clause of the following command: ** ** SELECT a+b AS x FROM table WHERE x<10; ** ** In cases like this, replace pExpr with a copy of the expression that ** forms the result set entry ("a+b" in the example) and return immediately. ** Note that the expression in the result set should have already been ** resolved by the time the WHERE clause is resolved. ** ** The ability to use an output result-set column in the WHERE, GROUP BY, ** or HAVING clauses, or as part of a larger expression in the ORDER BY ** clause is not standard SQL. This is a (goofy) SQLite extension, that ** is supported for backwards compatibility only. Hence, we issue a warning ** on sqlite3_log() whenever the capability is used. */ if( (pNC->ncFlags & NC_UEList)!=0 && cnt==0 && zTab==0 ){ pEList = pNC->uNC.pEList; assert( pEList!=0 ); for(j=0; j<pEList->nExpr; j++){ char *zAs = pEList->a[j].zName; if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){ Expr *pOrig; assert( pExpr->pLeft==0 && pExpr->pRight==0 ); assert( pExpr->x.pList==0 ); assert( pExpr->x.pSelect==0 ); pOrig = pEList->a[j].pExpr; if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){ sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs); return WRC_Abort; } if( (pNC->ncFlags&NC_AllowWin)==0 && ExprHasProperty(pOrig, EP_Win) ){ sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs); return WRC_Abort; } if( sqlite3ExprVectorSize(pOrig)!=1 ){ sqlite3ErrorMsg(pParse, "row value misused"); return WRC_Abort; } resolveAlias(pParse, pEList, j, pExpr, "", nSubquery); cnt = 1; pMatch = 0; assert( zTab==0 && zDb==0 ); if( IN_RENAME_OBJECT ){ sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr); } goto lookupname_end; } } } /* Advance to the next name context. The loop will exit when either ** we have a match (cnt>0) or when we run out of name contexts. */ if( cnt ) break; pNC = pNC->pNext; nSubquery++; }while( pNC ); /* ** If X and Y are NULL (in other words if only the column name Z is ** supplied) and the value of Z is enclosed in double-quotes, then ** Z is a string literal if it doesn't match any column names. In that ** case, we need to return right away and not make any changes to ** pExpr. ** ** Because no reference was made to outer contexts, the pNC->nRef ** fields are not changed in any context. */ if( cnt==0 && zTab==0 ){ assert( pExpr->op==TK_ID ); if( ExprHasProperty(pExpr,EP_DblQuoted) && areDoubleQuotedStringsEnabled(db, pTopNC) ){ /* If a double-quoted identifier does not match any known column name, ** then treat it as a string. ** ** This hack was added in the early days of SQLite in a misguided attempt ** to be compatible with MySQL 3.x, which used double-quotes for strings. ** I now sorely regret putting in this hack. The effect of this hack is ** that misspelled identifier names are silently converted into strings ** rather than causing an error, to the frustration of countless ** programmers. To all those frustrated programmers, my apologies. ** ** Someday, I hope to get rid of this hack. Unfortunately there is ** a huge amount of legacy SQL that uses it. So for now, we just ** issue a warning. */ sqlite3_log(SQLITE_WARNING, "double-quoted string literal: \"%w\"", zCol); #ifdef SQLITE_ENABLE_NORMALIZE sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol); #endif pExpr->op = TK_STRING; pExpr->y.pTab = 0; return WRC_Prune; } if( sqlite3ExprIdToTrueFalse(pExpr) ){ return WRC_Prune; } } /* ** cnt==0 means there was not match. cnt>1 means there were two or ** more matches. Either way, we have an error. */ if( cnt!=1 ){ const char *zErr; zErr = cnt==0 ? "no such column" : "ambiguous column name"; if( zDb ){ sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol); }else if( zTab ){ sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol); }else{ sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol); } pParse->checkSchema = 1; pTopNC->nErr++; } /* If a column from a table in pSrcList is referenced, then record ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the ** column number is greater than the number of bits in the bitmask ** then set the high-order bit of the bitmask. */ if( pExpr->iColumn>=0 && pMatch!=0 ){ int n = pExpr->iColumn; testcase( n==BMS-1 ); if( n>=BMS ){ n = BMS-1; } assert( pMatch->iCursor==pExpr->iTable ); pMatch->colUsed |= ((Bitmask)1)<<n; } /* Clean up and return */ sqlite3ExprDelete(db, pExpr->pLeft); pExpr->pLeft = 0; sqlite3ExprDelete(db, pExpr->pRight); pExpr->pRight = 0; pExpr->op = eNewExprOp; ExprSetProperty(pExpr, EP_Leaf); lookupname_end: if( cnt==1 ){ assert( pNC!=0 ); if( !ExprHasProperty(pExpr, EP_Alias) ){ sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList); } /* Increment the nRef value on all name contexts from TopNC up to ** the point where the name matched. */ for(;;){ assert( pTopNC!=0 ); pTopNC->nRef++; if( pTopNC==pNC ) break; pTopNC = pTopNC->pNext; } return WRC_Prune; } else { return WRC_Abort; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-703', 'CWE-681'], 'message': 'Whenever a generated column is used, assume that all columns are used. FossilOrigin-Name: 6601da58032d18ae00b466c0f2077fb2b1ecd84225b56e1787724bea478eedc9'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void check_file_actlst(int *ifd, char *dfile, struct activity *act[], uint64_t flags, struct file_magic *file_magic, struct file_header *file_hdr, struct file_activity **file_actlst, unsigned int id_seq[], int ignore, int *endian_mismatch, int *arch_64) { int i, j, k, p; struct file_activity *fal; void *buffer = NULL; size_t bh_size = FILE_HEADER_SIZE; size_t ba_size = FILE_ACTIVITY_SIZE; /* Open sa data file and read its magic structure */ if (sa_open_read_magic(ifd, dfile, file_magic, ignore, endian_mismatch, TRUE) < 0) /* * Not current sysstat's format. * Return now so that sadf -H can display at least * file's version and magic number. */ return; /* * We know now that we have a *compatible* sysstat datafile format * (correct FORMAT_MAGIC value), and in this case, we should have * checked header_size value. Anyway, with a corrupted datafile, * this may not be the case. So check again. */ if ((file_magic->header_size <= MIN_FILE_HEADER_SIZE) || (file_magic->header_size > MAX_FILE_HEADER_SIZE)) { #ifdef DEBUG fprintf(stderr, "%s: header_size=%u\n", __FUNCTION__, file_magic->header_size); #endif goto format_error; } /* Allocate buffer for file_header structure */ if (file_magic->header_size > FILE_HEADER_SIZE) { bh_size = file_magic->header_size; } SREALLOC(buffer, char, bh_size); /* Read sa data file standard header and allocate activity list */ sa_fread(*ifd, buffer, (size_t) file_magic->header_size, HARD_SIZE, UEOF_STOP); /* * Data file header size (file_magic->header_size) may be greater or * smaller than FILE_HEADER_SIZE. Remap the fields of the file header * then copy its contents to the expected structure. */ if (remap_struct(hdr_types_nr, file_magic->hdr_types_nr, buffer, file_magic->header_size, FILE_HEADER_SIZE, bh_size) < 0) goto format_error; memcpy(file_hdr, buffer, FILE_HEADER_SIZE); free(buffer); buffer = NULL; /* Tell that data come from a 64 bit machine */ *arch_64 = (file_hdr->sa_sizeof_long == SIZEOF_LONG_64BIT); /* Normalize endianness for file_hdr structure */ if (*endian_mismatch) { swap_struct(hdr_types_nr, file_hdr, *arch_64); } /* * Sanity checks. * NB: Compare against MAX_NR_ACT and not NR_ACT because * we are maybe reading a datafile from a future sysstat version * with more activities than known today. */ if ((file_hdr->sa_act_nr > MAX_NR_ACT) || (file_hdr->act_size > MAX_FILE_ACTIVITY_SIZE) || (file_hdr->rec_size > MAX_RECORD_HEADER_SIZE) || (MAP_SIZE(file_hdr->act_types_nr) > file_hdr->act_size) || (MAP_SIZE(file_hdr->rec_types_nr) > file_hdr->rec_size)) { #ifdef DEBUG fprintf(stderr, "%s: sa_act_nr=%d act_size=%u rec_size=%u map_size(act)=%u map_size(rec)=%u\n", __FUNCTION__, file_hdr->sa_act_nr, file_hdr->act_size, file_hdr->rec_size, MAP_SIZE(file_hdr->act_types_nr), MAP_SIZE(file_hdr->rec_types_nr)); #endif /* Maybe a "false positive" sysstat datafile? */ goto format_error; } /* Allocate buffer for file_activity structures */ if (file_hdr->act_size > FILE_ACTIVITY_SIZE) { ba_size = file_hdr->act_size; } SREALLOC(buffer, char, ba_size); SREALLOC(*file_actlst, struct file_activity, FILE_ACTIVITY_SIZE * file_hdr->sa_act_nr); fal = *file_actlst; /* Read activity list */ j = 0; for (i = 0; i < file_hdr->sa_act_nr; i++, fal++) { /* Read current file_activity structure from file */ sa_fread(*ifd, buffer, (size_t) file_hdr->act_size, HARD_SIZE, UEOF_STOP); /* * Data file_activity size (file_hdr->act_size) may be greater or * smaller than FILE_ACTIVITY_SIZE. Remap the fields of the file's structure * then copy its contents to the expected structure. */ if (remap_struct(act_types_nr, file_hdr->act_types_nr, buffer, file_hdr->act_size, FILE_ACTIVITY_SIZE, ba_size) < 0) goto format_error; memcpy(fal, buffer, FILE_ACTIVITY_SIZE); /* Normalize endianness for file_activity structures */ if (*endian_mismatch) { swap_struct(act_types_nr, fal, *arch_64); } /* * Every activity, known or unknown, should have * at least one item and sub-item, and a positive size value. * Also check that the number of items and sub-items * doesn't exceed a max value. This is necessary * because we will use @nr and @nr2 to * allocate memory to read the file contents. So we * must make sure the file is not corrupted. * NB: Another check will be made below for known * activities which have each a specific max value. */ if ((fal->nr < 1) || (fal->nr2 < 1) || (fal->nr > NR_MAX) || (fal->nr2 > NR2_MAX) || (fal->size <= 0)) { #ifdef DEBUG fprintf(stderr, "%s: id=%d nr=%d nr2=%d\n", __FUNCTION__, fal->id, fal->nr, fal->nr2); #endif goto format_error; } if ((p = get_activity_position(act, fal->id, RESUME_IF_NOT_FOUND)) < 0) /* Unknown activity */ continue; if (act[p]->magic != fal->magic) { /* Bad magical number */ if (ignore) { /* * This is how sadf -H knows that this * activity has an unknown format. */ act[p]->magic = ACTIVITY_MAGIC_UNKNOWN; } else continue; } /* Check max value for known activities */ if (fal->nr > act[p]->nr_max) { #ifdef DEBUG fprintf(stderr, "%s: id=%d nr=%d nr_max=%d\n", __FUNCTION__, fal->id, fal->nr, act[p]->nr_max); #endif goto format_error; } /* * Number of fields of each type ("long long", or "long" * or "int") composing the structure with statistics may * only increase with new sysstat versions. Here, we may * be reading a file created by current sysstat version, * or by an older or a newer version. */ if (!(((fal->types_nr[0] >= act[p]->gtypes_nr[0]) && (fal->types_nr[1] >= act[p]->gtypes_nr[1]) && (fal->types_nr[2] >= act[p]->gtypes_nr[2])) || ((fal->types_nr[0] <= act[p]->gtypes_nr[0]) && (fal->types_nr[1] <= act[p]->gtypes_nr[1]) && (fal->types_nr[2] <= act[p]->gtypes_nr[2]))) && !ignore) { #ifdef DEBUG fprintf(stderr, "%s: id=%d file=%d,%d,%d activity=%d,%d,%d\n", __FUNCTION__, fal->id, fal->types_nr[0], fal->types_nr[1], fal->types_nr[2], act[p]->gtypes_nr[0], act[p]->gtypes_nr[1], act[p]->gtypes_nr[2]); #endif goto format_error; } if (MAP_SIZE(fal->types_nr) > fal->size) { #ifdef DEBUG fprintf(stderr, "%s: id=%d size=%u map_size=%u\n", __FUNCTION__, fal->id, fal->size, MAP_SIZE(fal->types_nr)); #endif goto format_error; } for (k = 0; k < 3; k++) { act[p]->ftypes_nr[k] = fal->types_nr[k]; } if (fal->size > act[p]->msize) { act[p]->msize = fal->size; } act[p]->nr_ini = fal->nr; act[p]->nr2 = fal->nr2; act[p]->fsize = fal->size; /* * This is a known activity with a known format * (magical number). Only such activities will be displayed. * (Well, this may also be an unknown format if we have entered sadf -H.) */ id_seq[j++] = fal->id; } while (j < NR_ACT) { id_seq[j++] = 0; } free(buffer); /* Check that at least one activity selected by the user is available in file */ for (i = 0; i < NR_ACT; i++) { if (!IS_SELECTED(act[i]->options)) continue; /* Here is a selected activity: Does it exist in file? */ fal = *file_actlst; for (j = 0; j < file_hdr->sa_act_nr; j++, fal++) { if (act[i]->id == fal->id) break; } if (j == file_hdr->sa_act_nr) { /* No: Unselect it */ act[i]->options &= ~AO_SELECTED; } } /* * None of selected activities exist in file: Abort. * NB: Error is ignored if we only want to display * datafile header (sadf -H). */ if (!get_activity_nr(act, AO_SELECTED, COUNT_ACTIVITIES) && !DISPLAY_HDR_ONLY(flags)) { fprintf(stderr, _("Requested activities not available in file %s\n"), dfile); close(*ifd); exit(1); } /* * Check if there are some extra structures. * We will just skip them as they are unknown for now. */ if (file_hdr->extra_next && (skip_extra_struct(*ifd, *endian_mismatch, *arch_64) < 0)) goto format_error; return; format_error: if (buffer) { free(buffer); } handle_invalid_sa_file(*ifd, file_magic, dfile, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'Fix #242: Double free in check_file_actlst() Avoid freeing buffer() twice. Signed-off-by: Sebastien GODARD <sysstat@users.noreply.github.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ext4_clamp_want_extra_isize(struct super_block *sb) { struct ext4_sb_info *sbi = EXT4_SB(sb); struct ext4_super_block *es = sbi->s_es; /* determine the minimum size of new large inodes, if present */ if (sbi->s_inode_size > EXT4_GOOD_OLD_INODE_SIZE && sbi->s_want_extra_isize == 0) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; if (ext4_has_feature_extra_isize(sb)) { if (sbi->s_want_extra_isize < le16_to_cpu(es->s_want_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_want_extra_isize); if (sbi->s_want_extra_isize < le16_to_cpu(es->s_min_extra_isize)) sbi->s_want_extra_isize = le16_to_cpu(es->s_min_extra_isize); } } /* Check if enough inode space is available */ if (EXT4_GOOD_OLD_INODE_SIZE + sbi->s_want_extra_isize > sbi->s_inode_size) { sbi->s_want_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; ext4_msg(sb, KERN_INFO, "required extra inode space not available"); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-401'], 'message': 'ext4: add more paranoia checking in ext4_expand_extra_isize handling It's possible to specify a non-zero s_want_extra_isize via debugging option, and this can cause bad things(tm) to happen when using a file system with an inode size of 128 bytes. Add better checking when the file system is mounted, as well as when we are actually doing the trying to do the inode expansion. Link: https://lore.kernel.org/r/20191110121510.GH23325@mit.edu Reported-by: syzbot+f8d6f8386ceacdbfff57@syzkaller.appspotmail.com Reported-by: syzbot+33d7ea72e47de3bdf4e1@syzkaller.appspotmail.com Reported-by: syzbot+44b6763edfc17144296f@syzkaller.appspotmail.com Signed-off-by: Theodore Ts'o <tytso@mit.edu> Cc: stable@kernel.org'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void spl_filesystem_object_construct(INTERNAL_FUNCTION_PARAMETERS, zend_long ctor_flags) /* {{{ */ { spl_filesystem_object *intern; char *path; int parsed; size_t len; zend_long flags; zend_error_handling error_handling; zend_replace_error_handling(EH_THROW, spl_ce_UnexpectedValueException, &error_handling); if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_FLAGS)) { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_FILEINFO; parsed = zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &path, &len, &flags); } else { flags = SPL_FILE_DIR_KEY_AS_PATHNAME|SPL_FILE_DIR_CURRENT_AS_SELF; parsed = zend_parse_parameters(ZEND_NUM_ARGS(), "s", &path, &len); } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_SKIPDOTS)) { flags |= SPL_FILE_DIR_SKIPDOTS; } if (SPL_HAS_FLAG(ctor_flags, SPL_FILE_DIR_UNIXPATHS)) { flags |= SPL_FILE_DIR_UNIXPATHS; } if (parsed == FAILURE) { zend_restore_error_handling(&error_handling); return; } if (!len) { zend_throw_exception_ex(spl_ce_RuntimeException, 0, "Directory name must not be empty."); zend_restore_error_handling(&error_handling); return; } intern = Z_SPLFILESYSTEM_P(getThis()); if (intern->_path) { /* object is alreay initialized */ zend_restore_error_handling(&error_handling); php_error_docref(NULL, E_WARNING, "Directory object is already initialized"); return; } intern->flags = flags; #ifdef HAVE_GLOB if (SPL_HAS_FLAG(ctor_flags, DIT_CTOR_GLOB) && strstr(path, "glob://") != path) { spprintf(&path, 0, "glob://%s", path); spl_filesystem_dir_open(intern, path); efree(path); } else #endif { spl_filesystem_dir_open(intern, path); } intern->u.dir.is_recursive = instanceof_function(intern->std.ce, spl_ce_RecursiveDirectoryIterator) ? 1 : 0; zend_restore_error_handling(&error_handling); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-74'], 'message': 'Fix #78863: DirectoryIterator class silently truncates after a null byte Since the constructor of DirectoryIterator and friends is supposed to accepts paths (i.e. strings without NUL bytes), we must not accept arbitrary strings.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int test_curve(int c) { spiro_cp spiro[16]; int nextknot[17]; double d[5]; spiro_seg *segs = NULL; bezctx *bc; rs_check_vals *rsp; int i,j,done; /* Load sample data so that we can see if library is callable */ load_test_curve(spiro,nextknot,c); d[0] = 1.; d[1] = d[1] = 0.; #if defined(DO_CALL_TEST20) /* check if spiro values are reversed correctly on input path */ printf("---\ntesting spiroreverse() using data=path%d[].\n",c); if ( (spiroreverse(spiro,cl[c])) ) { fprintf(stderr,"error with spiroreverse() using data=path%d[].\n",c); return -1; } /* just do a visual check to verify types and points look ok. */ /* NOTE: spiro[] is NOT replaced if unable to reverse values. */ for (i=0; i < cl[c]; i++) { printf(" reversed %d: ty=%c, x=%g, y=%g\n", i,spiro[i].ty,spiro[i].x,spiro[i].y); } #else #if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) #if defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) /* run_spiro0 with various paths to test a simple arc output. */ d[0] = -1.; printf("---\ntesting run_spiro0(q) using data=path%d[].\n",c); if ( (segs=run_spiro0(spiro,d,SPIRO_ARC_MAYBE,cl[c]))==0 ) { fprintf(stderr,"error with run_spiro0(q) using data=path%d[].\n",c); return -1; } #else /* Do run_spiro0 instead (these tests are far from -0.5..+0.5 */ d[0] = -1.; printf("---\ntesting run_spiro0() using data=path%d[].\n",c); if ( (segs=run_spiro0(spiro,d,0,cl[c]))==0 ) { fprintf(stderr,"error with run_spiro0() using data=path%d[].\n",c); return -1; } #endif #else /* Check if run_spiro works okay (try backwards compatiblity) */ printf("---\ntesting run_spiro() using data=path%d[].\n",c); if ( (segs=run_spiro(spiro,cl[c]))==0 ) { fprintf(stderr,"error with run_spiro() using data=path%d[].\n",c); return -1; } #endif /* Load pointer to verification data to ensure it works right */ if ( c==0 ) rsp = verify_rs0; else if ( c==1 ) rsp = verify_rs1; else if ( c==2 ) rsp = verify_rs2; /* else if ( c==3 ) rsp = NULL; expecting failure to converge */ else if ( c==4 ) rsp = verify_rs4; else if ( c==5 ) rsp = verify_rs5; else if ( c==6 ) rsp = verify_rs5; /* same angles used for #6 */ else if ( c==7 ) rsp = verify_rs7; /* stop curve with ah code */ else if ( c==8 ) rsp = verify_rs8; else if ( c==9 ) rsp = verify_rs9; else if ( c==10 ) rsp = verify_rs10; /* start curve using ah. */ else if ( c==11 ) rsp = verify_rs11; else if ( c==12 ) rsp = verify_rs7; /* test #12 uses path7[]. */ else if ( c==13 ) rsp = verify_rs13; /* almost same as path11 */ else if ( c==14 ) rsp = verify_rs14; /* very large path9 copy */ else if ( c==15 ) rsp = verify_rs15; /* sub-atomic path9 copy */ else if ( c==16 ) rsp = verify_rs4; /* path4 arc curve output */ else if ( c==17 ) rsp = verify_rs4; /* path4 arc curve closed */ else if ( c==18 ) rsp = verify_rs2; /* trying many iterations */ else rsp = verify_rs0; /* long list, arc output. */ /* Quick visual check shows X,Y knots match with each pathN[] */ for (i=j=0; i < cl[c]-1; i++,j++) { if ( spiro[i].ty == 'h' ) { --j; printf("curve %d ctrl %d t=%c x=%f y=%f (handle)\n", \ c,j,segs[i].ty,spiro[i].x,spiro[i].y); } printf("curve %d line %d t=%c x=%f y=%f bend=%f ch=%f th=%f ",c,j, \ segs[i].ty,segs[i].x,segs[i].y,segs[i].bend_th,segs[i].seg_ch,segs[i].seg_th); /* Let computer verify that run_spiro() data is PASS/FAIL */ /* Tests including ah data more complicated to verify xy, */ /* therefore, skip testing xy for call_tests shown below. */ if ( (segs[i].ty != spiro[i].ty) || #if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) #if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) (fabs((segs[i].x * d[0] + d[1]) - spiro[i].x) > 1e5) || (fabs((segs[i].y * d[0] + d[2]) - spiro[i].y) > 1e5) || (fabs(segs[i].seg_ch * d[0] - rsp[i].ch) > 1e5) || #else (fabs((segs[i].x * d[0] + d[1]) - spiro[i].x) > 1e-47) || (fabs((segs[i].y * d[0] + d[2]) - spiro[i].y) > 1e-47) || (fabs(segs[i].seg_ch * d[0] - rsp[i].ch) > 1e-47) || #endif #else #if !defined(DO_CALL_TEST6) && !defined(DO_CALL_TEST7) && !defined(DO_CALL_TEST8) && !defined(DO_CALL_TEST10) && !defined(DO_CALL_TEST11) && !defined(DO_CALL_TEST12) && !defined(DO_CALL_TEST13) (fabs(segs[i].x - spiro[i].x) > 1e-5) || (fabs(segs[i].y - spiro[i].y) > 1e-5) || #endif (fabs(segs[i].seg_ch - rsp[i].ch) > 1e-5) || #endif (fabs(segs[i].bend_th - rsp[i].b) > 1e-5) || (fabs(segs[i].seg_th - rsp[i].th) > 1e-5) ) { printf("FAIL\n"); fprintf(stderr,"Error found with run_spiro() data. Results are not the same.\n"); fprintf(stderr,"expected line %d t=%c x=%f y=%f bend=%f ch=%f th=%f\n", j, \ spiro[i].ty,spiro[i].x,spiro[i].y,rsp[i].b,rsp[i].ch,rsp[i].th); free(segs); return -2; } else printf("PASS\n"); } printf("curve %d ",c); if ( spiro[i].ty == '}' || spiro[i].ty == 'z' ) printf("stop %d t=%c x=%f y=%f\n",j,segs[i].ty,segs[i].x,segs[i].y); else printf("line %d t=%c x=%f y=%f bend=%f ch=%f th=%f\n", j,segs[i].ty, \ segs[i].x,segs[i].y,segs[i].bend_th,segs[i].seg_ch,segs[i].seg_th); /* Quick visual check shows X,Y knots match with each pathN[] */ printf("---\ntesting spiro_to_bpath() using data from run_spiro(data=path%d[],len=%d).\n",c,cl[c]); bc = new_bezctx_test(); #if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) #if defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) spiro_to_bpath0(spiro,segs,d,SPIRO_ARC_MAYBE,cl[c],bc); #else spiro_to_bpath0(spiro,segs,d,0,cl[c],bc); #endif #else spiro_to_bpath(segs,cl[c],bc); #endif free(segs); #endif #if !defined(DO_CALL_TEST20) #if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) || defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) #if defined(DO_CALL_TEST14) || defined(DO_CALL_TEST15) || defined(DO_CALL_TEST16) || defined(DO_CALL_TEST17) /* Now verify we also have simple arc output too */ printf("---\ntesting SpiroCPsToBezier2() using data=path%d[].\n",c); if ( SpiroCPsToBezier2(spiro,cl[c],SPIRO_ARC_MAYBE,co[c],bc)!=1 ) { fprintf(stderr,"error with SpiroCPsToBezier2() using data=path%d[].\n",c); return -7; } #endif #if defined(DO_CALL_TEST18) || defined(DO_CALL_TEST19) printf("---\ntesting TaggedSpiroCPsToBezier2() using data=path%d[].\n",c); if ( TaggedSpiroCPsToBezier2(spiro,SPIRO_ARC_MAYBE,bc)!=1 ) { fprintf(stderr,"error with TaggedSpiroCPsToBezier2() using data=path%d[].\n",c); return -8; } #endif #else #if !defined(DO_CALL_TEST4) && !defined(DO_CALL_TEST6) && !defined(DO_CALL_TEST7) && !defined(DO_CALL_TEST8) && !defined(DO_CALL_TEST9) && !defined(DO_CALL_TEST10) && !defined(DO_CALL_TEST11) /* Check if TaggedSpiroCPsToBezier0() works okay */ printf("---\ntesting TaggedSpiroCPsToBezier0() using data=path%d[].\n",c); if ( TaggedSpiroCPsToBezier0(spiro,bc)!=1 ) { fprintf(stderr,"error with TaggedSpiroCPsToBezier0() using data=path%d[].\n",c); return -3; } #endif #if !defined(DO_CALL_TEST12) /* Check if SpiroCPsToBezier0() works okay */ printf("---\ntesting SpiroCPsToBezier0() using data=path%d[].\n",c); if ( SpiroCPsToBezier0(spiro,cl[c],co[c],bc)!=1 ) { fprintf(stderr,"error with SpiroCPsToBezier0() using data=path%d[].\n",c); return -4; } #endif #if !defined(DO_CALL_TEST4) && !defined(DO_CALL_TEST6) && !defined(DO_CALL_TEST7) && !defined(DO_CALL_TEST8) && !defined(DO_CALL_TEST9) && !defined(DO_CALL_TEST10) && !defined(DO_CALL_TEST11) /* Check if TaggedSpiroCPsToBezier1() works okay */ printf("---\ntesting TaggedSpiroCPsToBezier1() using data=path%d[].\n",c); TaggedSpiroCPsToBezier1(spiro,bc,&done); if ( done!=1 ) { fprintf(stderr,"error with TaggedSpiroCPsToBezier1() using data=path%d[].\n",c); return -5; } #endif #if !defined(DO_CALL_TEST12) /* Check if SpiroCPsToBezier1() works okay */ printf("---\ntesting SpiroCPsToBezier1() using data=path%d[].\n",c); SpiroCPsToBezier1(spiro,cl[c],co[c],bc,&done); if ( done!=1 ) { fprintf(stderr,"error with SpiroCPsToBezier1() using data=path%d[].\n",c); return -6; } #endif #endif #else /* We already visually checked output for spiroreverse above. */ /* Some reversed paths (above) will fail (like path20), so we */ /* reverse the reversed spiro path so we can use current test */ /* functions & values (so that this actually tests something) */ if (c == 20 || c == 21) { /* Check if SpiroCPsToBezier2() works okay */ printf("---\ntesting SpiroCPsToBezier2(reverse) using data=path%d[].\n",c); if ( SpiroCPsToBezier2(spiro,cl[c],SPIRO_REVERSE_SRC,co[c],bc)!=1 ) { fprintf(stderr,"error with SpiroCPsToBezier2(reverse) using data=path%d[].\n",c); return -9; } } else { /* c==22 || c==23 || c==24 */ /* Check if TaggedSpiroCPsToBezier2() works okay */ printf("---\ntesting TaggedSpiroCPsToBezier2(reverse) using data=path%d[].\n",c); if ( TaggedSpiroCPsToBezier2(spiro,SPIRO_REVERSE_SRC,bc)!=1 ) { fprintf(stderr,"error with TaggedSpiroCPsToBezier2(reverse) using data=path%d[].\n",c); return -10; } } #endif free(bc); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'CVE-2019-19847, Stack-based buffer overflow in the spiro_to_bpath0() Frederic Cambus (@fcambus) discovered a bug in call-test.c using: ./configure CFLAGS="-fsanitize=address" make ./tests/call-test[14,15,16,17,18,19] Fredrick Brennan (@ctrlcctrlv) provided bugfix. See issue #21'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void sqlite3Pragma( Parse *pParse, Token *pId1, /* First part of [schema.]id field */ Token *pId2, /* Second part of [schema.]id field, or NULL */ Token *pValue, /* Token for <value>, or NULL */ int minusFlag /* True if a '-' sign preceded <value> */ ){ char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */ char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */ const char *zDb = 0; /* The database name */ Token *pId; /* Pointer to <id> token */ char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */ int iDb; /* Database index for <database> */ int rc; /* return value form SQLITE_FCNTL_PRAGMA */ sqlite3 *db = pParse->db; /* The database connection */ Db *pDb; /* The specific database being pragmaed */ Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */ const PragmaName *pPragma; /* The pragma */ if( v==0 ) return; sqlite3VdbeRunOnlyOnce(v); pParse->nMem = 2; /* Interpret the [schema.] part of the pragma statement. iDb is the ** index of the database this pragma is being applied to in db.aDb[]. */ iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId); if( iDb<0 ) return; pDb = &db->aDb[iDb]; /* If the temp database has been explicitly named as part of the ** pragma, make sure it is open. */ if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){ return; } zLeft = sqlite3NameFromToken(db, pId); if( !zLeft ) return; if( minusFlag ){ zRight = sqlite3MPrintf(db, "-%T", pValue); }else{ zRight = sqlite3NameFromToken(db, pValue); } assert( pId2 ); zDb = pId2->n>0 ? pDb->zDbSName : 0; if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){ goto pragma_out; } /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS ** connection. If it returns SQLITE_OK, then assume that the VFS ** handled the pragma and generate a no-op prepared statement. ** ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed, ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file ** object corresponding to the database file to which the pragma ** statement refers. ** ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA ** file control is an array of pointers to strings (char**) in which the ** second element of the array is the name of the pragma and the third ** element is the argument to the pragma or NULL if the pragma has no ** argument. */ aFcntl[0] = 0; aFcntl[1] = zLeft; aFcntl[2] = zRight; aFcntl[3] = 0; db->busyHandler.nBusy = 0; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl); if( rc==SQLITE_OK ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, aFcntl[0], SQLITE_TRANSIENT); returnSingleText(v, aFcntl[0]); sqlite3_free(aFcntl[0]); goto pragma_out; } if( rc!=SQLITE_NOTFOUND ){ if( aFcntl[0] ){ sqlite3ErrorMsg(pParse, "%s", aFcntl[0]); sqlite3_free(aFcntl[0]); } pParse->nErr++; pParse->rc = rc; goto pragma_out; } /* Locate the pragma in the lookup table */ pPragma = pragmaLocate(zLeft); if( pPragma==0 ) goto pragma_out; /* Make sure the database schema is loaded if the pragma requires that */ if( (pPragma->mPragFlg & PragFlg_NeedSchema)!=0 ){ if( sqlite3ReadSchema(pParse) ) goto pragma_out; } /* Register the result column names for pragmas that return results */ if( (pPragma->mPragFlg & PragFlg_NoColumns)==0 && ((pPragma->mPragFlg & PragFlg_NoColumns1)==0 || zRight==0) ){ setPragmaResultColumnNames(v, pPragma); } /* Jump to the appropriate pragma handler */ switch( pPragma->ePragTyp ){ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED) /* ** PRAGMA [schema.]default_cache_size ** PRAGMA [schema.]default_cache_size=N ** ** The first form reports the current persistent setting for the ** page cache size. The value returned is the maximum number of ** pages in the page cache. The second form sets both the current ** page cache size value and the persistent page cache size value ** stored in the database file. ** ** Older versions of SQLite would set the default cache size to a ** negative number to indicate synchronous=OFF. These days, synchronous ** is always on by default regardless of the sign of the default cache ** size. But continue to take the absolute value of the default cache ** size of historical compatibility. */ case PragTyp_DEFAULT_CACHE_SIZE: { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList getCacheSize[] = { { OP_Transaction, 0, 0, 0}, /* 0 */ { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */ { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 2, 0}, { OP_Subtract, 1, 2, 1}, { OP_IfPos, 1, 8, 0}, { OP_Integer, 0, 1, 0}, /* 6 */ { OP_Noop, 0, 0, 0}, { OP_ResultRow, 1, 1, 0}, }; VdbeOp *aOp; sqlite3VdbeUsesBtree(v, iDb); if( !zRight ){ pParse->nMem += 2; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize)); aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE; }else{ int size = sqlite3AbsInt32(sqlite3Atoi(zRight)); sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, size); assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */ #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) /* ** PRAGMA [schema.]page_size ** PRAGMA [schema.]page_size=N ** ** The first form reports the current setting for the ** database page size in bytes. The second form sets the ** database page size value. The value can only be set if ** the database has not yet been created. */ case PragTyp_PAGE_SIZE: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0; returnSingleInt(v, size); }else{ /* Malloc may fail when setting the page-size, as there is an internal ** buffer that the pager module resizes using sqlite3_realloc(). */ db->nextPagesize = sqlite3Atoi(zRight); if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){ sqlite3OomFault(db); } } break; } /* ** PRAGMA [schema.]secure_delete ** PRAGMA [schema.]secure_delete=ON/OFF/FAST ** ** The first form reports the current setting for the ** secure_delete flag. The second form changes the secure_delete ** flag setting and reports the new value. */ case PragTyp_SECURE_DELETE: { Btree *pBt = pDb->pBt; int b = -1; assert( pBt!=0 ); if( zRight ){ if( sqlite3_stricmp(zRight, "fast")==0 ){ b = 2; }else{ b = sqlite3GetBoolean(zRight, 0); } } if( pId2->n==0 && b>=0 ){ int ii; for(ii=0; ii<db->nDb; ii++){ sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b); } } b = sqlite3BtreeSecureDelete(pBt, b); returnSingleInt(v, b); break; } /* ** PRAGMA [schema.]max_page_count ** PRAGMA [schema.]max_page_count=N ** ** The first form reports the current setting for the ** maximum number of pages in the database file. The ** second form attempts to change this setting. Both ** forms return the current setting. ** ** The absolute value of N is used. This is undocumented and might ** change. The only purpose is to provide an easy way to test ** the sqlite3AbsInt32() function. ** ** PRAGMA [schema.]page_count ** ** Return the number of pages in the specified database. */ case PragTyp_PAGE_COUNT: { int iReg; sqlite3CodeVerifySchema(pParse, iDb); iReg = ++pParse->nMem; if( sqlite3Tolower(zLeft[0])=='p' ){ sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg); }else{ sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, sqlite3AbsInt32(sqlite3Atoi(zRight))); } sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1); break; } /* ** PRAGMA [schema.]locking_mode ** PRAGMA [schema.]locking_mode = (normal|exclusive) */ case PragTyp_LOCKING_MODE: { const char *zRet = "normal"; int eMode = getLockingMode(zRight); if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){ /* Simple "PRAGMA locking_mode;" statement. This is a query for ** the current default locking mode (which may be different to ** the locking-mode of the main database). */ eMode = db->dfltLockMode; }else{ Pager *pPager; if( pId2->n==0 ){ /* This indicates that no database name was specified as part ** of the PRAGMA command. In this case the locking-mode must be ** set on all attached databases, as well as the main db file. ** ** Also, the sqlite3.dfltLockMode variable is set so that ** any subsequently attached databases also use the specified ** locking mode. */ int ii; assert(pDb==&db->aDb[0]); for(ii=2; ii<db->nDb; ii++){ pPager = sqlite3BtreePager(db->aDb[ii].pBt); sqlite3PagerLockingMode(pPager, eMode); } db->dfltLockMode = (u8)eMode; } pPager = sqlite3BtreePager(pDb->pBt); eMode = sqlite3PagerLockingMode(pPager, eMode); } assert( eMode==PAGER_LOCKINGMODE_NORMAL || eMode==PAGER_LOCKINGMODE_EXCLUSIVE ); if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){ zRet = "exclusive"; } returnSingleText(v, zRet); break; } /* ** PRAGMA [schema.]journal_mode ** PRAGMA [schema.]journal_mode = ** (delete|persist|off|truncate|memory|wal|off) */ case PragTyp_JOURNAL_MODE: { int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */ int ii; /* Loop counter */ if( zRight==0 ){ /* If there is no "=MODE" part of the pragma, do a query for the ** current mode */ eMode = PAGER_JOURNALMODE_QUERY; }else{ const char *zMode; int n = sqlite3Strlen30(zRight); for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){ if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break; } if( !zMode ){ /* If the "=MODE" part does not match any known journal mode, ** then do a query */ eMode = PAGER_JOURNALMODE_QUERY; } if( eMode==PAGER_JOURNALMODE_OFF && (db->flags & SQLITE_Defensive)!=0 ){ /* Do not allow journal-mode "OFF" in defensive since the database ** can become corrupted using ordinary SQL when the journal is off */ eMode = PAGER_JOURNALMODE_QUERY; } } if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){ /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */ iDb = 0; pId2->n = 1; } for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3VdbeUsesBtree(v, ii); sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode); } } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); break; } /* ** PRAGMA [schema.]journal_size_limit ** PRAGMA [schema.]journal_size_limit=N ** ** Get or set the size limit on rollback journal files. */ case PragTyp_JOURNAL_SIZE_LIMIT: { Pager *pPager = sqlite3BtreePager(pDb->pBt); i64 iLimit = -2; if( zRight ){ sqlite3DecOrHexToI64(zRight, &iLimit); if( iLimit<-1 ) iLimit = -1; } iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit); returnSingleInt(v, iLimit); break; } #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ /* ** PRAGMA [schema.]auto_vacuum ** PRAGMA [schema.]auto_vacuum=N ** ** Get or set the value of the database 'auto-vacuum' parameter. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL */ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_AUTO_VACUUM: { Btree *pBt = pDb->pBt; assert( pBt!=0 ); if( !zRight ){ returnSingleInt(v, sqlite3BtreeGetAutoVacuum(pBt)); }else{ int eAuto = getAutoVacuum(zRight); assert( eAuto>=0 && eAuto<=2 ); db->nextAutovac = (u8)eAuto; /* Call SetAutoVacuum() to set initialize the internal auto and ** incr-vacuum flags. This is required in case this connection ** creates the database file. It is important that it is created ** as an auto-vacuum capable db. */ rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto); if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){ /* When setting the auto_vacuum mode to either "full" or ** "incremental", write the value of meta[6] in the database ** file. Before writing to meta[6], check that meta[3] indicates ** that this really is an auto-vacuum capable database. */ static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList setMeta6[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE}, { OP_If, 1, 0, 0}, /* 2 */ { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */ { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */ }; VdbeOp *aOp; int iAddr = sqlite3VdbeCurrentAddr(v); sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setMeta6)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[2].p2 = iAddr+4; aOp[4].p1 = iDb; aOp[4].p3 = eAuto - 1; sqlite3VdbeUsesBtree(v, iDb); } } break; } #endif /* ** PRAGMA [schema.]incremental_vacuum(N) ** ** Do N steps of incremental vacuuming on a database. */ #ifndef SQLITE_OMIT_AUTOVACUUM case PragTyp_INCREMENTAL_VACUUM: { int iLimit, addr; if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){ iLimit = 0x7fffffff; } sqlite3BeginWriteOperation(pParse, 0, iDb); sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1); addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v); sqlite3VdbeAddOp1(v, OP_ResultRow, 1); sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addr); break; } #endif #ifndef SQLITE_OMIT_PAGER_PRAGMAS /* ** PRAGMA [schema.]cache_size ** PRAGMA [schema.]cache_size=N ** ** The first form reports the current local setting for the ** page cache size. The second form sets the local ** page cache size value. If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. */ case PragTyp_CACHE_SIZE: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, pDb->pSchema->cache_size); }else{ int size = sqlite3Atoi(zRight); pDb->pSchema->cache_size = size; sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size); } break; } /* ** PRAGMA [schema.]cache_spill ** PRAGMA cache_spill=BOOLEAN ** PRAGMA [schema.]cache_spill=N ** ** The first form reports the current local setting for the ** page cache spill size. The second form turns cache spill on ** or off. When turnning cache spill on, the size is set to the ** current cache_size. The third form sets a spill size that ** may be different form the cache size. ** If N is positive then that is the ** number of pages in the cache. If N is negative, then the ** number of pages is adjusted so that the cache uses -N kibibytes ** of memory. ** ** If the number of cache_spill pages is less then the number of ** cache_size pages, no spilling occurs until the page count exceeds ** the number of cache_size pages. ** ** The cache_spill=BOOLEAN setting applies to all attached schemas, ** not just the schema specified. */ case PragTyp_CACHE_SPILL: { assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( !zRight ){ returnSingleInt(v, (db->flags & SQLITE_CacheSpill)==0 ? 0 : sqlite3BtreeSetSpillSize(pDb->pBt,0)); }else{ int size = 1; if( sqlite3GetInt32(zRight, &size) ){ sqlite3BtreeSetSpillSize(pDb->pBt, size); } if( sqlite3GetBoolean(zRight, size!=0) ){ db->flags |= SQLITE_CacheSpill; }else{ db->flags &= ~(u64)SQLITE_CacheSpill; } setAllPagerFlags(db); } break; } /* ** PRAGMA [schema.]mmap_size(N) ** ** Used to set mapping size limit. The mapping size limit is ** used to limit the aggregate size of all memory mapped regions of the ** database file. If this parameter is set to zero, then memory mapping ** is not used at all. If N is negative, then the default memory map ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set. ** The parameter N is measured in bytes. ** ** This value is advisory. The underlying VFS is free to memory map ** as little or as much as it wants. Except, if N is set to 0 then the ** upper layers will never invoke the xFetch interfaces to the VFS. */ case PragTyp_MMAP_SIZE: { sqlite3_int64 sz; #if SQLITE_MAX_MMAP_SIZE>0 assert( sqlite3SchemaMutexHeld(db, iDb, 0) ); if( zRight ){ int ii; sqlite3DecOrHexToI64(zRight, &sz); if( sz<0 ) sz = sqlite3GlobalConfig.szMmap; if( pId2->n==0 ) db->szMmap = sz; for(ii=db->nDb-1; ii>=0; ii--){ if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){ sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz); } } } sz = -1; rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz); #else sz = 0; rc = SQLITE_OK; #endif if( rc==SQLITE_OK ){ returnSingleInt(v, sz); }else if( rc!=SQLITE_NOTFOUND ){ pParse->nErr++; pParse->rc = rc; } break; } /* ** PRAGMA temp_store ** PRAGMA temp_store = "default"|"memory"|"file" ** ** Return or set the local value of the temp_store flag. Changing ** the local value does not make changes to the disk file and the default ** value will be restored the next time the database is opened. ** ** Note that it is possible for the library compile-time options to ** override this setting */ case PragTyp_TEMP_STORE: { if( !zRight ){ returnSingleInt(v, db->temp_store); }else{ changeTempStorage(pParse, zRight); } break; } /* ** PRAGMA temp_store_directory ** PRAGMA temp_store_directory = ""|"directory_name" ** ** Return or set the local value of the temp_store_directory flag. Changing ** the value sets a specific directory to be used for temporary files. ** Setting to a null string reverts to the default temporary directory search. ** If temporary directory is changed, then invalidateTempStorage. ** */ case PragTyp_TEMP_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_temp_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } if( SQLITE_TEMP_STORE==0 || (SQLITE_TEMP_STORE==1 && db->temp_store<=1) || (SQLITE_TEMP_STORE==2 && db->temp_store==1) ){ invalidateTempStorage(pParse); } sqlite3_free(sqlite3_temp_directory); if( zRight[0] ){ sqlite3_temp_directory = sqlite3_mprintf("%s", zRight); }else{ sqlite3_temp_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } break; } #if SQLITE_OS_WIN /* ** PRAGMA data_store_directory ** PRAGMA data_store_directory = ""|"directory_name" ** ** Return or set the local value of the data_store_directory flag. Changing ** the value sets a specific directory to be used for database files that ** were specified with a relative pathname. Setting to a null string reverts ** to the default database directory, which for database files specified with ** a relative path will probably be based on the current directory for the ** process. Database file specified with an absolute path are not impacted ** by this setting, regardless of its value. ** */ case PragTyp_DATA_STORE_DIRECTORY: { if( !zRight ){ returnSingleText(v, sqlite3_data_directory); }else{ #ifndef SQLITE_OMIT_WSD if( zRight[0] ){ int res; rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res); if( rc!=SQLITE_OK || res==0 ){ sqlite3ErrorMsg(pParse, "not a writable directory"); goto pragma_out; } } sqlite3_free(sqlite3_data_directory); if( zRight[0] ){ sqlite3_data_directory = sqlite3_mprintf("%s", zRight); }else{ sqlite3_data_directory = 0; } #endif /* SQLITE_OMIT_WSD */ } break; } #endif #if SQLITE_ENABLE_LOCKING_STYLE /* ** PRAGMA [schema.]lock_proxy_file ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path" ** ** Return or set the value of the lock_proxy_file flag. Changing ** the value sets a specific file to be used for database access locks. ** */ case PragTyp_LOCK_PROXY_FILE: { if( !zRight ){ Pager *pPager = sqlite3BtreePager(pDb->pBt); char *proxy_file_path = NULL; sqlite3_file *pFile = sqlite3PagerFile(pPager); sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, &proxy_file_path); returnSingleText(v, proxy_file_path); }else{ Pager *pPager = sqlite3BtreePager(pDb->pBt); sqlite3_file *pFile = sqlite3PagerFile(pPager); int res; if( zRight[0] ){ res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, zRight); } else { res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, NULL); } if( res!=SQLITE_OK ){ sqlite3ErrorMsg(pParse, "failed to set lock proxy file"); goto pragma_out; } } break; } #endif /* SQLITE_ENABLE_LOCKING_STYLE */ /* ** PRAGMA [schema.]synchronous ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA ** ** Return or set the local value of the synchronous flag. Changing ** the local value does not make changes to the disk file and the ** default value will be restored the next time the database is ** opened. */ case PragTyp_SYNCHRONOUS: { if( !zRight ){ returnSingleInt(v, pDb->safety_level-1); }else{ if( !db->autoCommit ){ sqlite3ErrorMsg(pParse, "Safety level may not be changed inside a transaction"); }else if( iDb!=1 ){ int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK; if( iLevel==0 ) iLevel = 1; pDb->safety_level = iLevel; pDb->bSyncSet = 1; setAllPagerFlags(db); } } break; } #endif /* SQLITE_OMIT_PAGER_PRAGMAS */ #ifndef SQLITE_OMIT_FLAG_PRAGMAS case PragTyp_FLAG: { if( zRight==0 ){ setPragmaResultColumnNames(v, pPragma); returnSingleInt(v, (db->flags & pPragma->iArg)!=0 ); }else{ u64 mask = pPragma->iArg; /* Mask of bits to set or clear. */ if( db->autoCommit==0 ){ /* Foreign key support may not be enabled or disabled while not ** in auto-commit mode. */ mask &= ~(SQLITE_ForeignKeys); } #if SQLITE_USER_AUTHENTICATION if( db->auth.authLevel==UAUTH_User ){ /* Do not allow non-admin users to modify the schema arbitrarily */ mask &= ~(SQLITE_WriteSchema); } #endif if( sqlite3GetBoolean(zRight, 0) ){ db->flags |= mask; }else{ db->flags &= ~mask; if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0; } /* Many of the flag-pragmas modify the code generated by the SQL ** compiler (eg. count_changes). So add an opcode to expire all ** compiled SQL statements after modifying a pragma value. */ sqlite3VdbeAddOp0(v, OP_Expire); setAllPagerFlags(db); } break; } #endif /* SQLITE_OMIT_FLAG_PRAGMAS */ #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS /* ** PRAGMA table_info(<table>) ** ** Return a single row for each column of the named table. The columns of ** the returned data set are: ** ** cid: Column id (numbered from left to right, starting at 0) ** name: Column name ** type: Column declaration type. ** notnull: True if 'NOT NULL' is part of column declaration ** dflt_value: The default value for the column, if any. ** pk: Non-zero for PK fields. */ case PragTyp_TABLE_INFO: if( zRight ){ Table *pTab; pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int i, k; int nHidden = 0; Column *pCol; Index *pPk = sqlite3PrimaryKeyIndex(pTab); pParse->nMem = 7; sqlite3CodeVerifySchema(pParse, iTabDb); sqlite3ViewGetColumnNames(pParse, pTab); for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){ int isHidden = 0; if( pCol->colFlags & COLFLAG_NOINSERT ){ if( pPragma->iArg==0 ){ nHidden++; continue; } if( pCol->colFlags & COLFLAG_VIRTUAL ){ isHidden = 2; /* GENERATED ALWAYS AS ... VIRTUAL */ }else if( pCol->colFlags & COLFLAG_STORED ){ isHidden = 3; /* GENERATED ALWAYS AS ... STORED */ }else{ assert( pCol->colFlags & COLFLAG_HIDDEN ); isHidden = 1; /* HIDDEN */ } } if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){ k = 0; }else if( pPk==0 ){ k = 1; }else{ for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){} } assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN || isHidden>=2 ); sqlite3VdbeMultiLoad(v, 1, pPragma->iArg ? "issisii" : "issisi", i-nHidden, pCol->zName, sqlite3ColumnType(pCol,""), pCol->notNull ? 1 : 0, pCol->pDflt && isHidden<2 ? pCol->pDflt->u.zToken : 0, k, isHidden); } } } break; #ifdef SQLITE_DEBUG case PragTyp_STATS: { Index *pIdx; HashElem *i; pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iDb); for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){ Table *pTab = sqliteHashData(i); sqlite3VdbeMultiLoad(v, 1, "ssiii", pTab->zName, 0, pTab->szTabRow, pTab->nRowLogEst, pTab->tabFlags); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ sqlite3VdbeMultiLoad(v, 2, "siiiX", pIdx->zName, pIdx->szIdxRow, pIdx->aiRowLogEst[0], pIdx->hasStat1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5); } } } break; #endif case PragTyp_INDEX_INFO: if( zRight ){ Index *pIdx; Table *pTab; pIdx = sqlite3FindIndex(db, zRight, zDb); if( pIdx==0 ){ /* If there is no index named zRight, check to see if there is a ** WITHOUT ROWID table named zRight, and if there is, show the ** structure of the PRIMARY KEY index for that table. */ pTab = sqlite3LocateTable(pParse, LOCATE_NOERR, zRight, zDb); if( pTab && !HasRowid(pTab) ){ pIdx = sqlite3PrimaryKeyIndex(pTab); } } if( pIdx ){ int iIdxDb = sqlite3SchemaToIndex(db, pIdx->pSchema); int i; int mx; if( pPragma->iArg ){ /* PRAGMA index_xinfo (newer version with more rows and columns) */ mx = pIdx->nColumn; pParse->nMem = 6; }else{ /* PRAGMA index_info (legacy version) */ mx = pIdx->nKeyCol; pParse->nMem = 3; } pTab = pIdx->pTable; sqlite3CodeVerifySchema(pParse, iIdxDb); assert( pParse->nMem<=pPragma->nPragCName ); for(i=0; i<mx; i++){ i16 cnum = pIdx->aiColumn[i]; sqlite3VdbeMultiLoad(v, 1, "iisX", i, cnum, cnum<0 ? 0 : pTab->aCol[cnum].zName); if( pPragma->iArg ){ sqlite3VdbeMultiLoad(v, 4, "isiX", pIdx->aSortOrder[i], pIdx->azColl[i], i<pIdx->nKeyCol); } sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem); } } } break; case PragTyp_INDEX_LIST: if( zRight ){ Index *pIdx; Table *pTab; int i; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); pParse->nMem = 5; sqlite3CodeVerifySchema(pParse, iTabDb); for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){ const char *azOrigin[] = { "c", "u", "pk" }; sqlite3VdbeMultiLoad(v, 1, "isisi", i, pIdx->zName, IsUniqueIndex(pIdx), azOrigin[pIdx->idxType], pIdx->pPartIdxWhere!=0); } } } break; case PragTyp_DATABASE_LIST: { int i; pParse->nMem = 3; for(i=0; i<db->nDb; i++){ if( db->aDb[i].pBt==0 ) continue; assert( db->aDb[i].zDbSName!=0 ); sqlite3VdbeMultiLoad(v, 1, "iss", i, db->aDb[i].zDbSName, sqlite3BtreeGetFilename(db->aDb[i].pBt)); } } break; case PragTyp_COLLATION_LIST: { int i = 0; HashElem *p; pParse->nMem = 2; for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){ CollSeq *pColl = (CollSeq *)sqliteHashData(p); sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName); } } break; #ifndef SQLITE_OMIT_INTROSPECTION_PRAGMAS case PragTyp_FUNCTION_LIST: { int i; HashElem *j; FuncDef *p; pParse->nMem = 2; for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){ for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash ){ if( p->funcFlags & SQLITE_FUNC_INTERNAL ) continue; sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 1); } } for(j=sqliteHashFirst(&db->aFunc); j; j=sqliteHashNext(j)){ p = (FuncDef*)sqliteHashData(j); sqlite3VdbeMultiLoad(v, 1, "si", p->zName, 0); } } break; #ifndef SQLITE_OMIT_VIRTUALTABLE case PragTyp_MODULE_LIST: { HashElem *j; pParse->nMem = 1; for(j=sqliteHashFirst(&db->aModule); j; j=sqliteHashNext(j)){ Module *pMod = (Module*)sqliteHashData(j); sqlite3VdbeMultiLoad(v, 1, "s", pMod->zName); } } break; #endif /* SQLITE_OMIT_VIRTUALTABLE */ case PragTyp_PRAGMA_LIST: { int i; for(i=0; i<ArraySize(aPragmaName); i++){ sqlite3VdbeMultiLoad(v, 1, "s", aPragmaName[i].zName); } } break; #endif /* SQLITE_INTROSPECTION_PRAGMAS */ #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */ #ifndef SQLITE_OMIT_FOREIGN_KEY case PragTyp_FOREIGN_KEY_LIST: if( zRight ){ FKey *pFK; Table *pTab; pTab = sqlite3FindTable(db, zRight, zDb); if( pTab ){ pFK = pTab->pFKey; if( pFK ){ int iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); int i = 0; pParse->nMem = 8; sqlite3CodeVerifySchema(pParse, iTabDb); while(pFK){ int j; for(j=0; j<pFK->nCol; j++){ sqlite3VdbeMultiLoad(v, 1, "iissssss", i, j, pFK->zTo, pTab->aCol[pFK->aCol[j].iFrom].zName, pFK->aCol[j].zCol, actionName(pFK->aAction[1]), /* ON UPDATE */ actionName(pFK->aAction[0]), /* ON DELETE */ "NONE"); } ++i; pFK = pFK->pNextFrom; } } } } break; #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ #ifndef SQLITE_OMIT_FOREIGN_KEY #ifndef SQLITE_OMIT_TRIGGER case PragTyp_FOREIGN_KEY_CHECK: { FKey *pFK; /* A foreign key constraint */ Table *pTab; /* Child table contain "REFERENCES" keyword */ Table *pParent; /* Parent table that child points to */ Index *pIdx; /* Index in the parent table */ int i; /* Loop counter: Foreign key number for pTab */ int j; /* Loop counter: Field of the foreign key */ HashElem *k; /* Loop counter: Next table in schema */ int x; /* result variable */ int regResult; /* 3 registers to hold a result row */ int regKey; /* Register to hold key for checking the FK */ int regRow; /* Registers to hold a row from pTab */ int addrTop; /* Top of a loop checking foreign keys */ int addrOk; /* Jump here if the key is OK */ int *aiCols; /* child to parent column mapping */ regResult = pParse->nMem+1; pParse->nMem += 4; regKey = ++pParse->nMem; regRow = ++pParse->nMem; k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash); while( k ){ int iTabDb; if( zRight ){ pTab = sqlite3LocateTable(pParse, 0, zRight, zDb); k = 0; }else{ pTab = (Table*)sqliteHashData(k); k = sqliteHashNext(k); } if( pTab==0 || pTab->pFKey==0 ) continue; iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema); sqlite3CodeVerifySchema(pParse, iTabDb); sqlite3TableLock(pParse, iTabDb, pTab->tnum, 0, pTab->zName); if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow; sqlite3OpenTable(pParse, 0, iTabDb, pTab, OP_OpenRead); sqlite3VdbeLoadString(v, regResult, pTab->zName); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); if( pParent==0 ) continue; pIdx = 0; sqlite3TableLock(pParse, iTabDb, pParent->tnum, 0, pParent->zName); x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0); if( x==0 ){ if( pIdx==0 ){ sqlite3OpenTable(pParse, i, iTabDb, pParent, OP_OpenRead); }else{ sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iTabDb); sqlite3VdbeSetP4KeyInfo(pParse, pIdx); } }else{ k = 0; break; } } assert( pParse->nErr>0 || pFK==0 ); if( pFK ) break; if( pParse->nTab<i ) pParse->nTab = i; addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v); for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){ pParent = sqlite3FindTable(db, pFK->zTo, zDb); pIdx = 0; aiCols = 0; if( pParent ){ x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols); assert( x==0 ); } addrOk = sqlite3VdbeMakeLabel(pParse); /* Generate code to read the child key values into registers ** regRow..regRow+n. If any of the child key values are NULL, this ** row cannot cause an FK violation. Jump directly to addrOk in ** this case. */ for(j=0; j<pFK->nCol; j++){ int iCol = aiCols ? aiCols[j] : pFK->aCol[j].iFrom; sqlite3ExprCodeGetColumnOfTable(v, pTab, 0, iCol, regRow+j); sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v); } /* Generate code to query the parent index for a matching parent ** key. If a match is found, jump to addrOk. */ if( pIdx ){ sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey, sqlite3IndexAffinityStr(db,pIdx), pFK->nCol); sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0); VdbeCoverage(v); }else if( pParent ){ int jmp = sqlite3VdbeCurrentAddr(v)+2; sqlite3VdbeAddOp3(v, OP_SeekRowid, i, jmp, regRow); VdbeCoverage(v); sqlite3VdbeGoto(v, addrOk); assert( pFK->nCol==1 ); } /* Generate code to report an FK violation to the caller. */ if( HasRowid(pTab) ){ sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1); }else{ sqlite3VdbeAddOp2(v, OP_Null, 0, regResult+1); } sqlite3VdbeMultiLoad(v, regResult+2, "siX", pFK->zTo, i-1); sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4); sqlite3VdbeResolveLabel(v, addrOk); sqlite3DbFree(db, aiCols); } sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v); sqlite3VdbeJumpHere(v, addrTop); } } break; #endif /* !defined(SQLITE_OMIT_TRIGGER) */ #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */ #ifndef SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA /* Reinstall the LIKE and GLOB functions. The variant of LIKE ** used will be case sensitive or not depending on the RHS. */ case PragTyp_CASE_SENSITIVE_LIKE: { if( zRight ){ sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0)); } } break; #endif /* SQLITE_OMIT_CASE_SENSITIVE_LIKE_PRAGMA */ #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100 #endif #ifndef SQLITE_OMIT_INTEGRITY_CHECK /* PRAGMA integrity_check ** PRAGMA integrity_check(N) ** PRAGMA quick_check ** PRAGMA quick_check(N) ** ** Verify the integrity of the database. ** ** The "quick_check" is reduced version of ** integrity_check designed to detect most database corruption ** without the overhead of cross-checking indexes. Quick_check ** is linear time wherease integrity_check is O(NlogN). */ case PragTyp_INTEGRITY_CHECK: { int i, j, addr, mxErr; int isQuick = (sqlite3Tolower(zLeft[0])=='q'); /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check", ** then iDb is set to the index of the database identified by <db>. ** In this case, the integrity of database iDb only is verified by ** the VDBE created below. ** ** Otherwise, if the command was simply "PRAGMA integrity_check" (or ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb ** to -1 here, to indicate that the VDBE should verify the integrity ** of all attached databases. */ assert( iDb>=0 ); assert( iDb==0 || pId2->z ); if( pId2->z==0 ) iDb = -1; /* Initialize the VDBE program */ pParse->nMem = 6; /* Set the maximum error count */ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; if( zRight ){ sqlite3GetInt32(zRight, &mxErr); if( mxErr<=0 ){ mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX; } } sqlite3VdbeAddOp2(v, OP_Integer, mxErr-1, 1); /* reg[1] holds errors left */ /* Do an integrity check on each database file */ for(i=0; i<db->nDb; i++){ HashElem *x; /* For looping over tables in the schema */ Hash *pTbls; /* Set of all tables in the schema */ int *aRoot; /* Array of root page numbers of all btrees */ int cnt = 0; /* Number of entries in aRoot[] */ int mxIdx = 0; /* Maximum number of indexes for any table */ if( OMIT_TEMPDB && i==1 ) continue; if( iDb>=0 && i!=iDb ) continue; sqlite3CodeVerifySchema(pParse, i); /* Do an integrity check of the B-Tree ** ** Begin by finding the root pages numbers ** for all tables and indices in the database. */ assert( sqlite3SchemaMutexHeld(db, i, 0) ); pTbls = &db->aDb[i].pSchema->tblHash; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); /* Current table */ Index *pIdx; /* An index on pTab */ int nIdx; /* Number of indexes on pTab */ if( HasRowid(pTab) ) cnt++; for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; } if( nIdx>mxIdx ) mxIdx = nIdx; } aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1)); if( aRoot==0 ) break; for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx; if( HasRowid(pTab) ) aRoot[++cnt] = pTab->tnum; for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ aRoot[++cnt] = pIdx->tnum; } } aRoot[0] = cnt; /* Make sure sufficient number of registers have been allocated */ pParse->nMem = MAX( pParse->nMem, 8+mxIdx ); sqlite3ClearTempRegCache(pParse); /* Do the b-tree integrity checks */ sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY); sqlite3VdbeChangeP5(v, (u8)i); addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zDbSName), P4_DYNAMIC); sqlite3VdbeAddOp3(v, OP_Concat, 2, 3, 3); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, addr); /* Make sure all the indices are constructed correctly. */ for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){ Table *pTab = sqliteHashData(x); Index *pIdx, *pPk; Index *pPrior = 0; int loopTop; int iDataCur, iIdxCur; int r1 = -1; if( pTab->tnum<1 ) continue; /* Skip VIEWs or VIRTUAL TABLEs */ pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab); sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0, 1, 0, &iDataCur, &iIdxCur); /* reg[7] counts the number of entries in the table. ** reg[8+i] counts the number of entries in the i-th index */ sqlite3VdbeAddOp2(v, OP_Integer, 0, 7); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */ } assert( pParse->nMem>=8+j ); assert( sqlite3NoTempsInRange(pParse,1,7+j) ); sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v); loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1); if( !isQuick ){ /* Sanity check on record header decoding */ sqlite3VdbeAddOp3(v, OP_Column, iDataCur, pTab->nNVCol-1,3); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); } /* Verify that all NOT NULL columns really are NOT NULL */ for(j=0; j<pTab->nCol; j++){ char *zErr; int jmp2; if( j==pTab->iPKey ) continue; if( pTab->aCol[j].notNull==0 ) continue; sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3); sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG); jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v); zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName, pTab->aCol[j].zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, jmp2); } /* Verify CHECK constraints */ if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){ ExprList *pCheck = sqlite3ExprListDup(db, pTab->pCheck, 0); if( db->mallocFailed==0 ){ int addrCkFault = sqlite3VdbeMakeLabel(pParse); int addrCkOk = sqlite3VdbeMakeLabel(pParse); char *zErr; int k; pParse->iSelfTab = iDataCur + 1; for(k=pCheck->nExpr-1; k>0; k--){ sqlite3ExprIfFalse(pParse, pCheck->a[k].pExpr, addrCkFault, 0); } sqlite3ExprIfTrue(pParse, pCheck->a[0].pExpr, addrCkOk, SQLITE_JUMPIFNULL); sqlite3VdbeResolveLabel(v, addrCkFault); pParse->iSelfTab = 0; zErr = sqlite3MPrintf(db, "CHECK constraint failed in %s", pTab->zName); sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC); integrityCheckResultRow(v); sqlite3VdbeResolveLabel(v, addrCkOk); } sqlite3ExprListDelete(db, pCheck); } if( !isQuick ){ /* Omit the remaining tests for quick_check */ /* Validate index entries for the current row */ for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ int jmp2, jmp3, jmp4, jmp5; int ckUniq = sqlite3VdbeMakeLabel(pParse); if( pPk==pIdx ) continue; r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3, pPrior, r1); pPrior = pIdx; sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);/* increment entry count */ /* Verify that an index entry exists for the current table row */ jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1, pIdx->nColumn); VdbeCoverage(v); sqlite3VdbeLoadString(v, 3, "row "); sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3); sqlite3VdbeLoadString(v, 4, " missing from index "); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3); jmp4 = integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, jmp2); /* For UNIQUE indexes, verify that only one entry exists with the ** current key. The entry is unique if (1) any column is NULL ** or (2) the next entry has a different key */ if( IsUniqueIndex(pIdx) ){ int uniqOk = sqlite3VdbeMakeLabel(pParse); int jmp6; int kk; for(kk=0; kk<pIdx->nKeyCol; kk++){ int iCol = pIdx->aiColumn[kk]; assert( iCol!=XN_ROWID && iCol<pTab->nCol ); if( iCol>=0 && pTab->aCol[iCol].notNull ) continue; sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk); VdbeCoverage(v); } jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v); sqlite3VdbeGoto(v, uniqOk); sqlite3VdbeJumpHere(v, jmp6); sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1, pIdx->nKeyCol); VdbeCoverage(v); sqlite3VdbeLoadString(v, 3, "non-unique entry in index "); sqlite3VdbeGoto(v, jmp5); sqlite3VdbeResolveLabel(v, uniqOk); } sqlite3VdbeJumpHere(v, jmp4); sqlite3ResolvePartIdxLabel(pParse, jmp3); } } sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v); sqlite3VdbeJumpHere(v, loopTop-1); #ifndef SQLITE_OMIT_BTREECOUNT if( !isQuick ){ sqlite3VdbeLoadString(v, 2, "wrong # of entries in index "); for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){ if( pPk==pIdx ) continue; sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3); addr = sqlite3VdbeAddOp3(v, OP_Eq, 8+j, 0, 3); VdbeCoverage(v); sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); sqlite3VdbeLoadString(v, 4, pIdx->zName); sqlite3VdbeAddOp3(v, OP_Concat, 4, 2, 3); integrityCheckResultRow(v); sqlite3VdbeJumpHere(v, addr); } } #endif /* SQLITE_OMIT_BTREECOUNT */ } } { static const int iLn = VDBE_OFFSET_LINENO(2); static const VdbeOpList endCode[] = { { OP_AddImm, 1, 0, 0}, /* 0 */ { OP_IfNotZero, 1, 4, 0}, /* 1 */ { OP_String8, 0, 3, 0}, /* 2 */ { OP_ResultRow, 3, 1, 0}, /* 3 */ { OP_Halt, 0, 0, 0}, /* 4 */ { OP_String8, 0, 3, 0}, /* 5 */ { OP_Goto, 0, 3, 0}, /* 6 */ }; VdbeOp *aOp; aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn); if( aOp ){ aOp[0].p2 = 1-mxErr; aOp[2].p4type = P4_STATIC; aOp[2].p4.z = "ok"; aOp[5].p4type = P4_STATIC; aOp[5].p4.z = (char*)sqlite3ErrStr(SQLITE_CORRUPT); } sqlite3VdbeChangeP3(v, 0, sqlite3VdbeCurrentAddr(v)-2); } } break; #endif /* SQLITE_OMIT_INTEGRITY_CHECK */ #ifndef SQLITE_OMIT_UTF16 /* ** PRAGMA encoding ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be" ** ** In its first form, this pragma returns the encoding of the main ** database. If the database is not initialized, it is initialized now. ** ** The second form of this pragma is a no-op if the main database file ** has not already been initialized. In this case it sets the default ** encoding that will be used for the main database file if a new file ** is created. If an existing main database file is opened, then the ** default text encoding for the existing database is used. ** ** In all cases new databases created using the ATTACH command are ** created to use the same default text encoding as the main database. If ** the main database has not been initialized and/or created when ATTACH ** is executed, this is done before the ATTACH operation. ** ** In the second form this pragma sets the text encoding to be used in ** new database files created using this database handle. It is only ** useful if invoked immediately after the main database i */ case PragTyp_ENCODING: { static const struct EncName { char *zName; u8 enc; } encnames[] = { { "UTF8", SQLITE_UTF8 }, { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */ { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */ { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */ { "UTF16le", SQLITE_UTF16LE }, { "UTF16be", SQLITE_UTF16BE }, { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */ { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */ { 0, 0 } }; const struct EncName *pEnc; if( !zRight ){ /* "PRAGMA encoding" */ if( sqlite3ReadSchema(pParse) ) goto pragma_out; assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 ); assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE ); assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE ); returnSingleText(v, encnames[ENC(pParse->db)].zName); }else{ /* "PRAGMA encoding = XXX" */ /* Only change the value of sqlite.enc if the database handle is not ** initialized. If the main database exists, the new sqlite.enc value ** will be overwritten when the schema is next loaded. If it does not ** already exists, it will be created to use the new encoding value. */ if( !(DbHasProperty(db, 0, DB_SchemaLoaded)) || DbHasProperty(db, 0, DB_Empty) ){ for(pEnc=&encnames[0]; pEnc->zName; pEnc++){ if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){ SCHEMA_ENC(db) = ENC(db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE; break; } } if( !pEnc->zName ){ sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight); } } } } break; #endif /* SQLITE_OMIT_UTF16 */ #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS /* ** PRAGMA [schema.]schema_version ** PRAGMA [schema.]schema_version = <integer> ** ** PRAGMA [schema.]user_version ** PRAGMA [schema.]user_version = <integer> ** ** PRAGMA [schema.]freelist_count ** ** PRAGMA [schema.]data_version ** ** PRAGMA [schema.]application_id ** PRAGMA [schema.]application_id = <integer> ** ** The pragma's schema_version and user_version are used to set or get ** the value of the schema-version and user-version, respectively. Both ** the schema-version and the user-version are 32-bit signed integers ** stored in the database header. ** ** The schema-cookie is usually only manipulated internally by SQLite. It ** is incremented by SQLite whenever the database schema is modified (by ** creating or dropping a table or index). The schema version is used by ** SQLite each time a query is executed to ensure that the internal cache ** of the schema used when compiling the SQL query matches the schema of ** the database against which the compiled query is actually executed. ** Subverting this mechanism by using "PRAGMA schema_version" to modify ** the schema-version is potentially dangerous and may lead to program ** crashes or database corruption. Use with caution! ** ** The user-version is not used internally by SQLite. It may be used by ** applications for any purpose. */ case PragTyp_HEADER_VALUE: { int iCookie = pPragma->iArg; /* Which cookie to read or write */ sqlite3VdbeUsesBtree(v, iDb); if( zRight && (pPragma->mPragFlg & PragFlg_ReadOnly)==0 ){ /* Write the specified cookie value */ static const VdbeOpList setCookie[] = { { OP_Transaction, 0, 1, 0}, /* 0 */ { OP_SetCookie, 0, 0, 0}, /* 1 */ }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(setCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p2 = iCookie; aOp[1].p3 = sqlite3Atoi(zRight); }else{ /* Read the specified cookie value */ static const VdbeOpList readCookie[] = { { OP_Transaction, 0, 0, 0}, /* 0 */ { OP_ReadCookie, 0, 1, 0}, /* 1 */ { OP_ResultRow, 1, 1, 0} }; VdbeOp *aOp; sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(readCookie)); aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0); if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break; aOp[0].p1 = iDb; aOp[1].p1 = iDb; aOp[1].p3 = iCookie; sqlite3VdbeReusable(v); } } break; #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */ #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS /* ** PRAGMA compile_options ** ** Return the names of all compile-time options used in this build, ** one option per row. */ case PragTyp_COMPILE_OPTIONS: { int i = 0; const char *zOpt; pParse->nMem = 1; while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){ sqlite3VdbeLoadString(v, 1, zOpt); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1); } sqlite3VdbeReusable(v); } break; #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */ #ifndef SQLITE_OMIT_WAL /* ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate ** ** Checkpoint the database. */ case PragTyp_WAL_CHECKPOINT: { int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED); int eMode = SQLITE_CHECKPOINT_PASSIVE; if( zRight ){ if( sqlite3StrICmp(zRight, "full")==0 ){ eMode = SQLITE_CHECKPOINT_FULL; }else if( sqlite3StrICmp(zRight, "restart")==0 ){ eMode = SQLITE_CHECKPOINT_RESTART; }else if( sqlite3StrICmp(zRight, "truncate")==0 ){ eMode = SQLITE_CHECKPOINT_TRUNCATE; } } pParse->nMem = 3; sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1); sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3); } break; /* ** PRAGMA wal_autocheckpoint ** PRAGMA wal_autocheckpoint = N ** ** Configure a database connection to automatically checkpoint a database ** after accumulating N frames in the log. Or query for the current value ** of N. */ case PragTyp_WAL_AUTOCHECKPOINT: { if( zRight ){ sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->xWalCallback==sqlite3WalDefaultHook ? SQLITE_PTR_TO_INT(db->pWalArg) : 0); } break; #endif /* ** PRAGMA shrink_memory ** ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database ** connection on which it is invoked to free up as much memory as it ** can, by calling sqlite3_db_release_memory(). */ case PragTyp_SHRINK_MEMORY: { sqlite3_db_release_memory(db); break; } /* ** PRAGMA optimize ** PRAGMA optimize(MASK) ** PRAGMA schema.optimize ** PRAGMA schema.optimize(MASK) ** ** Attempt to optimize the database. All schemas are optimized in the first ** two forms, and only the specified schema is optimized in the latter two. ** ** The details of optimizations performed by this pragma are expected ** to change and improve over time. Applications should anticipate that ** this pragma will perform new optimizations in future releases. ** ** The optional argument is a bitmask of optimizations to perform: ** ** 0x0001 Debugging mode. Do not actually perform any optimizations ** but instead return one line of text for each optimization ** that would have been done. Off by default. ** ** 0x0002 Run ANALYZE on tables that might benefit. On by default. ** See below for additional information. ** ** 0x0004 (Not yet implemented) Record usage and performance ** information from the current session in the ** database file so that it will be available to "optimize" ** pragmas run by future database connections. ** ** 0x0008 (Not yet implemented) Create indexes that might have ** been helpful to recent queries ** ** The default MASK is and always shall be 0xfffe. 0xfffe means perform all ** of the optimizations listed above except Debug Mode, including new ** optimizations that have not yet been invented. If new optimizations are ** ever added that should be off by default, those off-by-default ** optimizations will have bitmasks of 0x10000 or larger. ** ** DETERMINATION OF WHEN TO RUN ANALYZE ** ** In the current implementation, a table is analyzed if only if all of ** the following are true: ** ** (1) MASK bit 0x02 is set. ** ** (2) The query planner used sqlite_stat1-style statistics for one or ** more indexes of the table at some point during the lifetime of ** the current connection. ** ** (3) One or more indexes of the table are currently unanalyzed OR ** the number of rows in the table has increased by 25 times or more ** since the last time ANALYZE was run. ** ** The rules for when tables are analyzed are likely to change in ** future releases. */ case PragTyp_OPTIMIZE: { int iDbLast; /* Loop termination point for the schema loop */ int iTabCur; /* Cursor for a table whose size needs checking */ HashElem *k; /* Loop over tables of a schema */ Schema *pSchema; /* The current schema */ Table *pTab; /* A table in the schema */ Index *pIdx; /* An index of the table */ LogEst szThreshold; /* Size threshold above which reanalysis is needd */ char *zSubSql; /* SQL statement for the OP_SqlExec opcode */ u32 opMask; /* Mask of operations to perform */ if( zRight ){ opMask = (u32)sqlite3Atoi(zRight); if( (opMask & 0x02)==0 ) break; }else{ opMask = 0xfffe; } iTabCur = pParse->nTab++; for(iDbLast = zDb?iDb:db->nDb-1; iDb<=iDbLast; iDb++){ if( iDb==1 ) continue; sqlite3CodeVerifySchema(pParse, iDb); pSchema = db->aDb[iDb].pSchema; for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){ pTab = (Table*)sqliteHashData(k); /* If table pTab has not been used in a way that would benefit from ** having analysis statistics during the current session, then skip it. ** This also has the effect of skipping virtual tables and views */ if( (pTab->tabFlags & TF_StatsUsed)==0 ) continue; /* Reanalyze if the table is 25 times larger than the last analysis */ szThreshold = pTab->nRowLogEst + 46; assert( sqlite3LogEst(25)==46 ); for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){ if( !pIdx->hasStat1 ){ szThreshold = 0; /* Always analyze if any index lacks statistics */ break; } } if( szThreshold ){ sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead); sqlite3VdbeAddOp3(v, OP_IfSmaller, iTabCur, sqlite3VdbeCurrentAddr(v)+2+(opMask&1), szThreshold); VdbeCoverage(v); } zSubSql = sqlite3MPrintf(db, "ANALYZE \"%w\".\"%w\"", db->aDb[iDb].zDbSName, pTab->zName); if( opMask & 0x01 ){ int r1 = sqlite3GetTempReg(pParse); sqlite3VdbeAddOp4(v, OP_String8, 0, r1, 0, zSubSql, P4_DYNAMIC); sqlite3VdbeAddOp2(v, OP_ResultRow, r1, 1); }else{ sqlite3VdbeAddOp4(v, OP_SqlExec, 0, 0, 0, zSubSql, P4_DYNAMIC); } } } sqlite3VdbeAddOp0(v, OP_Expire); break; } /* ** PRAGMA busy_timeout ** PRAGMA busy_timeout = N ** ** Call sqlite3_busy_timeout(db, N). Return the current timeout value ** if one is set. If no busy handler or a different busy handler is set ** then 0 is returned. Setting the busy_timeout to 0 or negative ** disables the timeout. */ /*case PragTyp_BUSY_TIMEOUT*/ default: { assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT ); if( zRight ){ sqlite3_busy_timeout(db, sqlite3Atoi(zRight)); } returnSingleInt(v, db->busyTimeout); break; } /* ** PRAGMA soft_heap_limit ** PRAGMA soft_heap_limit = N ** ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the ** sqlite3_soft_heap_limit64() interface with the argument N, if N is ** specified and is a non-negative integer. ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always ** returns the same integer that would be returned by the ** sqlite3_soft_heap_limit64(-1) C-language function. */ case PragTyp_SOFT_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_soft_heap_limit64(N); } returnSingleInt(v, sqlite3_soft_heap_limit64(-1)); break; } /* ** PRAGMA hard_heap_limit ** PRAGMA hard_heap_limit = N ** ** Invoke sqlite3_hard_heap_limit64() to query or set the hard heap ** limit. The hard heap limit can be activated or lowered by this ** pragma, but not raised or deactivated. Only the ** sqlite3_hard_heap_limit64() C-language API can raise or deactivate ** the hard heap limit. This allows an application to set a heap limit ** constraint that cannot be relaxed by an untrusted SQL script. */ case PragTyp_HARD_HEAP_LIMIT: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){ sqlite3_int64 iPrior = sqlite3_hard_heap_limit64(-1); if( N>0 && (iPrior==0 || iPrior>N) ) sqlite3_hard_heap_limit64(N); } returnSingleInt(v, sqlite3_hard_heap_limit64(-1)); break; } /* ** PRAGMA threads ** PRAGMA threads = N ** ** Configure the maximum number of worker threads. Return the new ** maximum, which might be less than requested. */ case PragTyp_THREADS: { sqlite3_int64 N; if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK && N>=0 ){ sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff)); } returnSingleInt(v, sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1)); break; } #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST) /* ** Report the current state of file logs for all databases */ case PragTyp_LOCK_STATUS: { static const char *const azLockName[] = { "unlocked", "shared", "reserved", "pending", "exclusive" }; int i; pParse->nMem = 2; for(i=0; i<db->nDb; i++){ Btree *pBt; const char *zState = "unknown"; int j; if( db->aDb[i].zDbSName==0 ) continue; pBt = db->aDb[i].pBt; if( pBt==0 || sqlite3BtreePager(pBt)==0 ){ zState = "closed"; }else if( sqlite3_file_control(db, i ? db->aDb[i].zDbSName : 0, SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){ zState = azLockName[j]; } sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zDbSName, zState); } break; } #endif #ifdef SQLITE_HAS_CODEC /* Pragma iArg ** ---------- ------ ** key 0 ** rekey 1 ** hexkey 2 ** hexrekey 3 ** textkey 4 ** textrekey 5 */ case PragTyp_KEY: { if( zRight ){ char zBuf[40]; const char *zKey = zRight; int n; if( pPragma->iArg==2 || pPragma->iArg==3 ){ u8 iByte; int i; for(i=0, iByte=0; i<sizeof(zBuf)*2 && sqlite3Isxdigit(zRight[i]); i++){ iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]); if( (i&1)!=0 ) zBuf[i/2] = iByte; } zKey = zBuf; n = i/2; }else{ n = pPragma->iArg<4 ? sqlite3Strlen30(zRight) : -1; } if( (pPragma->iArg & 1)==0 ){ rc = sqlite3_key_v2(db, zDb, zKey, n); }else{ rc = sqlite3_rekey_v2(db, zDb, zKey, n); } if( rc==SQLITE_OK && n!=0 ){ sqlite3VdbeSetNumCols(v, 1); sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "ok", SQLITE_STATIC); returnSingleText(v, "ok"); } } break; } #endif #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD) case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){ #ifdef SQLITE_HAS_CODEC if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){ sqlite3_activate_see(&zRight[4]); } #endif #ifdef SQLITE_ENABLE_CEROD if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){ sqlite3_activate_cerod(&zRight[6]); } #endif } break; #endif } /* End of the PRAGMA switch */ /* The following block is a no-op unless SQLITE_DEBUG is defined. Its only ** purpose is to execute assert() statements to verify that if the ** PragFlg_NoColumns1 flag is set and the caller specified an argument ** to the PRAGMA, the implementation has not added any OP_ResultRow ** instructions to the VM. */ if( (pPragma->mPragFlg & PragFlg_NoColumns1) && zRight ){ sqlite3VdbeVerifyNoResultRow(v); } pragma_out: sqlite3DbFree(db, zLeft); sqlite3DbFree(db, zRight); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-754'], 'message': 'Fix the NOT NULL verification logic in PRAGMA integrity_check so that it works for generated columns whose value is the result of a comparison operator. Ticket [bd8c280671ba44a7] FossilOrigin-Name: f3b39c71b88cb6721f443de56cdce4c08252453a5e340b00a2bd88dc10c42400'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: 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; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'When processing constant integer values in ORDER BY clauses of window definitions (see check-in [7e4809eadfe99ebf]) be sure to fully disable the constant value to avoid an invalid pointer dereference if the expression is ever duplicated. This fixes a crash report from Yongheng and Rui. FossilOrigin-Name: 1ca0bd982ab1183bbafce0d260e4dceda5eb766ed2e7793374a88d1ae0bdd2ca'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int kvaser_usb_leaf_flush_queue(struct kvaser_usb_net_priv *priv) { struct kvaser_cmd *cmd; int rc; cmd = kmalloc(sizeof(*cmd), GFP_KERNEL); if (!cmd) return -ENOMEM; cmd->id = CMD_FLUSH_QUEUE; cmd->len = CMD_HEADER_LEN + sizeof(struct kvaser_cmd_flush_queue); cmd->u.flush_queue.channel = priv->channel; cmd->u.flush_queue.flags = 0x00; rc = kvaser_usb_send_cmd(priv->dev, cmd, cmd->len); kfree(cmd); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-200', 'CWE-908'], 'message': 'can: kvaser_usb: kvaser_usb_leaf: Fix some info-leaks to USB devices Uninitialized Kernel memory can leak to USB devices. Fix this by using kzalloc() instead of kmalloc(). Signed-off-by: Xiaolong Huang <butterflyhuangxx@gmail.com> Fixes: 7259124eac7d ("can: kvaser_usb: Split driver into kvaser_usb_core.c and kvaser_usb_leaf.c") Cc: linux-stable <stable@vger.kernel.org> # >= v4.19 Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { size_t i; int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel; #ifdef KALLE_0 int offset_diff; #endif const maker_note_type *maker_note; char *dir_start; int data_len; for (i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) { #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "No maker note data found. Detected maker: %s (length = %d)", ImageInfo->make, strlen(ImageInfo->make)); #endif /* unknown manufacturer, not an error, use it as a string */ return TRUE; } maker_note = maker_note_array+i; /*exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "check (%s,%s)", maker_note->make?maker_note->make:"", maker_note->model?maker_note->model:"");*/ if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) continue; if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) continue; if (maker_note->id_string && value_len >= maker_note->id_string_len && strncmp(maker_note->id_string, value_ptr, maker_note->id_string_len)) continue; break; } if (value_len < 2 || maker_note->offset >= value_len - 1) { /* Do not go past the value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X offset 0x%04X", value_len, maker_note->offset); return FALSE; } dir_start = value_ptr + maker_note->offset; #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Process %s @x%04X + 0x%04X=%d: %s", exif_get_sectionname(section_index), (int)dir_start-(int)offset_base+maker_note->offset+displacement, value_len, value_len, exif_char_dump(value_ptr, value_len, (int)dir_start-(int)offset_base+maker_note->offset+displacement)); #endif ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; data_len = value_len; break; #ifdef KALLE_0 case MN_OFFSET_GUESS: if (maker_note->offset + 10 + 4 >= value_len) { /* Can not read dir_start+10 since it's beyond value end */ exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data too short: 0x%04X", value_len); return FALSE; } offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Using automatic offset correction: 0x%04X", ((int)dir_start-(int)offset_base+maker_note->offset+displacement) + offset_diff); #endif if (offset_diff < 0 || offset_diff >= value_len ) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "IFD data bad offset: 0x%04X length 0x%04X", offset_diff, value_len); return FALSE; } offset_base = value_ptr + offset_diff; data_len = value_len - offset_diff; break; #endif default: case MN_OFFSET_NORMAL: data_len = value_len; break; } if ((2+NumDirEntries*12) > value_len) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 2 + 0x%04X*12 = 0x%04X > 0x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return FALSE; } if ((dir_start - value_ptr) > value_len - (2+NumDirEntries*12)) { exif_error_docref("exif_read_data#error_ifd" EXIFERR_CC, ImageInfo, E_WARNING, "Illegal IFD size: 0x%04X > 0x%04X", (dir_start - value_ptr) + (2+NumDirEntries*12), value_len); return FALSE; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, data_len, displacement, section_index, 0, maker_note->tag_table)) { return FALSE; } } ImageInfo->motorola_intel = old_motorola_intel; /* NextDirOffset (must be NULL) = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel);*/ #ifdef EXIF_DEBUG exif_error_docref(NULL EXIFERR_CC, ImageInfo, E_NOTICE, "Subsection %s done", exif_get_sectionname(SECTION_MAKERNOTE)); #endif return TRUE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix bug #78793'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){ assert( p->nOp>0 || p->aOp==0 ); assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed ); if( p->nOp ){ assert( p->aOp ); sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment); p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-755'], 'message': 'When an error occurs while rewriting the parser tree for window functions in the sqlite3WindowRewrite() routine, make sure that pParse->nErr is set, and make sure that this shuts down any subsequent code generation that might depend on the transformations that were implemented. This fixes a problem discovered by the Yongheng and Rui fuzzer. FossilOrigin-Name: e2bddcd4c55ba3cbe0130332679ff4b048630d0ced9a8899982edb5a3569ba7f'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: 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; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Continue to back away from the LEFT JOIN optimization of check-in [41c27bc0ff1d3135] by disallowing query flattening if the outer query is DISTINCT. Without this fix, if an index scan is run on the table within the view on the right-hand side of the LEFT JOIN, stale result registers might be accessed yielding incorrect results, and/or an OP_IfNullRow opcode might be invoked on the un-opened table, resulting in a NULL-pointer dereference. This problem was found by the Yongheng and Rui fuzzer. FossilOrigin-Name: 862974312edf00e9d1068115d1a39b7235b7db68b6d86b81d38a12f025a4748e'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int zipfileUpdate( sqlite3_vtab *pVtab, int nVal, sqlite3_value **apVal, sqlite_int64 *pRowid ){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; /* Return Code */ ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ u32 mode = 0; /* Mode for new entry */ u32 mTime = 0; /* Modification time for new entry */ i64 sz = 0; /* Uncompressed size */ const char *zPath = 0; /* Path for new entry */ int nPath = 0; /* strlen(zPath) */ const u8 *pData = 0; /* Pointer to buffer containing content */ int nData = 0; /* Size of pData buffer in bytes */ int iMethod = 0; /* Compression method for new entry */ u8 *pFree = 0; /* Free this */ char *zFree = 0; /* Also free this */ ZipfileEntry *pOld = 0; ZipfileEntry *pOld2 = 0; int bUpdate = 0; /* True for an update that modifies "name" */ int bIsDir = 0; u32 iCrc32 = 0; if( pTab->pWriteFd==0 ){ rc = zipfileBegin(pVtab); if( rc!=SQLITE_OK ) return rc; } /* If this is a DELETE or UPDATE, find the archive entry to delete. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); int nDelete = (int)strlen(zDelete); if( nVal>1 ){ const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ bUpdate = 1; } } for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ break; } assert( pOld->pNext ); } } if( nVal>1 ){ /* Check that "sz" and "rawdata" are both NULL: */ if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ zipfileTableErr(pTab, "sz must be NULL"); rc = SQLITE_CONSTRAINT; } if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ zipfileTableErr(pTab, "rawdata must be NULL"); rc = SQLITE_CONSTRAINT; } if( rc==SQLITE_OK ){ if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ /* data=NULL. A directory */ bIsDir = 1; }else{ /* Value specified for "data", and possibly "method". This must be ** a regular file or a symlink. */ const u8 *aIn = sqlite3_value_blob(apVal[7]); int nIn = sqlite3_value_bytes(apVal[7]); int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; iMethod = sqlite3_value_int(apVal[8]); sz = nIn; pData = aIn; nData = nIn; if( iMethod!=0 && iMethod!=8 ){ zipfileTableErr(pTab, "unknown compression method: %d", iMethod); rc = SQLITE_CONSTRAINT; }else{ if( bAuto || iMethod ){ int nCmp; rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); if( rc==SQLITE_OK ){ if( iMethod || nCmp<nIn ){ iMethod = 8; pData = pFree; nData = nCmp; } } } iCrc32 = crc32(0, aIn, nIn); } } } if( rc==SQLITE_OK ){ rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); } if( rc==SQLITE_OK ){ zPath = (const char*)sqlite3_value_text(apVal[2]); nPath = (int)strlen(zPath); mTime = zipfileGetTime(apVal[4]); } if( rc==SQLITE_OK && bIsDir ){ /* For a directory, check that the last character in the path is a ** '/'. This appears to be required for compatibility with info-zip ** (the unzip command on unix). It does not create directories ** otherwise. */ if( zPath[nPath-1]!='/' ){ zFree = sqlite3_mprintf("%s/", zPath); if( zFree==0 ){ rc = SQLITE_NOMEM; } zPath = (const char*)zFree; nPath++; } } /* Check that we're not inserting a duplicate entry -OR- updating an ** entry with a path, thereby making it into a duplicate. */ if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ ZipfileEntry *p; for(p=pTab->pFirstEntry; p; p=p->pNext){ if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ switch( sqlite3_vtab_on_conflict(pTab->db) ){ case SQLITE_IGNORE: { goto zipfile_update_done; } case SQLITE_REPLACE: { pOld2 = p; break; } default: { zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); rc = SQLITE_CONSTRAINT; break; } } break; } } } if( rc==SQLITE_OK ){ /* Create the new CDS record. */ pNew = zipfileNewEntry(zPath); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; pNew->cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&pNew->cds, mTime); pNew->cds.crc32 = iCrc32; pNew->cds.szCompressed = nData; pNew->cds.szUncompressed = (u32)sz; pNew->cds.iExternalAttr = (mode<<16); pNew->cds.iOffset = (u32)pTab->szCurrent; pNew->cds.nFile = (u16)nPath; pNew->mUnixTime = (u32)mTime; rc = zipfileAppendEntry(pTab, pNew, pData, nData); zipfileAddEntry(pTab, pOld, pNew); } } } if( rc==SQLITE_OK && (pOld || pOld2) ){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ pCsr->pCurrent = pCsr->pCurrent->pNext; pCsr->bNoop = 1; } } zipfileRemoveEntryFromList(pTab, pOld); zipfileRemoveEntryFromList(pTab, pOld2); } zipfile_update_done: sqlite3_free(pFree); sqlite3_free(zFree); return rc; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-434'], 'message': 'Fix the zipfile extension so that INSERT works even if the pathname of the file being inserted is a NULL. Bug discovered by the Yongheng and Rui fuzzer. FossilOrigin-Name: a80f84b511231204658304226de3e075a55afc2e3f39ac063716f7a57f585c06'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static INLINE int vpx_read(vpx_reader *r, int prob) { unsigned int bit = 0; BD_VALUE value; BD_VALUE bigsplit; int count; unsigned int range; unsigned int split = (r->range * prob + (256 - prob)) >> CHAR_BIT; if (r->count < 0) vpx_reader_fill(r); value = r->value; count = r->count; bigsplit = (BD_VALUE)split << (BD_VALUE_SIZE - CHAR_BIT); range = split; if (value >= bigsplit) { range = r->range - split; value = value - bigsplit; bit = 1; } { const int shift = vpx_norm[range]; range <<= shift; value <<= shift; count -= shift; } r->value = value; r->count = count; r->range = range; return bit; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix OOB memory access on fuzzed data vp8_norm table has 256 elements while index to it can be higher on fuzzed data. Typecasting it to unsigned char will ensure valid range and will trigger proper error later. Also declaring "shift" as unsigned char to avoid UB sanitizer warning BUG=b/122373286,b/122373822,b/122371119 Change-Id: I3cef1d07f107f061b1504976a405fa0865afe9f5'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static vpx_codec_err_t decoder_peek_si_internal( const uint8_t *data, unsigned int data_sz, vpx_codec_stream_info_t *si, int *is_intra_only, vpx_decrypt_cb decrypt_cb, void *decrypt_state) { int intra_only_flag = 0; uint8_t clear_buffer[10]; if (data + data_sz <= data) return VPX_CODEC_INVALID_PARAM; si->is_kf = 0; si->w = si->h = 0; if (decrypt_cb) { data_sz = VPXMIN(sizeof(clear_buffer), data_sz); decrypt_cb(decrypt_state, data, clear_buffer, data_sz); data = clear_buffer; } // A maximum of 6 bits are needed to read the frame marker, profile and // show_existing_frame. if (data_sz < 1) return VPX_CODEC_UNSUP_BITSTREAM; { int show_frame; int error_resilient; struct vpx_read_bit_buffer rb = { data, data + data_sz, 0, NULL, NULL }; const int frame_marker = vpx_rb_read_literal(&rb, 2); const BITSTREAM_PROFILE profile = vp9_read_profile(&rb); if (frame_marker != VP9_FRAME_MARKER) return VPX_CODEC_UNSUP_BITSTREAM; if (profile >= MAX_PROFILES) return VPX_CODEC_UNSUP_BITSTREAM; if (vpx_rb_read_bit(&rb)) { // show an existing frame // If profile is > 2 and show_existing_frame is true, then at least 1 more // byte (6+3=9 bits) is needed. if (profile > 2 && data_sz < 2) return VPX_CODEC_UNSUP_BITSTREAM; vpx_rb_read_literal(&rb, 3); // Frame buffer to show. return VPX_CODEC_OK; } // For the rest of the function, a maximum of 9 more bytes are needed // (computed by taking the maximum possible bits needed in each case). Note // that this has to be updated if we read any more bits in this function. if (data_sz < 10) return VPX_CODEC_UNSUP_BITSTREAM; si->is_kf = !vpx_rb_read_bit(&rb); show_frame = vpx_rb_read_bit(&rb); error_resilient = vpx_rb_read_bit(&rb); if (si->is_kf) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } else { intra_only_flag = show_frame ? 0 : vpx_rb_read_bit(&rb); rb.bit_offset += error_resilient ? 0 : 2; // reset_frame_context if (intra_only_flag) { if (!vp9_read_sync_code(&rb)) return VPX_CODEC_UNSUP_BITSTREAM; if (profile > PROFILE_0) { if (!parse_bitdepth_colorspace_sampling(profile, &rb)) return VPX_CODEC_UNSUP_BITSTREAM; } rb.bit_offset += REF_FRAMES; // refresh_frame_flags vp9_read_frame_size(&rb, (int *)&si->w, (int *)&si->h); } } } if (is_intra_only != NULL) *is_intra_only = intra_only_flag; return VPX_CODEC_OK; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'vp9: fix OOB read in decoder_peek_si_internal Profile 1 or 3 bitstreams may require 11 bytes for the header in the intra-only case. Additionally add a check on the bit reader's error handler callback to ensure it's non-NULL before calling to avoid future regressions. This has existed since at least (pre-1.4.0): 09bf1d61c Changes hdr for profiles > 1 for intraonly frames BUG=webm:1543 Change-Id: I23901e6e3a219170e8ea9efecc42af0be2e5c378'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TEST(DecodeAPI, Vp9PeekSI) { const vpx_codec_iface_t *const codec = &vpx_codec_vp9_dx_algo; // The first 9 bytes are valid and the rest of the bytes are made up. Until // size 10, this should return VPX_CODEC_UNSUP_BITSTREAM and after that it // should return VPX_CODEC_CORRUPT_FRAME. const uint8_t data[32] = { 0x85, 0xa4, 0xc1, 0xa1, 0x38, 0x81, 0xa3, 0x49, 0x83, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; for (uint32_t data_sz = 1; data_sz <= 32; ++data_sz) { // Verify behavior of vpx_codec_decode. vpx_codec_decode doesn't even get // to decoder_peek_si_internal on frames of size < 8. if (data_sz >= 8) { vpx_codec_ctx_t dec; EXPECT_EQ(VPX_CODEC_OK, vpx_codec_dec_init(&dec, codec, NULL, 0)); EXPECT_EQ( (data_sz < 10) ? VPX_CODEC_UNSUP_BITSTREAM : VPX_CODEC_CORRUPT_FRAME, vpx_codec_decode(&dec, data, data_sz, NULL, 0)); vpx_codec_iter_t iter = NULL; EXPECT_EQ(NULL, vpx_codec_get_frame(&dec, &iter)); EXPECT_EQ(VPX_CODEC_OK, vpx_codec_destroy(&dec)); } // Verify behavior of vpx_codec_peek_stream_info. vpx_codec_stream_info_t si; si.sz = sizeof(si); EXPECT_EQ((data_sz < 10) ? VPX_CODEC_UNSUP_BITSTREAM : VPX_CODEC_OK, vpx_codec_peek_stream_info(codec, data, data_sz, &si)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'vp9: fix OOB read in decoder_peek_si_internal Profile 1 or 3 bitstreams may require 11 bytes for the header in the intra-only case. Additionally add a check on the bit reader's error handler callback to ensure it's non-NULL before calling to avoid future regressions. This has existed since at least (pre-1.4.0): 09bf1d61c Changes hdr for profiles > 1 for intraonly frames BUG=webm:1543 Change-Id: I23901e6e3a219170e8ea9efecc42af0be2e5c378'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: std::string GetTempFileName() { #if !defined _MSC_VER && !defined __MINGW32__ std::string temp_file_name_template_str = std::string(std::getenv("TEST_TMPDIR") ? std::getenv("TEST_TMPDIR") : ".") + "/libwebm_temp.XXXXXX"; char* temp_file_name_template = new char[temp_file_name_template_str.length() + 1]; memset(temp_file_name_template, 0, temp_file_name_template_str.length() + 1); temp_file_name_template_str.copy(temp_file_name_template, temp_file_name_template_str.length(), 0); int fd = mkstemp(temp_file_name_template); std::string temp_file_name = (fd != -1) ? std::string(temp_file_name_template) : std::string(); delete[] temp_file_name_template; if (fd != -1) { close(fd); } return temp_file_name; #else char tmp_file_name[_MAX_PATH]; #if defined _MSC_VER || defined MINGW_HAS_SECURE_API errno_t err = tmpnam_s(tmp_file_name); #else char* fname_pointer = tmpnam(tmp_file_name); int err = (fname_pointer == &tmp_file_name[0]) ? 0 : -1; #endif if (err == 0) { return std::string(tmp_file_name); } return std::string(); #endif } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-358-gdbf1d10 changelog: https://chromium.googlesource.com/webm/libwebm/+log/libwebm-1.0.0.27-351-g9f23fbc..libwebm-1.0.0.27-358-gdbf1d10 Change-Id: I28a6b3ae02a53fb1f2029eee11e9449afb94c8e3'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: VideoTrack::VideoTrack(Segment* pSegment, long long element_start, long long element_size) : Track(pSegment, element_start, element_size), m_colour(NULL), m_projection(NULL) {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: VideoTrack::VideoTrack(unsigned int* seed) : Track(seed), display_height_(0), display_width_(0), pixel_height_(0), pixel_width_(0), crop_left_(0), crop_right_(0), crop_top_(0), crop_bottom_(0), frame_rate_(0.0), height_(0), stereo_mode_(0), alpha_mode_(0), width_(0), colour_(NULL), projection_(NULL) {} ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: uint64_t VideoTrack::VideoPayloadSize() const { uint64_t size = EbmlElementSize( libwebm::kMkvPixelWidth, static_cast<uint64>((pixel_width_ > 0) ? pixel_width_ : width_)); size += EbmlElementSize( libwebm::kMkvPixelHeight, static_cast<uint64>((pixel_height_ > 0) ? pixel_height_ : height_)); if (display_width_ > 0) size += EbmlElementSize(libwebm::kMkvDisplayWidth, static_cast<uint64>(display_width_)); if (display_height_ > 0) size += EbmlElementSize(libwebm::kMkvDisplayHeight, static_cast<uint64>(display_height_)); if (crop_left_ > 0) size += EbmlElementSize(libwebm::kMkvPixelCropLeft, static_cast<uint64>(crop_left_)); if (crop_right_ > 0) size += EbmlElementSize(libwebm::kMkvPixelCropRight, static_cast<uint64>(crop_right_)); if (crop_top_ > 0) size += EbmlElementSize(libwebm::kMkvPixelCropTop, static_cast<uint64>(crop_top_)); if (crop_bottom_ > 0) size += EbmlElementSize(libwebm::kMkvPixelCropBottom, static_cast<uint64>(crop_bottom_)); if (stereo_mode_ > kMono) size += EbmlElementSize(libwebm::kMkvStereoMode, static_cast<uint64>(stereo_mode_)); if (alpha_mode_ > kNoAlpha) size += EbmlElementSize(libwebm::kMkvAlphaMode, static_cast<uint64>(alpha_mode_)); if (frame_rate_ > 0.0) size += EbmlElementSize(libwebm::kMkvFrameRate, static_cast<float>(frame_rate_)); if (colour_) size += colour_->ColourSize(); if (projection_) size += projection_->ProjectionSize(); return size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int MkvReader::Read(long long offset, long len, unsigned char* buffer) { if (m_file == NULL) return -1; if (offset < 0) return -1; if (len < 0) return -1; if (len == 0) return 0; if (offset >= m_length) return -1; #ifdef _MSC_VER const int status = _fseeki64(m_file, offset, SEEK_SET); if (status) return -1; // error #else fseeko(m_file, static_cast<off_t>(offset), SEEK_SET); #endif const size_t size = fread(buffer, 1, len, m_file); if (size < size_t(len)) return -1; // error return 0; // success } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool MasteringMetadata::Write(IMkvWriter* writer) const { const uint64_t size = PayloadSize(); // Don't write an empty element. if (size == 0) return true; if (!WriteEbmlMasterElement(writer, libwebm::kMkvMasteringMetadata, size)) return false; if (luminance_max_ != kValueNotPresent && !WriteEbmlElement(writer, libwebm::kMkvLuminanceMax, luminance_max_)) { return false; } if (luminance_min_ != kValueNotPresent && !WriteEbmlElement(writer, libwebm::kMkvLuminanceMin, luminance_min_)) { return false; } if (r_ && !r_->Write(writer, libwebm::kMkvPrimaryRChromaticityX, libwebm::kMkvPrimaryRChromaticityY)) { return false; } if (g_ && !g_->Write(writer, libwebm::kMkvPrimaryGChromaticityX, libwebm::kMkvPrimaryGChromaticityY)) { return false; } if (b_ && !b_->Write(writer, libwebm::kMkvPrimaryBChromaticityX, libwebm::kMkvPrimaryBChromaticityY)) { return false; } if (white_point_ && !white_point_->Write(writer, libwebm::kMkvWhitePointChromaticityX, libwebm::kMkvWhitePointChromaticityY)) { return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: uint64 WriteBlock(IMkvWriter* writer, const Frame* const frame, int64 timecode, uint64 timecode_scale) { uint64 block_additional_elem_size = 0; uint64 block_addid_elem_size = 0; uint64 block_more_payload_size = 0; uint64 block_more_elem_size = 0; uint64 block_additions_payload_size = 0; uint64 block_additions_elem_size = 0; if (frame->additional()) { block_additional_elem_size = EbmlElementSize(libwebm::kMkvBlockAdditional, frame->additional(), frame->additional_length()); block_addid_elem_size = EbmlElementSize( libwebm::kMkvBlockAddID, static_cast<uint64>(frame->add_id())); block_more_payload_size = block_addid_elem_size + block_additional_elem_size; block_more_elem_size = EbmlMasterElementSize(libwebm::kMkvBlockMore, block_more_payload_size) + block_more_payload_size; block_additions_payload_size = block_more_elem_size; block_additions_elem_size = EbmlMasterElementSize(libwebm::kMkvBlockAdditions, block_additions_payload_size) + block_additions_payload_size; } uint64 discard_padding_elem_size = 0; if (frame->discard_padding() != 0) { discard_padding_elem_size = EbmlElementSize(libwebm::kMkvDiscardPadding, static_cast<int64>(frame->discard_padding())); } const uint64 reference_block_timestamp = frame->reference_block_timestamp() / timecode_scale; uint64 reference_block_elem_size = 0; if (!frame->is_key()) { reference_block_elem_size = EbmlElementSize(libwebm::kMkvReferenceBlock, reference_block_timestamp); } const uint64 duration = frame->duration() / timecode_scale; uint64 block_duration_elem_size = 0; if (duration > 0) block_duration_elem_size = EbmlElementSize(libwebm::kMkvBlockDuration, duration); const uint64 block_payload_size = 4 + frame->length(); const uint64 block_elem_size = EbmlMasterElementSize(libwebm::kMkvBlock, block_payload_size) + block_payload_size; const uint64 block_group_payload_size = block_elem_size + block_additions_elem_size + block_duration_elem_size + discard_padding_elem_size + reference_block_elem_size; if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlockGroup, block_group_payload_size)) { return 0; } if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlock, block_payload_size)) return 0; if (WriteUInt(writer, frame->track_number())) return 0; if (SerializeInt(writer, timecode, 2)) return 0; // For a Block, flags is always 0. if (SerializeInt(writer, 0, 1)) return 0; if (writer->Write(frame->frame(), static_cast<uint32>(frame->length()))) return 0; if (frame->additional()) { if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlockAdditions, block_additions_payload_size)) { return 0; } if (!WriteEbmlMasterElement(writer, libwebm::kMkvBlockMore, block_more_payload_size)) return 0; if (!WriteEbmlElement(writer, libwebm::kMkvBlockAddID, static_cast<uint64>(frame->add_id()))) return 0; if (!WriteEbmlElement(writer, libwebm::kMkvBlockAdditional, frame->additional(), frame->additional_length())) { return 0; } } if (frame->discard_padding() != 0 && !WriteEbmlElement(writer, libwebm::kMkvDiscardPadding, static_cast<int64>(frame->discard_padding()))) { return false; } if (!frame->is_key() && !WriteEbmlElement(writer, libwebm::kMkvReferenceBlock, reference_block_timestamp)) { return false; } if (duration > 0 && !WriteEbmlElement(writer, libwebm::kMkvBlockDuration, duration)) { return false; } return EbmlMasterElementSize(libwebm::kMkvBlockGroup, block_group_payload_size) + block_group_payload_size; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool Track::Write(IMkvWriter* writer) const { if (!writer) return false; // mandatory elements without a default value. if (!type_ || !codec_id_) return false; // |size| may be bigger than what is written out in this function because // derived classes may write out more data in the Track element. const uint64_t payload_size = PayloadSize(); if (!WriteEbmlMasterElement(writer, libwebm::kMkvTrackEntry, payload_size)) return false; uint64_t size = EbmlElementSize(libwebm::kMkvTrackNumber, static_cast<uint64>(number_)); size += EbmlElementSize(libwebm::kMkvTrackUID, static_cast<uint64>(uid_)); size += EbmlElementSize(libwebm::kMkvTrackType, static_cast<uint64>(type_)); if (codec_id_) size += EbmlElementSize(libwebm::kMkvCodecID, codec_id_); if (codec_private_) size += EbmlElementSize(libwebm::kMkvCodecPrivate, codec_private_, static_cast<uint64>(codec_private_length_)); if (language_) size += EbmlElementSize(libwebm::kMkvLanguage, language_); if (name_) size += EbmlElementSize(libwebm::kMkvName, name_); if (max_block_additional_id_) size += EbmlElementSize(libwebm::kMkvMaxBlockAdditionID, static_cast<uint64>(max_block_additional_id_)); if (codec_delay_) size += EbmlElementSize(libwebm::kMkvCodecDelay, static_cast<uint64>(codec_delay_)); if (seek_pre_roll_) size += EbmlElementSize(libwebm::kMkvSeekPreRoll, static_cast<uint64>(seek_pre_roll_)); if (default_duration_) size += EbmlElementSize(libwebm::kMkvDefaultDuration, static_cast<uint64>(default_duration_)); const int64_t payload_position = writer->Position(); if (payload_position < 0) return false; if (!WriteEbmlElement(writer, libwebm::kMkvTrackNumber, static_cast<uint64>(number_))) return false; if (!WriteEbmlElement(writer, libwebm::kMkvTrackUID, static_cast<uint64>(uid_))) return false; if (!WriteEbmlElement(writer, libwebm::kMkvTrackType, static_cast<uint64>(type_))) return false; if (max_block_additional_id_) { if (!WriteEbmlElement(writer, libwebm::kMkvMaxBlockAdditionID, static_cast<uint64>(max_block_additional_id_))) { return false; } } if (codec_delay_) { if (!WriteEbmlElement(writer, libwebm::kMkvCodecDelay, static_cast<uint64>(codec_delay_))) return false; } if (seek_pre_roll_) { if (!WriteEbmlElement(writer, libwebm::kMkvSeekPreRoll, static_cast<uint64>(seek_pre_roll_))) return false; } if (default_duration_) { if (!WriteEbmlElement(writer, libwebm::kMkvDefaultDuration, static_cast<uint64>(default_duration_))) return false; } if (codec_id_) { if (!WriteEbmlElement(writer, libwebm::kMkvCodecID, codec_id_)) return false; } if (codec_private_) { if (!WriteEbmlElement(writer, libwebm::kMkvCodecPrivate, codec_private_, static_cast<uint64>(codec_private_length_))) return false; } if (language_) { if (!WriteEbmlElement(writer, libwebm::kMkvLanguage, language_)) return false; } if (name_) { if (!WriteEbmlElement(writer, libwebm::kMkvName, name_)) return false; } int64_t stop_position = writer->Position(); if (stop_position < 0 || stop_position - payload_position != static_cast<int64_t>(size)) return false; if (content_encoding_entries_size_ > 0) { uint64_t content_encodings_size = 0; for (uint32_t i = 0; i < content_encoding_entries_size_; ++i) { ContentEncoding* const encoding = content_encoding_entries_[i]; content_encodings_size += encoding->Size(); } if (!WriteEbmlMasterElement(writer, libwebm::kMkvContentEncodings, content_encodings_size)) return false; for (uint32_t i = 0; i < content_encoding_entries_size_; ++i) { ContentEncoding* const encoding = content_encoding_entries_[i]; if (!encoding->Write(writer)) return false; } } stop_position = writer->Position(); if (stop_position < 0) return false; return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'update libwebm to libwebm-1.0.0.27-352-g6ab9fcf https://chromium.googlesource.com/webm/libwebm/+log/af81f26..6ab9fcf Change-Id: I9d56e1fbaba9b96404b4fbabefddc1a85b79c25d'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: long ContentEncoding::ParseCompressionEntry(long long start, long long size, IMkvReader* pReader, ContentCompression* compression) { assert(pReader); assert(compression); long long pos = start; const long long stop = start + size; bool valid = false; while (pos < stop) { long long id, size; const long status = ParseElementHeader(pReader, pos, stop, id, size); if (status < 0) // error return status; if (id == libwebm::kMkvContentCompAlgo) { long long algo = UnserializeUInt(pReader, pos, size); if (algo < 0) return E_FILE_FORMAT_INVALID; compression->algo = algo; valid = true; } else if (id == libwebm::kMkvContentCompSettings) { if (size <= 0) return E_FILE_FORMAT_INVALID; const size_t buflen = static_cast<size_t>(size); unsigned char* buf = SafeArrayAlloc<unsigned char>(1, buflen); if (buf == NULL) return -1; const int read_status = pReader->Read(pos, static_cast<long>(buflen), buf); if (read_status) { delete[] buf; return status; } compression->settings = buf; compression->settings_len = buflen; } pos += size; // consume payload if (pos > stop) return E_FILE_FORMAT_INVALID; } // ContentCompAlgo is mandatory if (!valid) return E_FILE_FORMAT_INVALID; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'update libwebm to libwebm-1.0.0.27-361-g81de00c 81de00c Check there is only one settings per ContentCompression 5623013 Fixes a double free in ContentEncoding 93b2ba0 mkvparser: quiet static analysis warnings Change-Id: Ieaa562ef2f10075381bd856388e6b29f97ca2746'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: exif_data_load_data (ExifData *data, const unsigned char *d_orig, unsigned int ds) { unsigned int l; ExifLong offset; ExifShort n; const unsigned char *d = d_orig; unsigned int len, fullds; if (!data || !data->priv || !d || !ds) return; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Parsing %i byte(s) EXIF data...\n", ds); /* * It can be that the data starts with the EXIF header. If it does * not, search the EXIF marker. */ if (ds < 6) { LOG_TOO_SMALL; return; } if (!memcmp (d, ExifHeader, 6)) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Found EXIF header at start."); } else { while (ds >= 3) { while (ds && (d[0] == 0xff)) { d++; ds--; } /* JPEG_MARKER_SOI */ if (ds && d[0] == JPEG_MARKER_SOI) { d++; ds--; continue; } /* JPEG_MARKER_APP1 */ if (ds && d[0] == JPEG_MARKER_APP1) break; /* Skip irrelevant APP markers. The branch for APP1 must come before this, otherwise this code block will cause APP1 to be skipped. This code path is only relevant for files that are nonconformant to the EXIF specification. For conformant files, the APP1 code path above will be taken. */ if (ds >= 3 && d[0] >= 0xe0 && d[0] <= 0xef) { /* JPEG_MARKER_APPn */ d++; ds--; l = (d[0] << 8) | d[1]; if (l > ds) return; d += l; ds -= l; continue; } /* Unknown marker or data. Give up. */ exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("EXIF marker not found.")); return; } if (ds < 3) { LOG_TOO_SMALL; return; } d++; ds--; len = (d[0] << 8) | d[1]; exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "We have to deal with %i byte(s) of EXIF data.", len); d += 2; ds -= 2; } /* * Verify the exif header * (offset 2, length 6). */ if (ds < 6) { LOG_TOO_SMALL; return; } if (memcmp (d, ExifHeader, 6)) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("EXIF header not found.")); return; } exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "Found EXIF header."); /* Sanity check the data length */ if (ds < 14) return; /* The JPEG APP1 section can be no longer than 64 KiB (including a 16-bit length), so cap the data length to protect against overflow in future offset calculations */ fullds = ds; if (ds > 0xfffe) ds = 0xfffe; /* Byte order (offset 6, length 2) */ if (!memcmp (d + 6, "II", 2)) data->priv->order = EXIF_BYTE_ORDER_INTEL; else if (!memcmp (d + 6, "MM", 2)) data->priv->order = EXIF_BYTE_ORDER_MOTOROLA; else { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", _("Unknown encoding.")); return; } /* Fixed value */ if (exif_get_short (d + 8, data->priv->order) != 0x002a) return; /* IFD 0 offset */ offset = exif_get_long (d + 10, data->priv->order); exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "IFD 0 at %i.", (int) offset); /* Sanity check the offset, being careful about overflow */ if (offset > ds || offset + 6 + 2 > ds) return; /* Parse the actual exif data (usually offset 14 from start) */ exif_data_load_data_content (data, EXIF_IFD_0, d + 6, ds - 6, offset, 0); /* IFD 1 offset */ n = exif_get_short (d + 6 + offset, data->priv->order); if (offset + 6 + 2 + 12 * n + 4 > ds) return; offset = exif_get_long (d + 6 + offset + 2 + 12 * n, data->priv->order); if (offset) { exif_log (data->priv->log, EXIF_LOG_CODE_DEBUG, "ExifData", "IFD 1 at %i.", (int) offset); /* Sanity check. */ if (offset > ds || offset + 6 > ds) { exif_log (data->priv->log, EXIF_LOG_CODE_CORRUPT_DATA, "ExifData", "Bogus offset of IFD1."); } else { exif_data_load_data_content (data, EXIF_IFD_1, d + 6, ds - 6, offset, 0); } } /* * If we got an EXIF_TAG_MAKER_NOTE, try to interpret it. Some * cameras use pointers in the maker note tag that point to the * space between IFDs. Here is the only place where we have access * to that data. */ interpret_maker_note(data, d, fullds); /* Fixup tags if requested */ if (data->priv->options & EXIF_DATA_OPTION_FOLLOW_SPECIFICATION) exif_data_fix (data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190', 'CWE-787'], 'message': 'fix CVE-2019-9278 avoid the use of unsafe integer overflow checking constructs (unsigned integer operations cannot overflow, so "u1 + u2 > u1" can be optimized away) check for the actual sizes, which should also handle the overflows document other places google patched, but do not seem relevant due to other restrictions fixes https://github.com/libexif/libexif/issues/26'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: 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; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Continuation of [e2bddcd4c55ba3cb]: Add another spot where it is necessary to abort early due to prior errors in sqlite3WindowRewrite(). FossilOrigin-Name: cba2a2a44cdf138a629109bb0ad088ed4ef67fc66bed3e0373554681a39615d2'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: __fdnlist(int fd, struct nlist *list) { struct nlist *p; Elf_Off symoff = 0, symstroff = 0; Elf_Word symsize = 0, symstrsize = 0; Elf_Sword cc, i; int nent = -1; int errsave; Elf_Sym sbuf[1024]; Elf_Sym *s; Elf_Ehdr ehdr; char *strtab = NULL; Elf_Shdr *shdr = NULL; Elf_Word shdr_size; struct stat st; /* Make sure obj is OK */ if (lseek(fd, (off_t)0, SEEK_SET) == -1 || read(fd, &ehdr, sizeof(Elf_Ehdr)) != sizeof(Elf_Ehdr) || !__elf_is_okay__(&ehdr) || fstat(fd, &st) < 0) return (-1); if (ehdr.e_shnum == 0 || ehdr.e_shentsize != sizeof(Elf_Shdr)) { errno = ERANGE; return (-1); } /* calculate section header table size */ shdr_size = ehdr.e_shentsize * ehdr.e_shnum; /* Make sure it's not too big to mmap */ if (shdr_size > SIZE_T_MAX || shdr_size > st.st_size) { errno = EFBIG; return (-1); } shdr = malloc((size_t)shdr_size); if (shdr == NULL) return (-1); /* Load section header table. */ if (pread(fd, shdr, (size_t)shdr_size, (off_t)ehdr.e_shoff) != (ssize_t)shdr_size) goto done; /* * Find the symbol table entry and it's corresponding * string table entry. Version 1.1 of the ABI states * that there is only one symbol table but that this * could change in the future. */ for (i = 0; i < ehdr.e_shnum; i++) { if (shdr[i].sh_type == SHT_SYMTAB) { if (shdr[i].sh_link >= ehdr.e_shnum) goto done; symoff = shdr[i].sh_offset; symsize = shdr[i].sh_size; symstroff = shdr[shdr[i].sh_link].sh_offset; symstrsize = shdr[shdr[i].sh_link].sh_size; break; } } /* Check for files too large to mmap. */ if (symstrsize > SIZE_T_MAX || symstrsize > st.st_size) { errno = EFBIG; goto done; } /* * Load string table into our address space. This gives us * an easy way to randomly access all the strings, without * making the memory allocation permanent as with malloc/free * (i.e., munmap will return it to the system). */ strtab = malloc((size_t)symstrsize); if (strtab == NULL) goto done; if (pread(fd, strtab, (size_t)symstrsize, (off_t)symstroff) != (ssize_t)symstrsize) goto done; /* * clean out any left-over information for all valid entries. * Type and value defined to be 0 if not found; historical * versions cleared other and desc as well. Also figure out * the largest string length so don't read any more of the * string table than we have to. * * XXX clearing anything other than n_type and n_value violates * the semantics given in the man page. */ nent = 0; for (p = list; !ISLAST(p); ++p) { p->n_type = 0; p->n_other = 0; p->n_desc = 0; p->n_value = 0; ++nent; } /* Don't process any further if object is stripped. */ if (symoff == 0) goto done; if (lseek(fd, (off_t) symoff, SEEK_SET) == -1) { nent = -1; goto done; } while (symsize > 0 && nent > 0) { cc = MIN(symsize, sizeof(sbuf)); if (read(fd, sbuf, cc) != cc) break; symsize -= cc; for (s = sbuf; cc > 0 && nent > 0; ++s, cc -= sizeof(*s)) { char *name; struct nlist *p; name = strtab + s->st_name; if (name[0] == '\0') continue; for (p = list; !ISLAST(p); p++) { if ((p->n_un.n_name[0] == '_' && strcmp(name, p->n_un.n_name+1) == 0) || strcmp(name, p->n_un.n_name) == 0) { elf_sym_to_nlist(p, s, shdr, ehdr.e_shnum); if (--nent <= 0) break; } } } } done: errsave = errno; free(strtab); free(shdr); errno = errsave; return (nent); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'nlist: Fix out-of-bounds read on strtab When doing a string comparison for a symbol name from the string table, we should make sure we do a bounded comparison, otherwise a non-NUL terminated string might make the code read out-of-bounds. Warned-by: coverity'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ImagingFliDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8* ptr; int framesize; int c, chunks, advance; int l, lines; int i, j, x = 0, y, ymax; /* If not even the chunk size is present, we'd better leave */ if (bytes < 4) return 0; /* We don't decode anything unless we have a full chunk in the input buffer (on the other hand, the Python part of the driver makes sure this is always the case) */ ptr = buf; framesize = I32(ptr); if (framesize < I32(ptr)) return 0; /* Make sure this is a frame chunk. The Python driver takes case of other chunk types. */ if (I16(ptr+4) != 0xF1FA) { state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } chunks = I16(ptr+6); ptr += 16; bytes -= 16; /* Process subchunks */ for (c = 0; c < chunks; c++) { UINT8* data; if (bytes < 10) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } data = ptr + 6; switch (I16(ptr+4)) { case 4: case 11: /* FLI COLOR chunk */ break; /* ignored; handled by Python code */ case 7: /* FLI SS2 chunk (word delta) */ lines = I16(data); data += 2; for (l = y = 0; l < lines && y < state->ysize; l++, y++) { UINT8* buf = (UINT8*) im->image[y]; int p, packets; packets = I16(data); data += 2; while (packets & 0x8000) { /* flag word */ if (packets & 0x4000) { y += 65536 - packets; /* skip lines */ if (y >= state->ysize) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } buf = (UINT8*) im->image[y]; } else { /* store last byte (used if line width is odd) */ buf[state->xsize-1] = (UINT8) packets; } packets = I16(data); data += 2; } for (p = x = 0; p < packets; p++) { x += data[0]; /* pixel skip */ if (data[1] >= 128) { i = 256-data[1]; /* run */ if (x + i + i > state->xsize) break; for (j = 0; j < i; j++) { buf[x++] = data[2]; buf[x++] = data[3]; } data += 2 + 2; } else { i = 2 * (int) data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(buf + x, data + 2, i); data += 2 + i; x += i; } } if (p < packets) break; /* didn't process all packets */ } if (l < lines) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 12: /* FLI LC chunk (byte delta) */ y = I16(data); ymax = y + I16(data+2); data += 4; for (; y < ymax && y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; int p, packets = *data++; for (p = x = 0; p < packets; p++, x += i) { x += data[0]; /* skip pixels */ if (data[1] & 0x80) { i = 256-data[1]; /* run */ if (x + i > state->xsize) break; memset(out + x, data[2], i); data += 3; } else { i = data[1]; /* chunk */ if (x + i > state->xsize) break; memcpy(out + x, data + 2, i); data += i + 2; } } if (p < packets) break; /* didn't process all packets */ } if (y < ymax) { /* didn't process all lines */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } break; case 13: /* FLI BLACK chunk */ for (y = 0; y < state->ysize; y++) memset(im->image[y], 0, state->xsize); break; case 15: /* FLI BRUN chunk */ for (y = 0; y < state->ysize; y++) { UINT8* out = (UINT8*) im->image[y]; data += 1; /* ignore packetcount byte */ for (x = 0; x < state->xsize; x += i) { if (data[0] & 0x80) { i = 256 - data[0]; if (x + i > state->xsize) break; /* safety first */ memcpy(out + x, data + 1, i); data += i + 1; } else { i = data[0]; if (x + i > state->xsize) break; /* safety first */ memset(out + x, data[1], i); data += 2; } } if (x != state->xsize) { /* didn't unpack whole line */ state->errcode = IMAGING_CODEC_OVERRUN; return -1; } } break; case 16: /* COPY chunk */ for (y = 0; y < state->ysize; y++) { UINT8* buf = (UINT8*) im->image[y]; memcpy(buf, data, state->xsize); data += state->xsize; } break; case 18: /* PSTAMP chunk */ break; /* ignored */ default: /* unknown chunk */ /* printf("unknown FLI/FLC chunk: %d\n", I16(ptr+4)); */ state->errcode = IMAGING_CODEC_UNKNOWN; return -1; } advance = I32(ptr); ptr += advance; bytes -= advance; } return -1; /* end of frame */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125', 'CWE-787'], 'message': 'Catch FLI buffer overrun'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ImagingSgiRleDecode(Imaging im, ImagingCodecState state, UINT8* buf, Py_ssize_t bytes) { UINT8 *ptr; SGISTATE *c; int err = 0; /* Get all data from File descriptor */ c = (SGISTATE*)state->context; _imaging_seek_pyFd(state->fd, 0L, SEEK_END); c->bufsize = _imaging_tell_pyFd(state->fd); c->bufsize -= SGI_HEADER_SIZE; ptr = malloc(sizeof(UINT8) * c->bufsize); if (!ptr) { return IMAGING_CODEC_MEMORY; } _imaging_seek_pyFd(state->fd, SGI_HEADER_SIZE, SEEK_SET); _imaging_read_pyFd(state->fd, (char*)ptr, c->bufsize); /* decoder initialization */ state->count = 0; state->y = 0; if (state->ystep < 0) { state->y = im->ysize - 1; } else { state->ystep = 1; } if (im->xsize > INT_MAX / im->bands || im->ysize > INT_MAX / im->bands) { err = IMAGING_CODEC_MEMORY; goto sgi_finish_decode; } /* Allocate memory for RLE tables and rows */ free(state->buffer); state->buffer = NULL; /* malloc overflow check above */ state->buffer = calloc(im->xsize * im->bands, sizeof(UINT8) * 2); c->tablen = im->bands * im->ysize; c->starttab = calloc(c->tablen, sizeof(UINT32)); c->lengthtab = calloc(c->tablen, sizeof(UINT32)); if (!state->buffer || !c->starttab || !c->lengthtab) { err = IMAGING_CODEC_MEMORY; goto sgi_finish_decode; } /* populate offsets table */ for (c->tabindex = 0, c->bufindex = 0; c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4) read4B(&c->starttab[c->tabindex], &ptr[c->bufindex]); /* populate lengths table */ for (c->tabindex = 0, c->bufindex = c->tablen * sizeof(UINT32); c->tabindex < c->tablen; c->tabindex++, c->bufindex+=4) read4B(&c->lengthtab[c->tabindex], &ptr[c->bufindex]); state->count += c->tablen * sizeof(UINT32) * 2; /* read compressed rows */ for (c->rowno = 0; c->rowno < im->ysize; c->rowno++, state->y += state->ystep) { for (c->channo = 0; c->channo < im->bands; c->channo++) { c->rleoffset = c->starttab[c->rowno + c->channo * im->ysize]; c->rlelength = c->lengthtab[c->rowno + c->channo * im->ysize]; c->rleoffset -= SGI_HEADER_SIZE; if (c->rleoffset + c->rlelength > c->bufsize) { state->errcode = IMAGING_CODEC_OVERRUN; return -1; } /* row decompression */ if (c->bpc ==1) { if(expandrow(&state->buffer[c->channo], &ptr[c->rleoffset], c->rlelength, im->bands)) goto sgi_finish_decode; } else { if(expandrow2(&state->buffer[c->channo * 2], &ptr[c->rleoffset], c->rlelength, im->bands)) goto sgi_finish_decode; } state->count += c->rlelength; } /* store decompressed data in image */ state->shuffle((UINT8*)im->image[state->y], state->buffer, im->xsize); } c->bufsize++; sgi_finish_decode: ; free(c->starttab); free(c->lengthtab); free(ptr); if (err != 0){ return err; } return state->count - c->bufsize; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Catch SGI buffer overruns'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int expandrow2(UINT8* dest, const UINT8* src, int n, int z) { UINT8 pixel, count; for (;n > 0; n--) { pixel = src[1]; src+=2; if (n == 1 && pixel != 0) return n; count = pixel & RLE_MAX_RUN; if (!count) return count; if (pixel & RLE_COPY_FLAG) { while(count--) { memcpy(dest, src, 2); src += 2; dest += z * 2; } } else { while (count--) { memcpy(dest, src, 2); dest += z * 2; } src+=2; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-120', 'CWE-787'], 'message': 'Catch SGI buffer overruns'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int ImagingLibTiffDecode(Imaging im, ImagingCodecState state, UINT8* buffer, int bytes) { TIFFSTATE *clientstate = (TIFFSTATE *)state->context; char *filename = "tempfile.tif"; char *mode = "r"; TIFF *tiff; tsize_t size; /* buffer is the encoded file, bytes is the length of the encoded file */ /* it all ends up in state->buffer, which is a uint8* from Imaging.h */ TRACE(("in decoder: bytes %d\n", bytes)); TRACE(("State: count %d, state %d, x %d, y %d, ystep %d\n", state->count, state->state, state->x, state->y, state->ystep)); TRACE(("State: xsize %d, ysize %d, xoff %d, yoff %d \n", state->xsize, state->ysize, state->xoff, state->yoff)); TRACE(("State: bits %d, bytes %d \n", state->bits, state->bytes)); TRACE(("Buffer: %p: %c%c%c%c\n", buffer, (char)buffer[0], (char)buffer[1],(char)buffer[2], (char)buffer[3])); TRACE(("State->Buffer: %c%c%c%c\n", (char)state->buffer[0], (char)state->buffer[1],(char)state->buffer[2], (char)state->buffer[3])); TRACE(("Image: mode %s, type %d, bands: %d, xsize %d, ysize %d \n", im->mode, im->type, im->bands, im->xsize, im->ysize)); TRACE(("Image: image8 %p, image32 %p, image %p, block %p \n", im->image8, im->image32, im->image, im->block)); TRACE(("Image: pixelsize: %d, linesize %d \n", im->pixelsize, im->linesize)); dump_state(clientstate); clientstate->size = bytes; clientstate->eof = clientstate->size; clientstate->loc = 0; clientstate->data = (tdata_t)buffer; clientstate->flrealloc = 0; dump_state(clientstate); TIFFSetWarningHandler(NULL); TIFFSetWarningHandlerExt(NULL); if (clientstate->fp) { TRACE(("Opening using fd: %d\n",clientstate->fp)); lseek(clientstate->fp,0,SEEK_SET); // Sometimes, I get it set to the end. tiff = TIFFFdOpen(clientstate->fp, filename, mode); } else { TRACE(("Opening from string\n")); tiff = TIFFClientOpen(filename, mode, (thandle_t) clientstate, _tiffReadProc, _tiffWriteProc, _tiffSeekProc, _tiffCloseProc, _tiffSizeProc, _tiffMapProc, _tiffUnmapProc); } if (!tiff){ TRACE(("Error, didn't get the tiff\n")); state->errcode = IMAGING_CODEC_BROKEN; return -1; } if (clientstate->ifd){ int rv; uint32 ifdoffset = clientstate->ifd; TRACE(("reading tiff ifd %u\n", ifdoffset)); rv = TIFFSetSubDirectory(tiff, ifdoffset); if (!rv){ TRACE(("error in TIFFSetSubDirectory")); return -1; } } size = TIFFScanlineSize(tiff); TRACE(("ScanlineSize: %d \n", size)); if (size > state->bytes) { TRACE(("Error, scanline size > buffer size\n")); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } // Have to do this row by row and shove stuff into the buffer that way, // with shuffle. (or, just alloc a buffer myself, then figure out how to get it // back in. Can't use read encoded stripe. // This thing pretty much requires that I have the whole image in one shot. // Perhaps a stub version would work better??? while(state->y < state->ysize){ if (TIFFReadScanline(tiff, (tdata_t)state->buffer, (uint32)state->y, 0) == -1) { TRACE(("Decode Error, row %d\n", state->y)); state->errcode = IMAGING_CODEC_BROKEN; TIFFClose(tiff); return -1; } /* TRACE(("Decoded row %d \n", state->y)); */ state->shuffle((UINT8*) im->image[state->y + state->yoff] + state->xoff * im->pixelsize, state->buffer, state->xsize); state->y++; } TIFFClose(tiff); TRACE(("Done Decoding, Returning \n")); // Returning -1 here to force ImageFile.load to break, rather than // even think about looping back around. return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Adding support to reading tiled and YcbCr jpegs tiffs through libtiff'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int sta_info_move_state(struct sta_info *sta, enum ieee80211_sta_state new_state) { might_sleep(); if (sta->sta_state == new_state) return 0; /* check allowed transitions first */ switch (new_state) { case IEEE80211_STA_NONE: if (sta->sta_state != IEEE80211_STA_AUTH) return -EINVAL; break; case IEEE80211_STA_AUTH: if (sta->sta_state != IEEE80211_STA_NONE && sta->sta_state != IEEE80211_STA_ASSOC) return -EINVAL; break; case IEEE80211_STA_ASSOC: if (sta->sta_state != IEEE80211_STA_AUTH && sta->sta_state != IEEE80211_STA_AUTHORIZED) return -EINVAL; break; case IEEE80211_STA_AUTHORIZED: if (sta->sta_state != IEEE80211_STA_ASSOC) return -EINVAL; break; default: WARN(1, "invalid state %d", new_state); return -EINVAL; } sta_dbg(sta->sdata, "moving STA %pM to state %d\n", sta->sta.addr, new_state); /* * notify the driver before the actual changes so it can * fail the transition */ if (test_sta_flag(sta, WLAN_STA_INSERTED)) { int err = drv_sta_state(sta->local, sta->sdata, sta, sta->sta_state, new_state); if (err) return err; } /* reflect the change in all state variables */ switch (new_state) { case IEEE80211_STA_NONE: if (sta->sta_state == IEEE80211_STA_AUTH) clear_bit(WLAN_STA_AUTH, &sta->_flags); break; case IEEE80211_STA_AUTH: if (sta->sta_state == IEEE80211_STA_NONE) { set_bit(WLAN_STA_AUTH, &sta->_flags); } else if (sta->sta_state == IEEE80211_STA_ASSOC) { clear_bit(WLAN_STA_ASSOC, &sta->_flags); ieee80211_recalc_min_chandef(sta->sdata); if (!sta->sta.support_p2p_ps) ieee80211_recalc_p2p_go_ps_allowed(sta->sdata); } break; case IEEE80211_STA_ASSOC: if (sta->sta_state == IEEE80211_STA_AUTH) { set_bit(WLAN_STA_ASSOC, &sta->_flags); ieee80211_recalc_min_chandef(sta->sdata); if (!sta->sta.support_p2p_ps) ieee80211_recalc_p2p_go_ps_allowed(sta->sdata); } else if (sta->sta_state == IEEE80211_STA_AUTHORIZED) { ieee80211_vif_dec_num_mcast(sta->sdata); clear_bit(WLAN_STA_AUTHORIZED, &sta->_flags); ieee80211_clear_fast_xmit(sta); ieee80211_clear_fast_rx(sta); } break; case IEEE80211_STA_AUTHORIZED: if (sta->sta_state == IEEE80211_STA_ASSOC) { ieee80211_vif_inc_num_mcast(sta->sdata); set_bit(WLAN_STA_AUTHORIZED, &sta->_flags); ieee80211_check_fast_xmit(sta); ieee80211_check_fast_rx(sta); } break; default: break; } sta->sta_state = new_state; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'mac80211: Do not send Layer 2 Update frame before authorization The Layer 2 Update frame is used to update bridges when a station roams to another AP even if that STA does not transmit any frames after the reassociation. This behavior was described in IEEE Std 802.11F-2003 as something that would happen based on MLME-ASSOCIATE.indication, i.e., before completing 4-way handshake. However, this IEEE trial-use recommended practice document was published before RSN (IEEE Std 802.11i-2004) and as such, did not consider RSN use cases. Furthermore, IEEE Std 802.11F-2003 was withdrawn in 2006 and as such, has not been maintained amd should not be used anymore. Sending out the Layer 2 Update frame immediately after association is fine for open networks (and also when using SAE, FT protocol, or FILS authentication when the station is actually authenticated by the time association completes). However, it is not appropriate for cases where RSN is used with PSK or EAP authentication since the station is actually fully authenticated only once the 4-way handshake completes after authentication and attackers might be able to use the unauthenticated triggering of Layer 2 Update frame transmission to disrupt bridge behavior. Fix this by postponing transmission of the Layer 2 Update frame from station entry addition to the point when the station entry is marked authorized. Similarly, send out the VLAN binding update only if the STA entry has already been authorized. Signed-off-by: Jouni Malinen <jouni@codeaurora.org> Reviewed-by: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int ieee80211_change_station(struct wiphy *wiphy, struct net_device *dev, const u8 *mac, struct station_parameters *params) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); struct ieee80211_local *local = wiphy_priv(wiphy); struct sta_info *sta; struct ieee80211_sub_if_data *vlansdata; enum cfg80211_station_type statype; int err; mutex_lock(&local->sta_mtx); sta = sta_info_get_bss(sdata, mac); if (!sta) { err = -ENOENT; goto out_err; } switch (sdata->vif.type) { case NL80211_IFTYPE_MESH_POINT: if (sdata->u.mesh.user_mpm) statype = CFG80211_STA_MESH_PEER_USER; else statype = CFG80211_STA_MESH_PEER_KERNEL; break; case NL80211_IFTYPE_ADHOC: statype = CFG80211_STA_IBSS; break; case NL80211_IFTYPE_STATION: if (!test_sta_flag(sta, WLAN_STA_TDLS_PEER)) { statype = CFG80211_STA_AP_STA; break; } if (test_sta_flag(sta, WLAN_STA_AUTHORIZED)) statype = CFG80211_STA_TDLS_PEER_ACTIVE; else statype = CFG80211_STA_TDLS_PEER_SETUP; break; case NL80211_IFTYPE_AP: case NL80211_IFTYPE_AP_VLAN: if (test_sta_flag(sta, WLAN_STA_ASSOC)) statype = CFG80211_STA_AP_CLIENT; else statype = CFG80211_STA_AP_CLIENT_UNASSOC; break; default: err = -EOPNOTSUPP; goto out_err; } err = cfg80211_check_station_change(wiphy, params, statype); if (err) goto out_err; if (params->vlan && params->vlan != sta->sdata->dev) { vlansdata = IEEE80211_DEV_TO_SUB_IF(params->vlan); if (params->vlan->ieee80211_ptr->use_4addr) { if (vlansdata->u.vlan.sta) { err = -EBUSY; goto out_err; } rcu_assign_pointer(vlansdata->u.vlan.sta, sta); __ieee80211_check_fast_rx_iface(vlansdata); } if (sta->sdata->vif.type == NL80211_IFTYPE_AP_VLAN && sta->sdata->u.vlan.sta) RCU_INIT_POINTER(sta->sdata->u.vlan.sta, NULL); if (test_sta_flag(sta, WLAN_STA_AUTHORIZED)) ieee80211_vif_dec_num_mcast(sta->sdata); sta->sdata = vlansdata; ieee80211_check_fast_xmit(sta); if (test_sta_flag(sta, WLAN_STA_AUTHORIZED)) ieee80211_vif_inc_num_mcast(sta->sdata); cfg80211_send_layer2_update(sta->sdata->dev, sta->sta.addr); } err = sta_apply_parameters(local, sta, params); if (err) goto out_err; mutex_unlock(&local->sta_mtx); if ((sdata->vif.type == NL80211_IFTYPE_AP || sdata->vif.type == NL80211_IFTYPE_AP_VLAN) && sta->known_smps_mode != sta->sdata->bss->req_smps && test_sta_flag(sta, WLAN_STA_AUTHORIZED) && sta_info_tx_streams(sta) != 1) { ht_dbg(sta->sdata, "%pM just authorized and MIMO capable - update SMPS\n", sta->sta.addr); ieee80211_send_smps_action(sta->sdata, sta->sdata->bss->req_smps, sta->sta.addr, sta->sdata->vif.bss_conf.bssid); } if (sdata->vif.type == NL80211_IFTYPE_STATION && params->sta_flags_mask & BIT(NL80211_STA_FLAG_AUTHORIZED)) { ieee80211_recalc_ps(local); ieee80211_recalc_ps_vif(sdata); } return 0; out_err: mutex_unlock(&local->sta_mtx); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-287'], 'message': 'mac80211: Do not send Layer 2 Update frame before authorization The Layer 2 Update frame is used to update bridges when a station roams to another AP even if that STA does not transmit any frames after the reassociation. This behavior was described in IEEE Std 802.11F-2003 as something that would happen based on MLME-ASSOCIATE.indication, i.e., before completing 4-way handshake. However, this IEEE trial-use recommended practice document was published before RSN (IEEE Std 802.11i-2004) and as such, did not consider RSN use cases. Furthermore, IEEE Std 802.11F-2003 was withdrawn in 2006 and as such, has not been maintained amd should not be used anymore. Sending out the Layer 2 Update frame immediately after association is fine for open networks (and also when using SAE, FT protocol, or FILS authentication when the station is actually authenticated by the time association completes). However, it is not appropriate for cases where RSN is used with PSK or EAP authentication since the station is actually fully authenticated only once the 4-way handshake completes after authentication and attackers might be able to use the unauthenticated triggering of Layer 2 Update frame transmission to disrupt bridge behavior. Fix this by postponing transmission of the Layer 2 Update frame from station entry addition to the point when the station entry is marked authorized. Similarly, send out the VLAN binding update only if the STA entry has already been authorized. Signed-off-by: Jouni Malinen <jouni@codeaurora.org> Reviewed-by: Johannes Berg <johannes@sipsolutions.net> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: bool SFD_GetFontMetaData( FILE *sfd, char *tok, SplineFont *sf, SFD_GetFontMetaDataData* d ) { int ch; int i; KernClass* kc = 0; int old; char val[2000]; // This allows us to assume we can dereference d // at all times static SFD_GetFontMetaDataData my_static_d; static int my_static_d_is_virgin = 1; if( !d ) { if( my_static_d_is_virgin ) { my_static_d_is_virgin = 0; SFD_GetFontMetaDataData_Init( &my_static_d ); } d = &my_static_d; } if ( strmatch(tok,"FontName:")==0 ) { geteol(sfd,val); sf->fontname = copy(val); } else if ( strmatch(tok,"FullName:")==0 ) { geteol(sfd,val); sf->fullname = copy(val); } else if ( strmatch(tok,"FamilyName:")==0 ) { geteol(sfd,val); sf->familyname = copy(val); } else if ( strmatch(tok,"DefaultBaseFilename:")==0 ) { geteol(sfd,val); sf->defbasefilename = copy(val); } else if ( strmatch(tok,"Weight:")==0 ) { getprotectedname(sfd,val); sf->weight = copy(val); } else if ( strmatch(tok,"Copyright:")==0 ) { sf->copyright = getquotedeol(sfd); } else if ( strmatch(tok,"Comments:")==0 ) { char *temp = getquotedeol(sfd); sf->comments = latin1_2_utf8_copy(temp); free(temp); } else if ( strmatch(tok,"UComments:")==0 ) { sf->comments = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,"FontLog:")==0 ) { sf->fontlog = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,"Version:")==0 ) { geteol(sfd,val); sf->version = copy(val); } else if ( strmatch(tok,"StyleMapFamilyName:")==0 ) { sf->styleMapFamilyName = SFDReadUTF7Str(sfd); } /* Legacy attribute for StyleMapFamilyName. Deprecated. */ else if ( strmatch(tok,"OS2FamilyName:")==0 ) { if (sf->styleMapFamilyName == NULL) sf->styleMapFamilyName = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,"FONDName:")==0 ) { geteol(sfd,val); sf->fondname = copy(val); } else if ( strmatch(tok,"ItalicAngle:")==0 ) { getreal(sfd,&sf->italicangle); } else if ( strmatch(tok,"StrokeWidth:")==0 ) { getreal(sfd,&sf->strokewidth); } else if ( strmatch(tok,"UnderlinePosition:")==0 ) { getreal(sfd,&sf->upos); } else if ( strmatch(tok,"UnderlineWidth:")==0 ) { getreal(sfd,&sf->uwidth); } else if ( strmatch(tok,"ModificationTime:")==0 ) { getlonglong(sfd,&sf->modificationtime); } else if ( strmatch(tok,"CreationTime:")==0 ) { getlonglong(sfd,&sf->creationtime); d->hadtimes = true; } else if ( strmatch(tok,"PfmFamily:")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.pfmfamily = temp; sf->pfminfo.pfmset = true; } else if ( strmatch(tok,"LangName:")==0 ) { sf->names = SFDGetLangName(sfd,sf->names); } else if ( strmatch(tok,"GaspTable:")==0 ) { SFDGetGasp(sfd,sf); } else if ( strmatch(tok,"DesignSize:")==0 ) { SFDGetDesignSize(sfd,sf); } else if ( strmatch(tok,"OtfFeatName:")==0 ) { SFDGetOtfFeatName(sfd,sf); } else if ( strmatch(tok,"PfmWeight:")==0 || strmatch(tok,"TTFWeight:")==0 ) { getsint(sfd,&sf->pfminfo.weight); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,"TTFWidth:")==0 ) { getsint(sfd,&sf->pfminfo.width); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,"Panose:")==0 ) { int temp,i; for ( i=0; i<10; ++i ) { getint(sfd,&temp); sf->pfminfo.panose[i] = temp; } sf->pfminfo.panose_set = true; } else if ( strmatch(tok,"LineGap:")==0 ) { getsint(sfd,&sf->pfminfo.linegap); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,"VLineGap:")==0 ) { getsint(sfd,&sf->pfminfo.vlinegap); sf->pfminfo.pfmset = true; } else if ( strmatch(tok,"HheadAscent:")==0 ) { getsint(sfd,&sf->pfminfo.hhead_ascent); } else if ( strmatch(tok,"HheadAOffset:")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.hheadascent_add = temp; } else if ( strmatch(tok,"HheadDescent:")==0 ) { getsint(sfd,&sf->pfminfo.hhead_descent); } else if ( strmatch(tok,"HheadDOffset:")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp; } else if ( strmatch(tok,"OS2TypoLinegap:")==0 ) { getsint(sfd,&sf->pfminfo.os2_typolinegap); } else if ( strmatch(tok,"OS2TypoAscent:")==0 ) { getsint(sfd,&sf->pfminfo.os2_typoascent); } else if ( strmatch(tok,"OS2TypoAOffset:")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.typoascent_add = temp; } else if ( strmatch(tok,"OS2TypoDescent:")==0 ) { getsint(sfd,&sf->pfminfo.os2_typodescent); } else if ( strmatch(tok,"OS2TypoDOffset:")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.typodescent_add = temp; } else if ( strmatch(tok,"OS2WinAscent:")==0 ) { getsint(sfd,&sf->pfminfo.os2_winascent); } else if ( strmatch(tok,"OS2WinDescent:")==0 ) { getsint(sfd,&sf->pfminfo.os2_windescent); } else if ( strmatch(tok,"OS2WinAOffset:")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.winascent_add = temp; } else if ( strmatch(tok,"OS2WinDOffset:")==0 ) { int temp; getint(sfd,&temp); sf->pfminfo.windescent_add = temp; } else if ( strmatch(tok,"HHeadAscent:")==0 ) { // DUPLICATE OF ABOVE getsint(sfd,&sf->pfminfo.hhead_ascent); } else if ( strmatch(tok,"HHeadDescent:")==0 ) { // DUPLICATE OF ABOVE getsint(sfd,&sf->pfminfo.hhead_descent); } else if ( strmatch(tok,"HHeadAOffset:")==0 ) { // DUPLICATE OF ABOVE int temp; getint(sfd,&temp); sf->pfminfo.hheadascent_add = temp; } else if ( strmatch(tok,"HHeadDOffset:")==0 ) { // DUPLICATE OF ABOVE int temp; getint(sfd,&temp); sf->pfminfo.hheaddescent_add = temp; } else if ( strmatch(tok,"MacStyle:")==0 ) { getsint(sfd,&sf->macstyle); } else if ( strmatch(tok,"OS2SubXSize:")==0 ) { getsint(sfd,&sf->pfminfo.os2_subxsize); sf->pfminfo.subsuper_set = true; } else if ( strmatch(tok,"OS2SubYSize:")==0 ) { getsint(sfd,&sf->pfminfo.os2_subysize); } else if ( strmatch(tok,"OS2SubXOff:")==0 ) { getsint(sfd,&sf->pfminfo.os2_subxoff); } else if ( strmatch(tok,"OS2SubYOff:")==0 ) { getsint(sfd,&sf->pfminfo.os2_subyoff); } else if ( strmatch(tok,"OS2SupXSize:")==0 ) { getsint(sfd,&sf->pfminfo.os2_supxsize); } else if ( strmatch(tok,"OS2SupYSize:")==0 ) { getsint(sfd,&sf->pfminfo.os2_supysize); } else if ( strmatch(tok,"OS2SupXOff:")==0 ) { getsint(sfd,&sf->pfminfo.os2_supxoff); } else if ( strmatch(tok,"OS2SupYOff:")==0 ) { getsint(sfd,&sf->pfminfo.os2_supyoff); } else if ( strmatch(tok,"OS2StrikeYSize:")==0 ) { getsint(sfd,&sf->pfminfo.os2_strikeysize); } else if ( strmatch(tok,"OS2StrikeYPos:")==0 ) { getsint(sfd,&sf->pfminfo.os2_strikeypos); } else if ( strmatch(tok,"OS2CapHeight:")==0 ) { getsint(sfd,&sf->pfminfo.os2_capheight); } else if ( strmatch(tok,"OS2XHeight:")==0 ) { getsint(sfd,&sf->pfminfo.os2_xheight); } else if ( strmatch(tok,"OS2FamilyClass:")==0 ) { getsint(sfd,&sf->pfminfo.os2_family_class); } else if ( strmatch(tok,"OS2Vendor:")==0 ) { while ( isspace(nlgetc(sfd))); sf->pfminfo.os2_vendor[0] = nlgetc(sfd); sf->pfminfo.os2_vendor[1] = nlgetc(sfd); sf->pfminfo.os2_vendor[2] = nlgetc(sfd); sf->pfminfo.os2_vendor[3] = nlgetc(sfd); (void) nlgetc(sfd); } else if ( strmatch(tok,"OS2CodePages:")==0 ) { gethexints(sfd,sf->pfminfo.codepages,2); sf->pfminfo.hascodepages = true; } else if ( strmatch(tok,"OS2UnicodeRanges:")==0 ) { gethexints(sfd,sf->pfminfo.unicoderanges,4); sf->pfminfo.hasunicoderanges = true; } else if ( strmatch(tok,"TopEncoding:")==0 ) { /* Obsolete */ getint(sfd,&sf->top_enc); } else if ( strmatch(tok,"Ascent:")==0 ) { getint(sfd,&sf->ascent); } else if ( strmatch(tok,"Descent:")==0 ) { getint(sfd,&sf->descent); } else if ( strmatch(tok,"InvalidEm:")==0 ) { getint(sfd,&sf->invalidem); } else if ( strmatch(tok,"woffMajor:")==0 ) { getint(sfd,&sf->woffMajor); } else if ( strmatch(tok,"woffMinor:")==0 ) { getint(sfd,&sf->woffMinor); } else if ( strmatch(tok,"woffMetadata:")==0 ) { sf->woffMetadata = SFDReadUTF7Str(sfd); } else if ( strmatch(tok,"UFOAscent:")==0 ) { getreal(sfd,&sf->ufo_ascent); } else if ( strmatch(tok,"UFODescent:")==0 ) { getreal(sfd,&sf->ufo_descent); } else if ( strmatch(tok,"sfntRevision:")==0 ) { gethex(sfd,(uint32 *)&sf->sfntRevision); } else if ( strmatch(tok,"LayerCount:")==0 ) { d->had_layer_cnt = true; getint(sfd,&sf->layer_cnt); if ( sf->layer_cnt>2 ) { sf->layers = realloc(sf->layers,sf->layer_cnt*sizeof(LayerInfo)); memset(sf->layers+2,0,(sf->layer_cnt-2)*sizeof(LayerInfo)); } } else if ( strmatch(tok,"Layer:")==0 ) { // TODO: Read the U. F. O. path. int layer, o2, bk; getint(sfd,&layer); if ( layer>=sf->layer_cnt ) { sf->layers = realloc(sf->layers,(layer+1)*sizeof(LayerInfo)); memset(sf->layers+sf->layer_cnt,0,((layer+1)-sf->layer_cnt)*sizeof(LayerInfo)); sf->layer_cnt = layer+1; } getint(sfd,&o2); sf->layers[layer].order2 = o2; sf->layers[layer].background = layer==ly_back; /* Used briefly, now background is after layer name */ while ( (ch=nlgetc(sfd))==' ' ); ungetc(ch,sfd); if ( ch!='"' ) { getint(sfd,&bk); sf->layers[layer].background = bk; } /* end of section for obsolete format */ sf->layers[layer].name = SFDReadUTF7Str(sfd); while ( (ch=nlgetc(sfd))==' ' ); ungetc(ch,sfd); if ( ch!='\n' ) { getint(sfd,&bk); sf->layers[layer].background = bk; } while ( (ch=nlgetc(sfd))==' ' ); ungetc(ch,sfd); if ( ch!='\n' ) { sf->layers[layer].ufo_path = SFDReadUTF7Str(sfd); } } else if ( strmatch(tok,"PreferredKerning:")==0 ) { int temp; getint(sfd,&temp); sf->preferred_kerning = temp; } else if ( strmatch(tok,"StrokedFont:")==0 ) { int temp; getint(sfd,&temp); sf->strokedfont = temp; } else if ( strmatch(tok,"MultiLayer:")==0 ) { int temp; getint(sfd,&temp); sf->multilayer = temp; } else if ( strmatch(tok,"NeedsXUIDChange:")==0 ) { int temp; getint(sfd,&temp); sf->changed_since_xuidchanged = temp; } else if ( strmatch(tok,"VerticalOrigin:")==0 ) { // this doesn't seem to be written ever. int temp; getint(sfd,&temp); sf->hasvmetrics = true; } else if ( strmatch(tok,"HasVMetrics:")==0 ) { int temp; getint(sfd,&temp); sf->hasvmetrics = temp; } else if ( strmatch(tok,"Justify:")==0 ) { SFDParseJustify(sfd,sf,tok); } else if ( strmatch(tok,"BaseHoriz:")==0 ) { sf->horiz_base = SFDParseBase(sfd); d->last_base = sf->horiz_base; d->last_base_script = NULL; } else if ( strmatch(tok,"BaseVert:")==0 ) { sf->vert_base = SFDParseBase(sfd); d->last_base = sf->vert_base; d->last_base_script = NULL; } else if ( strmatch(tok,"BaseScript:")==0 ) { struct basescript *bs = SFDParseBaseScript(sfd,d->last_base); if ( d->last_base==NULL ) { BaseScriptFree(bs); bs = NULL; } else if ( d->last_base_script!=NULL ) d->last_base_script->next = bs; else d->last_base->scripts = bs; d->last_base_script = bs; } else if ( strmatch(tok,"StyleMap:")==0 ) { gethex(sfd,(uint32 *)&sf->pfminfo.stylemap); } /* Legacy attribute for StyleMap. Deprecated. */ else if ( strmatch(tok,"OS2StyleName:")==0 ) { char* sname = SFDReadUTF7Str(sfd); if (sf->pfminfo.stylemap == -1) { if (strcmp(sname,"bold italic")==0) sf->pfminfo.stylemap = 0x21; else if (strcmp(sname,"bold")==0) sf->pfminfo.stylemap = 0x20; else if (strcmp(sname,"italic")==0) sf->pfminfo.stylemap = 0x01; else if (strcmp(sname,"regular")==0) sf->pfminfo.stylemap = 0x40; } free(sname); } else if ( strmatch(tok,"FSType:")==0 ) { getsint(sfd,&sf->pfminfo.fstype); } else if ( strmatch(tok,"OS2Version:")==0 ) { getsint(sfd,&sf->os2_version); } else if ( strmatch(tok,"OS2_WeightWidthSlopeOnly:")==0 ) { int temp; getint(sfd,&temp); sf->weight_width_slope_only = temp; } else if ( strmatch(tok,"OS2_UseTypoMetrics:")==0 ) { int temp; getint(sfd,&temp); sf->use_typo_metrics = temp; } else if ( strmatch(tok,"UseUniqueID:")==0 ) { int temp; getint(sfd,&temp); sf->use_uniqueid = temp; } else if ( strmatch(tok,"UseXUID:")==0 ) { int temp; getint(sfd,&temp); sf->use_xuid = temp; } else if ( strmatch(tok,"UniqueID:")==0 ) { getint(sfd,&sf->uniqueid); } else if ( strmatch(tok,"XUID:")==0 ) { geteol(sfd,tok); sf->xuid = copy(tok); } else if ( strmatch(tok,"Lookup:")==0 ) { OTLookup *otl; int temp; if ( sf->sfd_version<2 ) { IError( "Lookups should not happen in version 1 sfd files." ); exit(1); } otl = chunkalloc(sizeof(OTLookup)); getint(sfd,&temp); otl->lookup_type = temp; getint(sfd,&temp); otl->lookup_flags = temp; getint(sfd,&temp); otl->store_in_afm = temp; otl->lookup_name = SFDReadUTF7Str(sfd); if ( otl->lookup_type<gpos_single ) { if ( d->lastsotl==NULL ) sf->gsub_lookups = otl; else d->lastsotl->next = otl; d->lastsotl = otl; } else { if ( d->lastpotl==NULL ) sf->gpos_lookups = otl; else d->lastpotl->next = otl; d->lastpotl = otl; } SFDParseLookup(sfd,otl); } else if ( strmatch(tok,"MarkAttachClasses:")==0 ) { getint(sfd,&sf->mark_class_cnt); sf->mark_classes = malloc(sf->mark_class_cnt*sizeof(char *)); sf->mark_class_names = malloc(sf->mark_class_cnt*sizeof(char *)); sf->mark_classes[0] = NULL; sf->mark_class_names[0] = NULL; for ( i=1; i<sf->mark_class_cnt; ++i ) { /* Class 0 is unused */ int temp; while ( (temp=nlgetc(sfd))=='\n' || temp=='\r' ); ungetc(temp,sfd); sf->mark_class_names[i] = SFDReadUTF7Str(sfd); getint(sfd,&temp); sf->mark_classes[i] = malloc(temp+1); sf->mark_classes[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(sf->mark_classes[i],1,temp,sfd); } } else if ( strmatch(tok,"MarkAttachSets:")==0 ) { getint(sfd,&sf->mark_set_cnt); sf->mark_sets = malloc(sf->mark_set_cnt*sizeof(char *)); sf->mark_set_names = malloc(sf->mark_set_cnt*sizeof(char *)); for ( i=0; i<sf->mark_set_cnt; ++i ) { /* Set 0 is used */ int temp; while ( (temp=nlgetc(sfd))=='\n' || temp=='\r' ); ungetc(temp,sfd); sf->mark_set_names[i] = SFDReadUTF7Str(sfd); getint(sfd,&temp); sf->mark_sets[i] = malloc(temp+1); sf->mark_sets[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(sf->mark_sets[i],1,temp,sfd); } } else if ( strmatch(tok,"KernClass2:")==0 || strmatch(tok,"VKernClass2:")==0 || strmatch(tok,"KernClass:")==0 || strmatch(tok,"VKernClass:")==0 || strmatch(tok,"KernClass3:")==0 || strmatch(tok,"VKernClass3:")==0 ) { int kernclassversion = 0; int isv = tok[0]=='V'; int kcvoffset = (isv ? 10 : 9); //Offset to read kerning class version if (isdigit(tok[kcvoffset])) kernclassversion = tok[kcvoffset] - '0'; int temp, classstart=1; int old = (kernclassversion == 0); if ( (sf->sfd_version<2)!=old ) { IError( "Version mixup in Kerning Classes of sfd file." ); exit(1); } kc = chunkalloc(old ? sizeof(KernClass1) : sizeof(KernClass)); getint(sfd,&kc->first_cnt); ch=nlgetc(sfd); if ( ch=='+' ) classstart = 0; else ungetc(ch,sfd); getint(sfd,&kc->second_cnt); if ( old ) { getint(sfd,&temp); ((KernClass1 *) kc)->sli = temp; getint(sfd,&temp); ((KernClass1 *) kc)->flags = temp; } else { kc->subtable = SFFindLookupSubtableAndFreeName(sf,SFDReadUTF7Str(sfd)); if ( kc->subtable!=NULL && kc->subtable->kc==NULL ) kc->subtable->kc = kc; else { if ( kc->subtable==NULL ) LogError(_("Bad SFD file, missing subtable in kernclass defn.\n") ); else LogError(_("Bad SFD file, two kerning classes assigned to the same subtable: %s\n"), kc->subtable->subtable_name ); kc->subtable = NULL; } } kc->firsts = calloc(kc->first_cnt,sizeof(char *)); kc->seconds = calloc(kc->second_cnt,sizeof(char *)); kc->offsets = calloc(kc->first_cnt*kc->second_cnt,sizeof(int16)); kc->adjusts = calloc(kc->first_cnt*kc->second_cnt,sizeof(DeviceTable)); if (kernclassversion >= 3) { kc->firsts_flags = calloc(kc->first_cnt, sizeof(int)); kc->seconds_flags = calloc(kc->second_cnt, sizeof(int)); kc->offsets_flags = calloc(kc->first_cnt*kc->second_cnt, sizeof(int)); kc->firsts_names = calloc(kc->first_cnt, sizeof(char*)); kc->seconds_names = calloc(kc->second_cnt, sizeof(char*)); } kc->firsts[0] = NULL; for ( i=classstart; i<kc->first_cnt; ++i ) { if (kernclassversion < 3) { getint(sfd,&temp); kc->firsts[i] = malloc(temp+1); kc->firsts[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(kc->firsts[i],1,temp,sfd); } else { getint(sfd,&kc->firsts_flags[i]); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->firsts_names[i] = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->firsts[i] = SFDReadUTF7Str(sfd); if (kc->firsts[i] == NULL) kc->firsts[i] = copy(""); // In certain places, this must be defined. while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); } } kc->seconds[0] = NULL; for ( i=1; i<kc->second_cnt; ++i ) { if (kernclassversion < 3) { getint(sfd,&temp); kc->seconds[i] = malloc(temp+1); kc->seconds[i][temp] = '\0'; nlgetc(sfd); /* skip space */ fread(kc->seconds[i],1,temp,sfd); } else { getint(sfd,&temp); kc->seconds_flags[i] = temp; while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->seconds_names[i] = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); if (ch == '\n' || ch == EOF) continue; kc->seconds[i] = SFDReadUTF7Str(sfd); if (kc->seconds[i] == NULL) kc->seconds[i] = copy(""); // In certain places, this must be defined. while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); } } for ( i=0; i<kc->first_cnt*kc->second_cnt; ++i ) { if (kernclassversion >= 3) { getint(sfd,&temp); kc->offsets_flags[i] = temp; } getint(sfd,&temp); kc->offsets[i] = temp; SFDReadDeviceTable(sfd,&kc->adjusts[i]); } if ( !old && kc->subtable == NULL ) { /* Error. Ignore it. Free it. Whatever */; } else if ( !isv ) { if ( d->lastkc==NULL ) sf->kerns = kc; else d->lastkc->next = kc; d->lastkc = kc; } else { if ( d->lastvkc==NULL ) sf->vkerns = kc; else d->lastvkc->next = kc; d->lastvkc = kc; } } else if ( strmatch(tok,"ContextPos2:")==0 || strmatch(tok,"ContextSub2:")==0 || strmatch(tok,"ChainPos2:")==0 || strmatch(tok,"ChainSub2:")==0 || strmatch(tok,"ReverseChain2:")==0 || strmatch(tok,"ContextPos:")==0 || strmatch(tok,"ContextSub:")==0 || strmatch(tok,"ChainPos:")==0 || strmatch(tok,"ChainSub:")==0 || strmatch(tok,"ReverseChain:")==0 ) { FPST *fpst; int old; if ( strchr(tok,'2')!=NULL ) { old = false; fpst = chunkalloc(sizeof(FPST)); } else { old = true; fpst = chunkalloc(sizeof(FPST1)); } if ( (sf->sfd_version<2)!=old ) { IError( "Version mixup in FPST of sfd file." ); exit(1); } if ( d->lastfp==NULL ) sf->possub = fpst; else d->lastfp->next = fpst; d->lastfp = fpst; SFDParseChainContext(sfd,sf,fpst,tok,old); } else if ( strmatch(tok,"Group:")==0 ) { struct ff_glyphclasses *grouptmp = calloc(1, sizeof(struct ff_glyphclasses)); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); grouptmp->classname = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); grouptmp->glyphs = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); if (d->lastgroup != NULL) d->lastgroup->next = grouptmp; else sf->groups = grouptmp; d->lastgroup = grouptmp; } else if ( strmatch(tok,"GroupKern:")==0 ) { int temp = 0; struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets)); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->left = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->right = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); getint(sfd,&temp); kerntmp->offset = temp; while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); if (d->lastgroupkern != NULL) d->lastgroupkern->next = kerntmp; else sf->groupkerns = kerntmp; d->lastgroupkern = kerntmp; } else if ( strmatch(tok,"GroupVKern:")==0 ) { int temp = 0; struct ff_rawoffsets *kerntmp = calloc(1, sizeof(struct ff_rawoffsets)); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->left = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); kerntmp->right = SFDReadUTF7Str(sfd); while ((ch=nlgetc(sfd)) == ' '); ungetc(ch, sfd); getint(sfd,&temp); kerntmp->offset = temp; while ((ch=nlgetc(sfd)) == ' ' || ch == '\n'); ungetc(ch, sfd); if (d->lastgroupvkern != NULL) d->lastgroupvkern->next = kerntmp; else sf->groupvkerns = kerntmp; d->lastgroupvkern = kerntmp; } else if ( strmatch(tok,"MacIndic2:")==0 || strmatch(tok,"MacContext2:")==0 || strmatch(tok,"MacLigature2:")==0 || strmatch(tok,"MacSimple2:")==0 || strmatch(tok,"MacKern2:")==0 || strmatch(tok,"MacInsert2:")==0 || strmatch(tok,"MacIndic:")==0 || strmatch(tok,"MacContext:")==0 || strmatch(tok,"MacLigature:")==0 || strmatch(tok,"MacSimple:")==0 || strmatch(tok,"MacKern:")==0 || strmatch(tok,"MacInsert:")==0 ) { ASM *sm; if ( strchr(tok,'2')!=NULL ) { old = false; sm = chunkalloc(sizeof(ASM)); } else { old = true; sm = chunkalloc(sizeof(ASM1)); } if ( (sf->sfd_version<2)!=old ) { IError( "Version mixup in state machine of sfd file." ); exit(1); } if ( d->lastsm==NULL ) sf->sm = sm; else d->lastsm->next = sm; d->lastsm = sm; SFDParseStateMachine(sfd,sf,sm,tok,old); } else if ( strmatch(tok,"MacFeat:")==0 ) { sf->features = SFDParseMacFeatures(sfd,tok); } else if ( strmatch(tok,"TtfTable:")==0 ) { /* Old, binary format */ /* still used for maxp and unknown tables */ SFDGetTtfTable(sfd,sf,d->lastttf); } else if ( strmatch(tok,"TtTable:")==0 ) { /* text instruction format */ SFDGetTtTable(sfd,sf,d->lastttf); } /////////////////// else if ( strmatch(tok,"ShortTable:")==0 ) { // only read, not written. /* text number format */ SFDGetShortTable(sfd,sf,d->lastttf); } else { // // We didn't have a match ourselves. // return false; } return true; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix for #4084 Use-after-free (heap) in the SFD_GetFontMetaData() function Fix for #4086 NULL pointer dereference in the SFDGetSpiros() function Fix for #4088 NULL pointer dereference in the SFD_AssignLookups() function Add empty sf->fontname string if it isn't set, fixing #4089 #4090 and many other potential issues (many downstream calls to strlen() on the value).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void SFD_AssignLookups(SplineFont1 *sf) { PST1 *pst, *pst2; int isv; KernPair1 *kp, *kp2; KernClass1 *kc, *kc2; FPST1 *fpst; ASM1 *sm; AnchorClass1 *ac, *ac2; int gid, gid2, cnt, i, k, isgpos; SplineFont1 *subsf; SplineChar *sc, *sc2; OTLookup *otl, **all; struct lookup_subtable *sub; /* Fix up some gunk from really old versions of the sfd format */ SFDCleanupAnchorClasses(&sf->sf); if ( sf->sf.uni_interp==ui_unset ) sf->sf.uni_interp = interp_from_encoding(sf->sf.map->enc,ui_none); /* Fixup for an old bug */ if ( sf->sf.pfminfo.os2_winascent < sf->sf.ascent/4 && !sf->sf.pfminfo.winascent_add ) { sf->sf.pfminfo.winascent_add = true; sf->sf.pfminfo.os2_winascent = 0; sf->sf.pfminfo.windescent_add = true; sf->sf.pfminfo.os2_windescent = 0; } /* First handle the PSTs, no complications here */ k=0; do { subsf = sf->sf.subfontcnt==0 ? sf : (SplineFont1 *) (sf->sf.subfonts[k]); for ( gid=0; gid<subsf->sf.glyphcnt; ++gid ) if ( (sc=subsf->sf.glyphs[gid])!=NULL ) { for ( pst = (PST1 *) (sc->possub); pst!=NULL; pst = (PST1*) (pst->pst.next) ) { if ( pst->pst.type == pst_lcaret || pst->pst.subtable!=NULL ) continue; /* Nothing to do, or already done */ otl = CreateLookup(sf,pst->tag,pst->script_lang_index,pst->flags,pst->pst.type); sub = CreateSubtable(otl,sf); /* There might be another PST with the same flags on this glyph */ /* And we must fixup the current pst */ for ( pst2=pst ; pst2!=NULL; pst2 = (PST1 *) (pst2->pst.next) ) { if ( pst2->tag==pst->tag && pst2->script_lang_index==pst->script_lang_index && pst2->flags==pst->flags && pst2->pst.type==pst->pst.type ) pst2->pst.subtable = sub; } for ( gid2=gid+1; gid2<subsf->sf.glyphcnt; ++gid2 ) if ( (sc2=subsf->sf.glyphs[gid2])!=NULL ) { for ( pst2 = (PST1 *) (sc2->possub); pst2!=NULL; pst2 = (PST1 *) (pst2->pst.next) ) { if ( pst2->tag==pst->tag && pst2->script_lang_index==pst->script_lang_index && pst2->flags==pst->flags && pst2->pst.type==pst->pst.type ) pst2->pst.subtable = sub; } } } } ++k; } while ( k<sf->sf.subfontcnt ); /* Now kerns. May need to merge kernclasses to kernpair lookups (different subtables, of course */ for ( isv=0; isv<2; ++isv ) { k=0; do { subsf = sf->sf.subfontcnt==0 ? sf : (SplineFont1 *) (sf->sf.subfonts[k]); for ( gid=0; gid<subsf->sf.glyphcnt; ++gid ) if ( (sc=subsf->sf.glyphs[gid])!=NULL ) { for ( kp = (KernPair1 *) (isv ? sc->vkerns : sc->kerns); kp!=NULL; kp = (KernPair1 *) (kp->kp.next) ) { if ( kp->kp.subtable!=NULL ) continue; /* already done */ otl = CreateLookup(sf,isv ? CHR('v','k','r','n') : CHR('k','e','r','n'), kp->sli,kp->flags,pst_pair); sub = CreateSubtable(otl,sf); /* There might be another kp with the same flags on this glyph */ /* And we must fixup the current kp */ for ( kp2=kp ; kp2!=NULL; kp2 = (KernPair1 *) (kp2->kp.next) ) { if ( kp2->sli==kp->sli && kp2->flags==kp->flags ) kp2->kp.subtable = sub; } for ( gid2=gid+1; gid2<subsf->sf.glyphcnt; ++gid2 ) if ( (sc2=subsf->sf.glyphs[gid2])!=NULL ) { for ( kp2 = (KernPair1 *) (isv ? sc2->vkerns : sc2->kerns); kp2!=NULL; kp2 = (KernPair1 *) (kp2->kp.next) ) { if ( kp2->sli==kp->sli && kp2->flags==kp->flags ) kp2->kp.subtable = sub; } } /* And there might be a kerning class... */ for ( kc=(KernClass1 *) (isv ? sf->sf.vkerns : sf->sf.kerns); kc!=NULL; kc = (KernClass1 *) (kc->kc.next) ) { if ( kc->sli == kp->sli && kc->flags == kp->flags && kc->kc.subtable==NULL) { sub = CreateSubtable(otl,sf); sub->per_glyph_pst_or_kern = false; sub->kc = &kc->kc; kc->kc.subtable = sub; } } } } ++k; } while ( k<sf->sf.subfontcnt ); /* Or there might be a kerning class all by its lonesome */ for ( kc=(KernClass1 *) (isv ? sf->sf.vkerns : sf->sf.kerns); kc!=NULL; kc = (KernClass1 *) (kc->kc.next) ) { if ( kc->kc.subtable==NULL) { otl = CreateLookup(sf,isv ? CHR('v','k','r','n') : CHR('k','e','r','n'), kc->sli,kc->flags,pst_pair); for ( kc2=kc; kc2!=NULL; kc2=(KernClass1 *) (kc2->kc.next) ) { if ( kc->sli == kc2->sli && kc->flags == kc2->flags && kc2->kc.subtable==NULL) { sub = CreateSubtable(otl,sf); sub->per_glyph_pst_or_kern = false; sub->kc = &kc2->kc; kc2->kc.subtable = sub; } } } } } /* Every FPST and ASM lives in its own lookup with one subtable */ /* But the old format refered to nested lookups by tag, and now we refer */ /* to the lookup itself, so fix that up */ for ( fpst=(FPST1 *) sf->sf.possub; fpst!=NULL; fpst=((FPST1 *) fpst->fpst.next) ) { otl = CreateLookup(sf,fpst->tag, fpst->script_lang_index, fpst->flags,fpst->fpst.type); sub = CreateSubtable(otl,sf); sub->per_glyph_pst_or_kern = false; sub->fpst = &fpst->fpst; fpst->fpst.subtable = sub; FPSTReplaceTagsWithLookups(&fpst->fpst,sf); } for ( sm=(ASM1 *) sf->sf.sm; sm!=NULL; sm=((ASM1 *) sm->sm.next) ) { otl = CreateMacLookup(sf,sm); sub = CreateSubtable(otl,sf); sub->per_glyph_pst_or_kern = false; sub->sm = &sm->sm; sm->sm.subtable = sub; if ( sm->sm.type==asm_context ) ASMReplaceTagsWithLookups(&sm->sm,sf); } /* We retained the old nested feature tags so we could do the above conversion */ /* of tag to lookup. Get rid of them now */ for ( isgpos=0; isgpos<2; ++isgpos ) { for ( otl = isgpos ? sf->sf.gpos_lookups : sf->sf.gsub_lookups ; otl != NULL; otl=otl->next ) { if ( otl->features!=NULL && otl->features->scripts==NULL ) { chunkfree(otl->features,sizeof(FeatureScriptLangList)); otl->features = NULL; } } } /* Anchor classes are complicated, because I foolishly failed to distinguish */ /* between mark to base and mark to ligature classes. So one AC might have */ /* both. If so we need to turn it into two ACs, and have separate lookups */ /* for each */ for ( ac=(AnchorClass1 *) (sf->sf.anchor); ac!=NULL; ac=(AnchorClass1 *) ac->ac.next ) { ACHasBaseLig(sf,ac); if ( ac->has_ligatures && !ac->has_bases ) ac->ac.type = act_mklg; else if ( ac->has_ligatures && ac->has_bases ) ACDisassociateLigatures(sf,ac); } for ( ac=(AnchorClass1 *) (sf->sf.anchor); ac!=NULL; ac=(AnchorClass1 *) ac->ac.next ) { if ( ac->ac.subtable==NULL ) { otl = CreateACLookup(sf,ac); sub = CreateSubtable(otl,sf); for ( ac2=ac; ac2!=NULL; ac2 = (AnchorClass1 *) ac2->ac.next ) { if ( ac2->feature_tag == ac->feature_tag && ac2->script_lang_index == ac->script_lang_index && ac2->flags == ac->flags && ac2->ac.type == ac->ac.type && ac2->merge_with == ac->merge_with ) ac2->ac.subtable = sub; } } } /* Now I want to order the gsub lookups. I shan't bother with the gpos */ /* lookups because I didn't before */ for ( otl=sf->sf.gsub_lookups, cnt=0; otl!=NULL; otl=otl->next, ++cnt ); if ( cnt!=0 ) { all = malloc(cnt*sizeof(OTLookup *)); for ( otl=sf->sf.gsub_lookups, cnt=0; otl!=NULL; otl=otl->next, ++cnt ) { all[cnt] = otl; otl->lookup_index = GSubOrder(sf,otl->features); } qsort(all,cnt,sizeof(OTLookup *),order_lookups); sf->sf.gsub_lookups = all[0]; for ( i=1; i<cnt; ++i ) all[i-1]->next = all[i]; all[cnt-1]->next = NULL; free( all ); } for ( isgpos=0; isgpos<2; ++isgpos ) { for ( otl = isgpos ? sf->sf.gpos_lookups : sf->sf.gsub_lookups , cnt=0; otl!=NULL; otl = otl->next ) { otl->lookup_index = cnt++; NameOTLookup(otl,&sf->sf); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Fix for #4084 Use-after-free (heap) in the SFD_GetFontMetaData() function Fix for #4086 NULL pointer dereference in the SFDGetSpiros() function Fix for #4088 NULL pointer dereference in the SFD_AssignLookups() function Add empty sf->fontname string if it isn't set, fixing #4089 #4090 and many other potential issues (many downstream calls to strlen() on the value).'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void ttm_put_pages(struct page **pages, unsigned npages, int flags, enum ttm_caching_state cstate) { struct ttm_page_pool *pool = ttm_get_pool(flags, false, cstate); #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct ttm_page_pool *huge = ttm_get_pool(flags, true, cstate); #endif unsigned long irq_flags; unsigned i; if (pool == NULL) { /* No pool for this memory type so free the pages */ i = 0; while (i < npages) { #ifdef CONFIG_TRANSPARENT_HUGEPAGE struct page *p = pages[i]; #endif unsigned order = 0, j; if (!pages[i]) { ++i; continue; } #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (!(flags & TTM_PAGE_FLAG_DMA32)) { for (j = 0; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j == HPAGE_PMD_NR) order = HPAGE_PMD_ORDER; } #endif if (page_count(pages[i]) != 1) pr_err("Erroneous page count. Leaking pages.\n"); __free_pages(pages[i], order); j = 1 << order; while (j) { pages[i++] = NULL; --j; } } return; } i = 0; #ifdef CONFIG_TRANSPARENT_HUGEPAGE if (huge) { unsigned max_size, n2free; spin_lock_irqsave(&huge->lock, irq_flags); while (i < npages) { struct page *p = pages[i]; unsigned j; if (!p) break; for (j = 0; j < HPAGE_PMD_NR; ++j) if (p++ != pages[i + j]) break; if (j != HPAGE_PMD_NR) break; list_add_tail(&pages[i]->lru, &huge->list); for (j = 0; j < HPAGE_PMD_NR; ++j) pages[i++] = NULL; huge->npages++; } /* Check that we don't go over the pool limit */ max_size = _manager->options.max_size; max_size /= HPAGE_PMD_NR; if (huge->npages > max_size) n2free = huge->npages - max_size; else n2free = 0; spin_unlock_irqrestore(&huge->lock, irq_flags); if (n2free) ttm_page_pool_free(huge, n2free, false); } #endif spin_lock_irqsave(&pool->lock, irq_flags); while (i < npages) { if (pages[i]) { if (page_count(pages[i]) != 1) pr_err("Erroneous page count. Leaking pages.\n"); list_add_tail(&pages[i]->lru, &pool->list); pages[i] = NULL; pool->npages++; } ++i; } /* Check that we don't go over the pool limit */ npages = 0; if (pool->npages > _manager->options.max_size) { npages = pool->npages - _manager->options.max_size; /* free at least NUM_PAGES_TO_ALLOC number of pages * to reduce calls to set_memory_wb */ if (npages < NUM_PAGES_TO_ALLOC) npages = NUM_PAGES_TO_ALLOC; } spin_unlock_irqrestore(&pool->lock, irq_flags); if (npages) ttm_page_pool_free(pool, npages, false); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'drm/ttm: fix out-of-bounds read in ttm_put_pages() v2 When ttm_put_pages() tries to figure out whether it's dealing with transparent hugepages, it just reads past the bounds of the pages array without a check. v2: simplify the test if enough pages are left in the array (Christian). Signed-off-by: Jann Horn <jannh@google.com> Signed-off-by: Christian König <christian.koenig@amd.com> Fixes: 5c42c64f7d54 ("drm/ttm: fix the fix for huge compound pages") Cc: stable@vger.kernel.org Reviewed-by: Michel Dänzer <michel.daenzer@amd.com> Reviewed-by: Junwei Zhang <Jerry.Zhang@amd.com> Reviewed-by: Huang Rui <ray.huang@amd.com> Signed-off-by: Alex Deucher <alexander.deucher@amd.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int duplicate_search_and_fix(e2fsck_t ctx, ext2_filsys fs, ext2_ino_t ino, struct fill_dir_struct *fd) { struct problem_context pctx; struct hash_entry *ent, *prev; int i, j; int fixed = 0; char new_name[256]; unsigned int new_len; int hash_alg; int hash_flags = fd->inode->i_flags & EXT4_CASEFOLD_FL; clear_problem_context(&pctx); pctx.ino = ino; hash_alg = fs->super->s_def_hash_version; if ((hash_alg <= EXT2_HASH_TEA) && (fs->super->s_flags & EXT2_FLAGS_UNSIGNED_HASH)) hash_alg += 3; for (i=1; i < fd->num_array; i++) { ent = fd->harray + i; prev = ent - 1; if (!ent->dir->inode || (ext2fs_dirent_name_len(ent->dir) != ext2fs_dirent_name_len(prev->dir)) || memcmp(ent->dir->name, prev->dir->name, ext2fs_dirent_name_len(ent->dir))) continue; pctx.dirent = ent->dir; if ((ent->dir->inode == prev->dir->inode) && fix_problem(ctx, PR_2_DUPLICATE_DIRENT, &pctx)) { e2fsck_adjust_inode_count(ctx, ent->dir->inode, -1); ent->dir->inode = 0; fixed++; continue; } new_len = ext2fs_dirent_name_len(ent->dir); memcpy(new_name, ent->dir->name, new_len); mutate_name(new_name, &new_len); for (j=0; j < fd->num_array; j++) { if ((i==j) || (new_len != (unsigned) ext2fs_dirent_name_len(fd->harray[j].dir)) || memcmp(new_name, fd->harray[j].dir->name, new_len)) continue; mutate_name(new_name, &new_len); j = -1; } new_name[new_len] = 0; pctx.str = new_name; if (fix_problem(ctx, PR_2_NON_UNIQUE_FILE, &pctx)) { memcpy(ent->dir->name, new_name, new_len); ext2fs_dirent_set_name_len(ent->dir, new_len); ext2fs_dirhash2(hash_alg, new_name, new_len, fs->encoding, hash_flags, fs->super->s_hash_seed, &ent->hash, &ent->minor_hash); fixed++; } } return fixed; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'e2fsck: abort if there is a corrupted directory block when rehashing In e2fsck pass 3a, when we are rehashing directories, at least in theory, all of the directories should have had corruptions with respect to directory entry structure fixed. However, it's possible (for example, if the user declined a fix) that we can reach this stage of processing with a corrupted directory entries. So check for that case and don't try to process a corrupted directory block so we don't run into trouble in mutate_name() if there is a zero-length file name. Addresses: TALOS-2019-0973 Addresses: CVE-2019-5188 Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void delete_file(e2fsck_t ctx, ext2_ino_t ino, struct dup_inode *dp, char* block_buf) { ext2_filsys fs = ctx->fs; struct process_block_struct pb; struct problem_context pctx; unsigned int count; clear_problem_context(&pctx); pctx.ino = pb.ino = ino; pb.dup_blocks = 0; pb.ctx = ctx; pctx.str = "delete_file"; pb.cur_cluster = ~0; if (ext2fs_inode_has_valid_blocks2(fs, EXT2_INODE(&dp->inode))) pctx.errcode = ext2fs_block_iterate3(fs, ino, BLOCK_FLAG_READ_ONLY, block_buf, delete_file_block, &pb); if (pctx.errcode) fix_problem(ctx, PR_1B_BLOCK_ITERATE, &pctx); if (ctx->inode_bad_map) ext2fs_unmark_inode_bitmap2(ctx->inode_bad_map, ino); ext2fs_inode_alloc_stats2(fs, ino, -1, LINUX_S_ISDIR(dp->inode.i_mode)); quota_data_sub(ctx->qctx, &dp->inode, ino, pb.dup_blocks * fs->blocksize); quota_data_inodes(ctx->qctx, &dp->inode, ino, -1); /* Inode may have changed by block_iterate, so reread it */ e2fsck_read_inode_full(ctx, ino, EXT2_INODE(&dp->inode), sizeof(dp->inode), "delete_file"); e2fsck_clear_inode(ctx, ino, EXT2_INODE(&dp->inode), 0, "delete_file"); if (ext2fs_file_acl_block(fs, EXT2_INODE(&dp->inode)) && ext2fs_has_feature_xattr(fs->super)) { blk64_t file_acl_block = ext2fs_file_acl_block(fs, EXT2_INODE(&dp->inode)); count = 1; pctx.errcode = ext2fs_adjust_ea_refcount3(fs, file_acl_block, block_buf, -1, &count, ino); if (pctx.errcode == EXT2_ET_BAD_EA_BLOCK_NUM) { pctx.errcode = 0; count = 1; } if (pctx.errcode) { pctx.blk = file_acl_block; fix_problem(ctx, PR_1B_ADJ_EA_REFCOUNT, &pctx); } /* * If the count is zero, then arrange to have the * block deleted. If the block is in the block_dup_map, * also call delete_file_block since it will take care * of keeping the accounting straight. */ if ((count == 0) || ext2fs_test_block_bitmap2(ctx->block_dup_map, file_acl_block)) { delete_file_block(fs, &file_acl_block, BLOCK_COUNT_EXTATTR, 0, 0, &pb); ext2fs_file_acl_block_set(fs, EXT2_INODE(&dp->inode), file_acl_block); quota_data_sub(ctx->qctx, &dp->inode, ino, fs->blocksize); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'e2fsck: don't try to rehash a deleted directory If directory has been deleted in pass1[bcd] processing, then we shouldn't try to rehash the directory in pass 3a when we try to rehash/reoptimize directories. Signed-off-by: Theodore Ts'o <tytso@mit.edu>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: char* parseValue( char* ptr, FileNode& node ) { if (!ptr) CV_PARSE_ERROR_CPP("Invalid input"); FileNode new_elem; bool have_space = true; int value_type = node.type(); std::string key, key2, type_name; for(;;) { char c = *ptr, d; char* endptr; // FIXIT ptr[1], ptr[2] - out of bounds read without check or data fetch (#11061) if( cv_isspace(c) || c == '\0' || (c == '<' && ptr[1] == '!' && ptr[2] == '-') ) { ptr = skipSpaces( ptr, 0 ); if (!ptr) CV_PARSE_ERROR_CPP("Invalid input"); have_space = true; c = *ptr; } d = ptr[1]; // FIXIT ptr[1] - out of bounds read without check or data fetch (#11061) if( c =='<' || c == '\0' ) { int tag_type = 0; int elem_type = FileNode::NONE; if( d == '/' || c == '\0' ) break; ptr = parseTag( ptr, key, type_name, tag_type ); if( tag_type == CV_XML_DIRECTIVE_TAG ) CV_PARSE_ERROR_CPP( "Directive tags are not allowed here" ); if( tag_type == CV_XML_EMPTY_TAG ) CV_PARSE_ERROR_CPP( "Empty tags are not supported" ); CV_Assert(tag_type == CV_XML_OPENING_TAG); /* for base64 string */ bool binary_string = false; if( !type_name.empty() ) { const char* tn = type_name.c_str(); if( strcmp(tn, "str") == 0 ) elem_type = FileNode::STRING; else if( strcmp( tn, "map" ) == 0 ) elem_type = FileNode::MAP; else if( strcmp( tn, "seq" ) == 0 ) elem_type = FileNode::SEQ; else if( strcmp( tn, "binary") == 0) binary_string = true; } new_elem = fs->addNode(node, key, elem_type, 0); if (!binary_string) ptr = parseValue(ptr, new_elem); else { ptr = fs->parseBase64( ptr, 0, new_elem); ptr = skipSpaces( ptr, 0 ); if (!ptr) CV_PARSE_ERROR_CPP("Invalid input"); } ptr = parseTag( ptr, key2, type_name, tag_type ); if( tag_type != CV_XML_CLOSING_TAG || key2 != key ) CV_PARSE_ERROR_CPP( "Mismatched closing tag" ); have_space = true; } else { if( !have_space ) CV_PARSE_ERROR_CPP( "There should be space between literals" ); FileNode* elem = &node; if( node.type() != FileNode::NONE ) { fs->convertToCollection( FileNode::SEQ, node ); new_elem = fs->addNode(node, std::string(), FileNode::NONE, 0); elem = &new_elem; } if( value_type != FileNode::STRING && (cv_isdigit(c) || ((c == '-' || c == '+') && (cv_isdigit(d) || d == '.')) || (c == '.' && cv_isalnum(d))) ) // a number { endptr = ptr + (c == '-' || c == '+'); while( cv_isdigit(*endptr) ) endptr++; if( *endptr == '.' || *endptr == 'e' ) { double fval = fs->strtod( ptr, &endptr ); elem->setValue(FileNode::REAL, &fval); } else { int ival = (int)strtol( ptr, &endptr, 0 ); elem->setValue(FileNode::INT, &ival); } if( endptr == ptr ) CV_PARSE_ERROR_CPP( "Invalid numeric value (inconsistent explicit type specification?)" ); ptr = endptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); } else { // string int i = 0, len, is_quoted = 0; if( c == '\"' ) is_quoted = 1; else --ptr; strbuf[0] = '\0'; for( ;; ) { c = *++ptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); if( !cv_isalnum(c) ) { if( c == '\"' ) { if( !is_quoted ) CV_PARSE_ERROR_CPP( "Literal \" is not allowed within a string. Use &quot;" ); ++ptr; break; } else if( !cv_isprint(c) || c == '<' || (!is_quoted && cv_isspace(c))) { if( is_quoted ) CV_PARSE_ERROR_CPP( "Closing \" is expected" ); break; } else if( c == '\'' || c == '>' ) { CV_PARSE_ERROR_CPP( "Literal \' or > are not allowed. Use &apos; or &gt;" ); } else if( c == '&' ) { if( *++ptr == '#' ) { int val, base = 10; ptr++; if( *ptr == 'x' ) { base = 16; ptr++; } val = (int)strtol( ptr, &endptr, base ); if( (unsigned)val > (unsigned)255 || !endptr || *endptr != ';' ) CV_PARSE_ERROR_CPP( "Invalid numeric value in the string" ); c = (char)val; } else { endptr = ptr; do c = *++endptr; while( cv_isalnum(c) ); if( c != ';' ) CV_PARSE_ERROR_CPP( "Invalid character in the symbol entity name" ); len = (int)(endptr - ptr); if( len == 2 && memcmp( ptr, "lt", len ) == 0 ) c = '<'; else if( len == 2 && memcmp( ptr, "gt", len ) == 0 ) c = '>'; else if( len == 3 && memcmp( ptr, "amp", len ) == 0 ) c = '&'; else if( len == 4 && memcmp( ptr, "apos", len ) == 0 ) c = '\''; else if( len == 4 && memcmp( ptr, "quot", len ) == 0 ) c = '\"'; else { memcpy( strbuf + i, ptr-1, len + 2 ); i += len + 2; } } ptr = endptr; CV_PERSISTENCE_CHECK_END_OF_BUFFER_BUG_CPP(); } } strbuf[i++] = c; if( i >= CV_FS_MAX_LEN ) CV_PARSE_ERROR_CPP( "Too long string literal" ); } elem->setValue(FileNode::STRING, strbuf, i); } if( value_type != FileNode::NONE && value_type != FileNode::SEQ && value_type != FileNode::MAP ) break; have_space = false; } } fs->finalizeCollection(node); return ptr; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'core(persistence): add more checks for implementation limitations'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void drop_sysctl_table(struct ctl_table_header *header) { struct ctl_dir *parent = header->parent; if (--header->nreg) return; put_links(header); start_unregistering(header); if (!--header->count) kfree_rcu(header, rcu); if (parent) drop_sysctl_table(&parent->header); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'fs/proc/proc_sysctl.c: fix NULL pointer dereference in put_links Syzkaller reports: kasan: GPF could be caused by NULL-ptr deref or user memory access general protection fault: 0000 [#1] SMP KASAN PTI CPU: 1 PID: 5373 Comm: syz-executor.0 Not tainted 5.0.0-rc8+ #3 Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.10.2-1ubuntu1 04/01/2014 RIP: 0010:put_links+0x101/0x440 fs/proc/proc_sysctl.c:1599 Code: 00 0f 85 3a 03 00 00 48 8b 43 38 48 89 44 24 20 48 83 c0 38 48 89 c2 48 89 44 24 28 48 b8 00 00 00 00 00 fc ff df 48 c1 ea 03 <80> 3c 02 00 0f 85 fe 02 00 00 48 8b 74 24 20 48 c7 c7 60 2a 9d 91 RSP: 0018:ffff8881d828f238 EFLAGS: 00010202 RAX: dffffc0000000000 RBX: ffff8881e01b1140 RCX: ffffffff8ee98267 RDX: 0000000000000007 RSI: ffffc90001479000 RDI: ffff8881e01b1178 RBP: dffffc0000000000 R08: ffffed103ee27259 R09: ffffed103ee27259 R10: 0000000000000001 R11: ffffed103ee27258 R12: fffffffffffffff4 R13: 0000000000000006 R14: ffff8881f59838c0 R15: dffffc0000000000 FS: 00007f072254f700(0000) GS:ffff8881f7100000(0000) knlGS:0000000000000000 CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033 CR2: 00007fff8b286668 CR3: 00000001f0542002 CR4: 00000000007606e0 DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000 DR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400 PKRU: 55555554 Call Trace: drop_sysctl_table+0x152/0x9f0 fs/proc/proc_sysctl.c:1629 get_subdir fs/proc/proc_sysctl.c:1022 [inline] __register_sysctl_table+0xd65/0x1090 fs/proc/proc_sysctl.c:1335 br_netfilter_init+0xbc/0x1000 [br_netfilter] do_one_initcall+0xfa/0x5ca init/main.c:887 do_init_module+0x204/0x5f6 kernel/module.c:3460 load_module+0x66b2/0x8570 kernel/module.c:3808 __do_sys_finit_module+0x238/0x2a0 kernel/module.c:3902 do_syscall_64+0x147/0x600 arch/x86/entry/common.c:290 entry_SYSCALL_64_after_hwframe+0x49/0xbe RIP: 0033:0x462e99 Code: f7 d8 64 89 02 b8 ff ff ff ff c3 66 0f 1f 44 00 00 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 bc ff ff ff f7 d8 64 89 01 48 RSP: 002b:00007f072254ec58 EFLAGS: 00000246 ORIG_RAX: 0000000000000139 RAX: ffffffffffffffda RBX: 000000000073bf00 RCX: 0000000000462e99 RDX: 0000000000000000 RSI: 0000000020000280 RDI: 0000000000000003 RBP: 00007f072254ec70 R08: 0000000000000000 R09: 0000000000000000 R10: 0000000000000000 R11: 0000000000000246 R12: 00007f072254f6bc R13: 00000000004bcefa R14: 00000000006f6fb0 R15: 0000000000000004 Modules linked in: br_netfilter(+) dvb_usb_dibusb_mc_common dib3000mc dibx000_common dvb_usb_dibusb_common dvb_usb_dw2102 dvb_usb classmate_laptop palmas_regulator cn videobuf2_v4l2 v4l2_common snd_soc_bd28623 mptbase snd_usb_usx2y snd_usbmidi_lib snd_rawmidi wmi libnvdimm lockd sunrpc grace rc_kworld_pc150u rc_core rtc_da9063 sha1_ssse3 i2c_cros_ec_tunnel adxl34x_spi adxl34x nfnetlink lib80211 i5500_temp dvb_as102 dvb_core videobuf2_common videodev media videobuf2_vmalloc videobuf2_memops udc_core lnbp22 leds_lp3952 hid_roccat_ryos s1d13xxxfb mtd vport_geneve openvswitch nf_conncount nf_nat_ipv6 nsh geneve udp_tunnel ip6_udp_tunnel snd_soc_mt6351 sis_agp phylink snd_soc_adau1761_spi snd_soc_adau1761 snd_soc_adau17x1 snd_soc_core snd_pcm_dmaengine ac97_bus snd_compress snd_soc_adau_utils snd_soc_sigmadsp_regmap snd_soc_sigmadsp raid_class hid_roccat_konepure hid_roccat_common hid_roccat c2port_duramar2150 core mdio_bcm_unimac iptable_security iptable_raw iptable_mangle iptable_nat nf_nat_ipv4 nf_nat nf_conntrack nf_defrag_ipv6 nf_defrag_ipv4 iptable_filter bpfilter ip6_vti ip_vti ip_gre ipip sit tunnel4 ip_tunnel hsr veth netdevsim devlink vxcan batman_adv cfg80211 rfkill chnl_net caif nlmon dummy team bonding vcan bridge stp llc ip6_gre gre ip6_tunnel tunnel6 tun crct10dif_pclmul crc32_pclmul crc32c_intel ghash_clmulni_intel joydev mousedev ide_pci_generic piix aesni_intel aes_x86_64 ide_core crypto_simd atkbd cryptd glue_helper serio_raw ata_generic pata_acpi i2c_piix4 floppy sch_fq_codel ip_tables x_tables ipv6 [last unloaded: lm73] Dumping ftrace buffer: (ftrace buffer empty) ---[ end trace 770020de38961fd0 ]--- A new dir entry can be created in get_subdir and its 'header->parent' is set to NULL. Only after insert_header success, it will be set to 'dir', otherwise 'header->parent' is set to NULL and drop_sysctl_table is called. However in err handling path of get_subdir, drop_sysctl_table also be called on 'new->header' regardless its value of parent pointer. Then put_links is called, which triggers NULL-ptr deref when access member of header->parent. In fact we have multiple error paths which call drop_sysctl_table() there, upon failure on insert_links() we also call drop_sysctl_table().And even in the successful case on __register_sysctl_table() we still always call drop_sysctl_table().This patch fix it. Link: http://lkml.kernel.org/r/20190314085527.13244-1-yuehaibing@huawei.com Fixes: 0e47c99d7fe25 ("sysctl: Replace root_list with links between sysctl_table_sets") Signed-off-by: YueHaibing <yuehaibing@huawei.com> Reported-by: Hulk Robot <hulkci@huawei.com> Acked-by: Luis Chamberlain <mcgrof@kernel.org> Cc: Kees Cook <keescook@chromium.org> Cc: Alexey Dobriyan <adobriyan@gmail.com> Cc: Alexei Starovoitov <ast@kernel.org> Cc: Daniel Borkmann <daniel@iogearbox.net> Cc: Al Viro <viro@zeniv.linux.org.uk> Cc: Eric W. Biederman <ebiederm@xmission.com> Cc: <stable@vger.kernel.org> [3.4+] Signed-off-by: Andrew Morton <akpm@linux-foundation.org> Signed-off-by: Linus Torvalds <torvalds@linux-foundation.org>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: ngx_http_send_error_page(ngx_http_request_t *r, ngx_http_err_page_t *err_page) { ngx_int_t overwrite; ngx_str_t uri, args; ngx_table_elt_t *location; ngx_http_core_loc_conf_t *clcf; overwrite = err_page->overwrite; if (overwrite && overwrite != NGX_HTTP_OK) { r->expect_tested = 1; } if (overwrite >= 0) { r->err_status = overwrite; } if (ngx_http_complex_value(r, &err_page->value, &uri) != NGX_OK) { return NGX_ERROR; } if (uri.len && uri.data[0] == '/') { if (err_page->value.lengths) { ngx_http_split_args(r, &uri, &args); } else { args = err_page->args; } if (r->method != NGX_HTTP_HEAD) { r->method = NGX_HTTP_GET; r->method_name = ngx_http_core_get_method; } return ngx_http_internal_redirect(r, &uri, &args); } if (uri.len && uri.data[0] == '@') { return ngx_http_named_location(r, &uri); } location = ngx_list_push(&r->headers_out.headers); if (location == NULL) { return NGX_ERROR; } if (overwrite != NGX_HTTP_MOVED_PERMANENTLY && overwrite != NGX_HTTP_MOVED_TEMPORARILY && overwrite != NGX_HTTP_SEE_OTHER && overwrite != NGX_HTTP_TEMPORARY_REDIRECT && overwrite != NGX_HTTP_PERMANENT_REDIRECT) { r->err_status = NGX_HTTP_MOVED_TEMPORARILY; } location->hash = 1; ngx_str_set(&location->key, "Location"); location->value = uri; ngx_http_clear_location(r); r->headers_out.location = location; clcf = ngx_http_get_module_loc_conf(r, ngx_http_core_module); if (clcf->msie_refresh && r->headers_in.msie) { return ngx_http_send_refresh(r); } return ngx_http_send_special_response(r, clcf, r->err_status - NGX_HTTP_MOVED_PERMANENTLY + NGX_HTTP_OFF_3XX); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-444', 'CWE-787'], 'message': 'Discard request body when redirecting to a URL via error_page. Reported by Bert JW Regeer and Francisco Oca Gonzalez.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: TightDecoder::FilterGradient24(const rdr::U8 *inbuf, const PixelFormat& pf, PIXEL_T* outbuf, int stride, const Rect& r) { int x, y, c; rdr::U8 prevRow[TIGHT_MAX_WIDTH*3]; rdr::U8 thisRow[TIGHT_MAX_WIDTH*3]; rdr::U8 pix[3]; int est[3]; memset(prevRow, 0, sizeof(prevRow)); // Set up shortcut variables int rectHeight = r.height(); int rectWidth = r.width(); for (y = 0; y < rectHeight; y++) { /* First pixel in a row */ for (c = 0; c < 3; c++) { pix[c] = inbuf[y*rectWidth*3+c] + prevRow[c]; thisRow[c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride], pix, 1); /* Remaining pixels of a row */ for (x = 1; x < rectWidth; x++) { for (c = 0; c < 3; c++) { est[c] = prevRow[x*3+c] + pix[c] - prevRow[(x-1)*3+c]; if (est[c] > 0xff) { est[c] = 0xff; } else if (est[c] < 0) { est[c] = 0; } pix[c] = inbuf[(y*rectWidth+x)*3+c] + est[c]; thisRow[x*3+c] = pix[c]; } pf.bufferFromRGB((rdr::U8*)&outbuf[y*stride+x], pix, 1); } memcpy(prevRow, thisRow, sizeof(prevRow)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'Handle empty Tight gradient rects We always assumed there would be one pixel per row so a rect with a zero width would result in us writing to unknown memory. This could theoretically be used by a malicious server to inject code in to the viewer process. Issue found by Pavel Cheremushkin from Kaspersky Lab.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int overrun(int itemSize, int nItems) { int len = ptr - start + itemSize * nItems; if (len < (end - start) * 2) len = (end - start) * 2; U8* newStart = new U8[len]; memcpy(newStart, start, ptr - start); ptr = newStart + (ptr - start); delete [] start; start = newStart; end = newStart + len; return nItems; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline void pad(int bytes) { while (bytes-- > 0) writeU8(0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline bool checkNoWait(int length) { return check(length, 1, false)!=0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void readBytes(void* data, int length) { U8* dataPtr = (U8*)data; U8* dataEnd = dataPtr + length; while (dataPtr < dataEnd) { int n = check(1, dataEnd - dataPtr); memcpy(dataPtr, ptr, n); ptr += n; dataPtr += n; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int length() { return ptr - start; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: MemInStream(const void* data, int len, bool deleteWhenDone_=false) : start((const U8*)data), deleteWhenDone(deleteWhenDone_) { ptr = start; end = start + len; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: inline int check(int itemSize, int nItems=1, bool wait=true) { if (ptr + itemSize * nItems > end) { if (ptr + itemSize > end) return overrun(itemSize, nItems, wait); nItems = (end - ptr) / itemSize; } return nItems; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int pos() { return ptr - start; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-787'], 'message': 'Use size_t for lengths in stream objects Provides safety against them accidentally becoming negative because of bugs in the calculations. Also does the same to CharArray and friends as they were strongly connection to the stream objects.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int tcp_emu(struct socket *so, struct mbuf *m) { Slirp *slirp = so->slirp; unsigned n1, n2, n3, n4, n5, n6; char buff[257]; uint32_t laddr; unsigned lport; char *bptr; DEBUG_CALL("tcp_emu"); DEBUG_ARG("so = %p", so); DEBUG_ARG("m = %p", m); switch (so->so_emu) { int x, i; /* TODO: IPv6 */ case EMU_IDENT: /* * Identification protocol as per rfc-1413 */ { struct socket *tmpso; struct sockaddr_in addr; socklen_t addrlen = sizeof(struct sockaddr_in); char *eol = g_strstr_len(m->m_data, m->m_len, "\r\n"); if (!eol) { return 1; } *eol = '\0'; if (sscanf(m->m_data, "%u%*[ ,]%u", &n1, &n2) == 2) { HTONS(n1); HTONS(n2); /* n2 is the one on our host */ for (tmpso = slirp->tcb.so_next; tmpso != &slirp->tcb; tmpso = tmpso->so_next) { if (tmpso->so_laddr.s_addr == so->so_laddr.s_addr && tmpso->so_lport == n2 && tmpso->so_faddr.s_addr == so->so_faddr.s_addr && tmpso->so_fport == n1) { if (getsockname(tmpso->s, (struct sockaddr *)&addr, &addrlen) == 0) n2 = addr.sin_port; break; } } NTOHS(n1); NTOHS(n2); m_inc(m, snprintf(NULL, 0, "%d,%d\r\n", n1, n2) + 1); m->m_len = snprintf(m->m_data, M_ROOM(m), "%d,%d\r\n", n1, n2); assert(m->m_len < M_ROOM(m)); } else { *eol = '\r'; } return 1; } case EMU_FTP: /* ftp */ m_inc(m, m->m_len + 1); *(m->m_data + m->m_len) = 0; /* NUL terminate for strstr */ if ((bptr = (char *)strstr(m->m_data, "ORT")) != NULL) { /* * Need to emulate the PORT command */ x = sscanf(bptr, "ORT %u,%u,%u,%u,%u,%u\r\n%256[^\177]", &n1, &n2, &n3, &n4, &n5, &n6, buff); if (x < 6) return 1; laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4)); lport = htons((n5 << 8) | (n6)); if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport, SS_FACCEPTONCE)) == NULL) { return 1; } n6 = ntohs(so->so_fport); n5 = (n6 >> 8) & 0xff; n6 &= 0xff; laddr = ntohl(so->so_faddr.s_addr); n1 = ((laddr >> 24) & 0xff); n2 = ((laddr >> 16) & 0xff); n3 = ((laddr >> 8) & 0xff); n4 = (laddr & 0xff); m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size - m->m_len, "ORT %d,%d,%d,%d,%d,%d\r\n%s", n1, n2, n3, n4, n5, n6, x == 7 ? buff : ""); return 1; } else if ((bptr = (char *)strstr(m->m_data, "27 Entering")) != NULL) { /* * Need to emulate the PASV response */ x = sscanf( bptr, "27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\r\n%256[^\177]", &n1, &n2, &n3, &n4, &n5, &n6, buff); if (x < 6) return 1; laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4)); lport = htons((n5 << 8) | (n6)); if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport, SS_FACCEPTONCE)) == NULL) { return 1; } n6 = ntohs(so->so_fport); n5 = (n6 >> 8) & 0xff; n6 &= 0xff; laddr = ntohl(so->so_faddr.s_addr); n1 = ((laddr >> 24) & 0xff); n2 = ((laddr >> 16) & 0xff); n3 = ((laddr >> 8) & 0xff); n4 = (laddr & 0xff); m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size - m->m_len, "27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n%s", n1, n2, n3, n4, n5, n6, x == 7 ? buff : ""); return 1; } return 1; case EMU_KSH: /* * The kshell (Kerberos rsh) and shell services both pass * a local port port number to carry signals to the server * and stderr to the client. It is passed at the beginning * of the connection as a NUL-terminated decimal ASCII string. */ so->so_emu = 0; for (lport = 0, i = 0; i < m->m_len - 1; ++i) { if (m->m_data[i] < '0' || m->m_data[i] > '9') return 1; /* invalid number */ lport *= 10; lport += m->m_data[i] - '0'; } if (m->m_data[m->m_len - 1] == '\0' && lport != 0 && (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr, htons(lport), SS_FACCEPTONCE)) != NULL) m->m_len = snprintf(m->m_data, m->m_size, "%d", ntohs(so->so_fport)) + 1; return 1; case EMU_IRC: /* * Need to emulate DCC CHAT, DCC SEND and DCC MOVE */ m_inc(m, m->m_len + 1); *(m->m_data + m->m_len) = 0; /* NULL terminate the string for strstr */ if ((bptr = (char *)strstr(m->m_data, "DCC")) == NULL) return 1; /* The %256s is for the broken mIRC */ if (sscanf(bptr, "DCC CHAT %256s %u %u", buff, &laddr, &lport) == 3) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size, "DCC CHAT chat %lu %u%c\n", (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), 1); } else if (sscanf(bptr, "DCC SEND %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size, "DCC SEND %s %lu %u %u%c\n", buff, (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), n1, 1); } else if (sscanf(bptr, "DCC MOVE %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size, "DCC MOVE %s %lu %u %u%c\n", buff, (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), n1, 1); } return 1; case EMU_REALAUDIO: /* * RealAudio emulation - JP. We must try to parse the incoming * data and try to find the two characters that contain the * port number. Then we redirect an udp port and replace the * number with the real port we got. * * The 1.0 beta versions of the player are not supported * any more. * * A typical packet for player version 1.0 (release version): * * 0000:50 4E 41 00 05 * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB * * Now the port number 0x1BD7 is found at offset 0x04 of the * Now the port number 0x1BD7 is found at offset 0x04 of the * second packet. This time we received five bytes first and * then the rest. You never know how many bytes you get. * * A typical packet for player version 2.0 (beta): * * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA............. * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0 * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/ * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B * * Port number 0x1BC1 is found at offset 0x0d. * * This is just a horrible switch statement. Variable ra tells * us where we're going. */ bptr = m->m_data; while (bptr < m->m_data + m->m_len) { uint16_t p; static int ra = 0; char ra_tbl[4]; ra_tbl[0] = 0x50; ra_tbl[1] = 0x4e; ra_tbl[2] = 0x41; ra_tbl[3] = 0; switch (ra) { case 0: case 2: case 3: if (*bptr++ != ra_tbl[ra]) { ra = 0; continue; } break; case 1: /* * We may get 0x50 several times, ignore them */ if (*bptr == 0x50) { ra = 1; bptr++; continue; } else if (*bptr++ != ra_tbl[ra]) { ra = 0; continue; } break; case 4: /* * skip version number */ bptr++; break; case 5: /* * The difference between versions 1.0 and * 2.0 is here. For future versions of * the player this may need to be modified. */ if (*(bptr + 1) == 0x02) bptr += 8; else bptr += 4; break; case 6: /* This is the field containing the port * number that RA-player is listening to. */ lport = (((uint8_t *)bptr)[0] << 8) + ((uint8_t *)bptr)[1]; if (lport < 6970) lport += 256; /* don't know why */ if (lport < 6970 || lport > 7170) return 1; /* failed */ /* try to get udp port between 6970 - 7170 */ for (p = 6970; p < 7071; p++) { if (udp_listen(slirp, INADDR_ANY, htons(p), so->so_laddr.s_addr, htons(lport), SS_FACCEPTONCE)) { break; } } if (p == 7071) p = 0; *(uint8_t *)bptr++ = (p >> 8) & 0xff; *(uint8_t *)bptr = p & 0xff; ra = 0; return 1; /* port redirected, we're done */ break; default: ra = 0; } ra++; } return 1; default: /* Ooops, not emulated, won't call tcp_emu again */ so->so_emu = 0; return 1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'tcp_emu: Fix oob access The main loop only checks for one available byte, while we sometimes need two bytes.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int tcp_emu(struct socket *so, struct mbuf *m) { Slirp *slirp = so->slirp; unsigned n1, n2, n3, n4, n5, n6; char buff[257]; uint32_t laddr; unsigned lport; char *bptr; DEBUG_CALL("tcp_emu"); DEBUG_ARG("so = %p", so); DEBUG_ARG("m = %p", m); switch (so->so_emu) { int x, i; /* TODO: IPv6 */ case EMU_IDENT: /* * Identification protocol as per rfc-1413 */ { struct socket *tmpso; struct sockaddr_in addr; socklen_t addrlen = sizeof(struct sockaddr_in); char *eol = g_strstr_len(m->m_data, m->m_len, "\r\n"); if (!eol) { return 1; } *eol = '\0'; if (sscanf(m->m_data, "%u%*[ ,]%u", &n1, &n2) == 2) { HTONS(n1); HTONS(n2); /* n2 is the one on our host */ for (tmpso = slirp->tcb.so_next; tmpso != &slirp->tcb; tmpso = tmpso->so_next) { if (tmpso->so_laddr.s_addr == so->so_laddr.s_addr && tmpso->so_lport == n2 && tmpso->so_faddr.s_addr == so->so_faddr.s_addr && tmpso->so_fport == n1) { if (getsockname(tmpso->s, (struct sockaddr *)&addr, &addrlen) == 0) n2 = addr.sin_port; break; } } NTOHS(n1); NTOHS(n2); m_inc(m, snprintf(NULL, 0, "%d,%d\r\n", n1, n2) + 1); m->m_len = snprintf(m->m_data, M_ROOM(m), "%d,%d\r\n", n1, n2); assert(m->m_len < M_ROOM(m)); } else { *eol = '\r'; } return 1; } case EMU_FTP: /* ftp */ m_inc(m, m->m_len + 1); *(m->m_data + m->m_len) = 0; /* NUL terminate for strstr */ if ((bptr = (char *)strstr(m->m_data, "ORT")) != NULL) { /* * Need to emulate the PORT command */ x = sscanf(bptr, "ORT %u,%u,%u,%u,%u,%u\r\n%256[^\177]", &n1, &n2, &n3, &n4, &n5, &n6, buff); if (x < 6) return 1; laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4)); lport = htons((n5 << 8) | (n6)); if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport, SS_FACCEPTONCE)) == NULL) { return 1; } n6 = ntohs(so->so_fport); n5 = (n6 >> 8) & 0xff; n6 &= 0xff; laddr = ntohl(so->so_faddr.s_addr); n1 = ((laddr >> 24) & 0xff); n2 = ((laddr >> 16) & 0xff); n3 = ((laddr >> 8) & 0xff); n4 = (laddr & 0xff); m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size - m->m_len, "ORT %d,%d,%d,%d,%d,%d\r\n%s", n1, n2, n3, n4, n5, n6, x == 7 ? buff : ""); return 1; } else if ((bptr = (char *)strstr(m->m_data, "27 Entering")) != NULL) { /* * Need to emulate the PASV response */ x = sscanf( bptr, "27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\r\n%256[^\177]", &n1, &n2, &n3, &n4, &n5, &n6, buff); if (x < 6) return 1; laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4)); lport = htons((n5 << 8) | (n6)); if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport, SS_FACCEPTONCE)) == NULL) { return 1; } n6 = ntohs(so->so_fport); n5 = (n6 >> 8) & 0xff; n6 &= 0xff; laddr = ntohl(so->so_faddr.s_addr); n1 = ((laddr >> 24) & 0xff); n2 = ((laddr >> 16) & 0xff); n3 = ((laddr >> 8) & 0xff); n4 = (laddr & 0xff); m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, m->m_size - m->m_len, "27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n%s", n1, n2, n3, n4, n5, n6, x == 7 ? buff : ""); return 1; } return 1; case EMU_KSH: /* * The kshell (Kerberos rsh) and shell services both pass * a local port port number to carry signals to the server * and stderr to the client. It is passed at the beginning * of the connection as a NUL-terminated decimal ASCII string. */ so->so_emu = 0; for (lport = 0, i = 0; i < m->m_len - 1; ++i) { if (m->m_data[i] < '0' || m->m_data[i] > '9') return 1; /* invalid number */ lport *= 10; lport += m->m_data[i] - '0'; } if (m->m_data[m->m_len - 1] == '\0' && lport != 0 && (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr, htons(lport), SS_FACCEPTONCE)) != NULL) m->m_len = snprintf(m->m_data, m->m_size, "%d", ntohs(so->so_fport)) + 1; return 1; case EMU_IRC: /* * Need to emulate DCC CHAT, DCC SEND and DCC MOVE */ m_inc(m, m->m_len + 1); *(m->m_data + m->m_len) = 0; /* NULL terminate the string for strstr */ if ((bptr = (char *)strstr(m->m_data, "DCC")) == NULL) return 1; /* The %256s is for the broken mIRC */ if (sscanf(bptr, "DCC CHAT %256s %u %u", buff, &laddr, &lport) == 3) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, M_FREEROOM(m), "DCC CHAT chat %lu %u%c\n", (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), 1); } else if (sscanf(bptr, "DCC SEND %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, M_FREEROOM(m), "DCC SEND %s %lu %u %u%c\n", buff, (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), n1, 1); } else if (sscanf(bptr, "DCC MOVE %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) { if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr), htons(lport), SS_FACCEPTONCE)) == NULL) { return 1; } m->m_len = bptr - m->m_data; /* Adjust length */ m->m_len += snprintf(bptr, M_FREEROOM(m), "DCC MOVE %s %lu %u %u%c\n", buff, (unsigned long)ntohl(so->so_faddr.s_addr), ntohs(so->so_fport), n1, 1); } return 1; case EMU_REALAUDIO: /* * RealAudio emulation - JP. We must try to parse the incoming * data and try to find the two characters that contain the * port number. Then we redirect an udp port and replace the * number with the real port we got. * * The 1.0 beta versions of the player are not supported * any more. * * A typical packet for player version 1.0 (release version): * * 0000:50 4E 41 00 05 * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB * * Now the port number 0x1BD7 is found at offset 0x04 of the * Now the port number 0x1BD7 is found at offset 0x04 of the * second packet. This time we received five bytes first and * then the rest. You never know how many bytes you get. * * A typical packet for player version 2.0 (beta): * * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA............. * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0 * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/ * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas * 0040:65 2E 72 61 79 53 00 00 06 36 42 e.rayS...6B * * Port number 0x1BC1 is found at offset 0x0d. * * This is just a horrible switch statement. Variable ra tells * us where we're going. */ bptr = m->m_data; while (bptr < m->m_data + m->m_len) { uint16_t p; static int ra = 0; char ra_tbl[4]; ra_tbl[0] = 0x50; ra_tbl[1] = 0x4e; ra_tbl[2] = 0x41; ra_tbl[3] = 0; switch (ra) { case 0: case 2: case 3: if (*bptr++ != ra_tbl[ra]) { ra = 0; continue; } break; case 1: /* * We may get 0x50 several times, ignore them */ if (*bptr == 0x50) { ra = 1; bptr++; continue; } else if (*bptr++ != ra_tbl[ra]) { ra = 0; continue; } break; case 4: /* * skip version number */ bptr++; break; case 5: if (bptr == m->m_data + m->m_len - 1) return 1; /* We need two bytes */ /* * The difference between versions 1.0 and * 2.0 is here. For future versions of * the player this may need to be modified. */ if (*(bptr + 1) == 0x02) bptr += 8; else bptr += 4; break; case 6: /* This is the field containing the port * number that RA-player is listening to. */ if (bptr == m->m_data + m->m_len - 1) return 1; /* We need two bytes */ lport = (((uint8_t *)bptr)[0] << 8) + ((uint8_t *)bptr)[1]; if (lport < 6970) lport += 256; /* don't know why */ if (lport < 6970 || lport > 7170) return 1; /* failed */ /* try to get udp port between 6970 - 7170 */ for (p = 6970; p < 7071; p++) { if (udp_listen(slirp, INADDR_ANY, htons(p), so->so_laddr.s_addr, htons(lport), SS_FACCEPTONCE)) { break; } } if (p == 7071) p = 0; *(uint8_t *)bptr++ = (p >> 8) & 0xff; *(uint8_t *)bptr = p & 0xff; ra = 0; return 1; /* port redirected, we're done */ break; default: ra = 0; } ra++; } return 1; default: /* Ooops, not emulated, won't call tcp_emu again */ so->so_emu = 0; return 1; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'slirp: use correct size while emulating commands While emulating services in tcp_emu(), it uses 'mbuf' size 'm->m_size' to write commands via snprintf(3). Use M_FREEROOM(m) size to avoid possible OOB access. Signed-off-by: Prasad J Pandit <pjp@fedoraproject.org> Signed-off-by: Samuel Thibault <samuel.thibault@ens-lyon.org> Message-Id: <20200109094228.79764-3-ppandit@redhat.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int __feat_register_sp(struct list_head *fn, u8 feat, u8 is_local, u8 mandatory, u8 const *sp_val, u8 sp_len) { dccp_feat_val fval; if (dccp_feat_type(feat) != FEAT_SP || !dccp_feat_sp_list_ok(feat, sp_val, sp_len)) return -EINVAL; /* Avoid negotiating alien CCIDs by only advertising supported ones */ if (feat == DCCPF_CCID && !ccid_support_check(sp_val, sp_len)) return -EOPNOTSUPP; if (dccp_feat_clone_sp_val(&fval, sp_val, sp_len)) return -ENOMEM; return dccp_feat_push_change(fn, feat, is_local, mandatory, &fval); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-401'], 'message': 'dccp: Fix memleak in __feat_register_sp If dccp_feat_push_change fails, we forget free the mem which is alloced by kmemdup in dccp_feat_clone_sp_val. Reported-by: Hulk Robot <hulkci@huawei.com> Fixes: e8ef967a54f4 ("dccp: Registration routines for changing feature values") Reviewed-by: Mukesh Ojha <mojha@codeaurora.org> Signed-off-by: YueHaibing <yuehaibing@huawei.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static Image *ReadOneMNGImage(MngInfo* mng_info, const ImageInfo *image_info, ExceptionInfo *exception) { char page_geometry[MagickPathExtent]; Image *image; MagickBooleanType logging; volatile int first_mng_object, object_id, term_chunk_found, skip_to_iend; volatile ssize_t image_count=0; MagickBooleanType status; MagickOffsetType offset; MngBox default_fb, fb, previous_fb; #if defined(MNG_INSERT_LAYERS) PixelInfo mng_background_color; #endif register unsigned char *p; register ssize_t i; size_t count; ssize_t loop_level; volatile short skipping_loop; #if defined(MNG_INSERT_LAYERS) unsigned int mandatory_back=0; #endif volatile unsigned int #ifdef MNG_OBJECT_BUFFERS mng_background_object=0, #endif mng_type=0; /* 0: PNG or JNG; 1: MNG; 2: MNG-LC; 3: MNG-VLC */ size_t default_frame_timeout, frame_timeout, #if defined(MNG_INSERT_LAYERS) image_height, image_width, #endif length; /* These delays are all measured in image ticks_per_second, * not in MNG ticks_per_second */ volatile size_t default_frame_delay, final_delay, final_image_delay, frame_delay, #if defined(MNG_INSERT_LAYERS) insert_layers, #endif mng_iterations=1, simplicity=0, subframe_height=0, subframe_width=0; previous_fb.top=0; previous_fb.bottom=0; previous_fb.left=0; previous_fb.right=0; default_fb.top=0; default_fb.bottom=0; default_fb.left=0; default_fb.right=0; logging=LogMagickEvent(CoderEvent,GetMagickModule(), " Enter ReadOneMNGImage()"); image=mng_info->image; if (LocaleCompare(image_info->magick,"MNG") == 0) { char magic_number[MagickPathExtent]; /* Verify MNG signature. */ count=(size_t) ReadBlob(image,8,(unsigned char *) magic_number); if ((count < 8) || (memcmp(magic_number,"\212MNG\r\n\032\n",8) != 0)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize some nonzero members of the MngInfo structure. */ for (i=0; i < MNG_MAX_OBJECTS; i++) { mng_info->object_clip[i].right=(ssize_t) PNG_UINT_31_MAX; mng_info->object_clip[i].bottom=(ssize_t) PNG_UINT_31_MAX; } mng_info->exists[0]=MagickTrue; } skipping_loop=(-1); first_mng_object=MagickTrue; mng_type=0; #if defined(MNG_INSERT_LAYERS) insert_layers=MagickFalse; /* should be False during convert or mogrify */ #endif default_frame_delay=0; default_frame_timeout=0; frame_delay=0; final_delay=1; mng_info->ticks_per_second=1UL*image->ticks_per_second; object_id=0; skip_to_iend=MagickFalse; term_chunk_found=MagickFalse; mng_info->framing_mode=1; #if defined(MNG_INSERT_LAYERS) mandatory_back=MagickFalse; #endif #if defined(MNG_INSERT_LAYERS) mng_background_color=image->background_color; #endif default_fb=mng_info->frame; previous_fb=mng_info->frame; do { char type[MagickPathExtent]; if (LocaleCompare(image_info->magick,"MNG") == 0) { unsigned char *chunk; /* Read a new chunk. */ type[0]='\0'; (void) ConcatenateMagickString(type,"errr",MagickPathExtent); length=(size_t) ReadBlobMSBLong(image); count=(size_t) ReadBlob(image,4,(unsigned char *) type); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading MNG chunk type %c%c%c%c, length: %.20g", type[0],type[1],type[2],type[3],(double) length); if ((length > PNG_UINT_31_MAX) || (length > GetBlobSize(image)) || (count < 4)) ThrowReaderException(CorruptImageError,"CorruptImage"); p=NULL; chunk=(unsigned char *) NULL; if (length != 0) { chunk=(unsigned char *) AcquireQuantumMemory(length,sizeof(*chunk)); if (chunk == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) length; i++) { int c; c=ReadBlobByte(image); if (c == EOF) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } chunk[i]=(unsigned char) c; } p=chunk; } (void) ReadBlobMSBLong(image); /* read crc word */ #if !defined(JNG_SUPPORTED) if (memcmp(type,mng_JHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->jhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"JNGCompressNotSupported","`%s'",image->filename); mng_info->jhdr_warning++; } #endif if (memcmp(type,mng_DHDR,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->dhdr_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DeltaPNGNotSupported","`%s'",image->filename); mng_info->dhdr_warning++; } if (memcmp(type,mng_MEND,4) == 0) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); break; } if (skip_to_iend) { if (memcmp(type,mng_IEND,4) == 0) skip_to_iend=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skip to IEND."); continue; } if (memcmp(type,mng_MHDR,4) == 0) { if (length != 28) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } mng_info->mng_width=(unsigned long)mng_get_long(p); mng_info->mng_height=(unsigned long)mng_get_long(&p[4]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG width: %.20g",(double) mng_info->mng_width); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " MNG height: %.20g",(double) mng_info->mng_height); } p+=8; mng_info->ticks_per_second=(size_t) mng_get_long(p); if (mng_info->ticks_per_second == 0) default_frame_delay=0; else default_frame_delay=1UL*image->ticks_per_second/ mng_info->ticks_per_second; frame_delay=default_frame_delay; simplicity=0; p+=16; simplicity=(size_t) mng_get_long(p); mng_type=1; /* Full MNG */ if ((simplicity != 0) && ((simplicity | 11) == 11)) mng_type=2; /* LC */ if ((simplicity != 0) && ((simplicity | 9) == 9)) mng_type=3; /* VLC */ #if defined(MNG_INSERT_LAYERS) if (mng_type != 3) insert_layers=MagickTrue; #endif if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return((Image *) NULL); image=SyncNextImageInList(image); mng_info->image=image; } if ((mng_info->mng_width > 65535L) || (mng_info->mng_height > 65535L)) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ImageError,"WidthOrHeightExceedsLimit"); } (void) FormatLocaleString(page_geometry,MagickPathExtent, "%.20gx%.20g+0+0",(double) mng_info->mng_width,(double) mng_info->mng_height); mng_info->frame.left=0; mng_info->frame.right=(ssize_t) mng_info->mng_width; mng_info->frame.top=0; mng_info->frame.bottom=(ssize_t) mng_info->mng_height; mng_info->clip=default_fb=previous_fb=mng_info->frame; for (i=0; i < MNG_MAX_OBJECTS; i++) mng_info->object_clip[i]=mng_info->frame; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_TERM,4) == 0) { int repeat=0; if (length != 0) repeat=p[0]; if (repeat == 3 && length > 9) { final_delay=(png_uint_32) mng_get_long(&p[2]); mng_iterations=(png_uint_32) mng_get_long(&p[6]); if (mng_iterations == PNG_UINT_31_MAX) mng_iterations=0; image->iterations=mng_iterations; term_chunk_found=MagickTrue; } if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " repeat=%d, final_delay=%.20g, iterations=%.20g", repeat,(double) final_delay, (double) image->iterations); } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_DEFI,4) == 0) { if (mng_type == 3) { (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"DEFI chunk found in MNG-VLC datastream","`%s'", image->filename); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (length < 2) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"CorruptImage"); } object_id=((unsigned int) p[0] << 8) | (unsigned int) p[1]; if (mng_type == 2 && object_id != 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Nonzero object_id in MNG-LC datastream","`%s'", image->filename); if (object_id >= MNG_MAX_OBJECTS) { /* Instead of using a warning we should allocate a larger MngInfo structure and continue. */ (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"object id too large","`%s'",image->filename); object_id=MNG_MAX_OBJECTS-1; } if (mng_info->exists[object_id]) if (mng_info->frozen[object_id]) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "DEFI cannot redefine a frozen MNG object","`%s'", image->filename); continue; } mng_info->exists[object_id]=MagickTrue; if (length > 2) mng_info->invisible[object_id]=p[2]; /* Extract object offset info. */ if (length > 11) { mng_info->x_off[object_id]=(ssize_t) mng_get_long(&p[4]); mng_info->y_off[object_id]=(ssize_t) mng_get_long(&p[8]); if (logging != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), " x_off[%d]: %.20g, y_off[%d]: %.20g", object_id,(double) mng_info->x_off[object_id], object_id,(double) mng_info->y_off[object_id]); } } /* Extract object clipping info. */ if (length > 27) mng_info->object_clip[object_id]=mng_read_box(mng_info->frame,0, &p[12]); chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_bKGD,4) == 0) { mng_info->have_global_bkgd=MagickFalse; if (length > 5) { mng_info->mng_global_bkgd.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_info->mng_global_bkgd.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_info->mng_global_bkgd.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_info->have_global_bkgd=MagickTrue; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_BACK,4) == 0) { #if defined(MNG_INSERT_LAYERS) if (length > 6) mandatory_back=p[6]; else mandatory_back=0; if (mandatory_back && length > 5) { mng_background_color.red= ScaleShortToQuantum((unsigned short) ((p[0] << 8) | p[1])); mng_background_color.green= ScaleShortToQuantum((unsigned short) ((p[2] << 8) | p[3])); mng_background_color.blue= ScaleShortToQuantum((unsigned short) ((p[4] << 8) | p[5])); mng_background_color.alpha=OpaqueAlpha; } #ifdef MNG_OBJECT_BUFFERS if (length > 8) mng_background_object=(p[7] << 8) | p[8]; #endif #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_PLTE,4) == 0) { /* Read global PLTE. */ if (length && (length < 769)) { /* Read global PLTE. */ if (mng_info->global_plte == (png_colorp) NULL) mng_info->global_plte=(png_colorp) AcquireQuantumMemory(256, sizeof(*mng_info->global_plte)); if (mng_info->global_plte == (png_colorp) NULL) { mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } for (i=0; i < (ssize_t) (length/3); i++) { mng_info->global_plte[i].red=p[3*i]; mng_info->global_plte[i].green=p[3*i+1]; mng_info->global_plte[i].blue=p[3*i+2]; } mng_info->global_plte_length=(unsigned int) (length/3); } #ifdef MNG_LOOSE for ( ; i < 256; i++) { mng_info->global_plte[i].red=i; mng_info->global_plte[i].green=i; mng_info->global_plte[i].blue=i; } if (length != 0) mng_info->global_plte_length=256; #endif else mng_info->global_plte_length=0; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_tRNS,4) == 0) { /* read global tRNS */ if (length > 0 && length < 257) for (i=0; i < (ssize_t) length; i++) mng_info->global_trns[i]=p[i]; #ifdef MNG_LOOSE for ( ; i < 256; i++) mng_info->global_trns[i]=255; #endif mng_info->global_trns_length=(unsigned int) length; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_gAMA,4) == 0) { if (length == 4) { ssize_t igamma; igamma=mng_get_long(p); mng_info->global_gamma=((float) igamma)*0.00001; mng_info->have_global_gama=MagickTrue; } else mng_info->have_global_gama=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_cHRM,4) == 0) { /* Read global cHRM */ if (length == 32) { mng_info->global_chrm.white_point.x=0.00001*mng_get_long(p); mng_info->global_chrm.white_point.y=0.00001*mng_get_long(&p[4]); mng_info->global_chrm.red_primary.x=0.00001*mng_get_long(&p[8]); mng_info->global_chrm.red_primary.y=0.00001* mng_get_long(&p[12]); mng_info->global_chrm.green_primary.x=0.00001* mng_get_long(&p[16]); mng_info->global_chrm.green_primary.y=0.00001* mng_get_long(&p[20]); mng_info->global_chrm.blue_primary.x=0.00001* mng_get_long(&p[24]); mng_info->global_chrm.blue_primary.y=0.00001* mng_get_long(&p[28]); mng_info->have_global_chrm=MagickTrue; } else mng_info->have_global_chrm=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_sRGB,4) == 0) { /* Read global sRGB. */ if (length != 0) { mng_info->global_srgb_intent= Magick_RenderingIntent_from_PNG_RenderingIntent(p[0]); mng_info->have_global_srgb=MagickTrue; } else mng_info->have_global_srgb=MagickFalse; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_iCCP,4) == 0) { /* To do: */ /* Read global iCCP. */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_FRAM,4) == 0) { if (mng_type == 3) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"FRAM chunk found in MNG-VLC datastream","`%s'", image->filename); if ((mng_info->framing_mode == 2) || (mng_info->framing_mode == 4)) image->delay=frame_delay; frame_delay=default_frame_delay; frame_timeout=default_frame_timeout; fb=default_fb; if (length != 0) if (p[0]) mng_info->framing_mode=p[0]; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_mode=%d",mng_info->framing_mode); if (length > 6) { /* Note the delay and frame clipping boundaries. */ p++; /* framing mode */ while (((p-chunk) < (long) length) && *p) p++; /* frame name */ p++; /* frame name terminator */ if ((p-chunk) < (ssize_t) (length-4)) { int change_delay, change_timeout, change_clipping; change_delay=(*p++); change_timeout=(*p++); change_clipping=(*p++); p++; /* change_sync */ if (change_delay && ((p-chunk) < (ssize_t) (length-4))) { frame_delay=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_delay/=mng_info->ticks_per_second; else frame_delay=PNG_UINT_31_MAX; if (change_delay == 2) default_frame_delay=frame_delay; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_delay=%.20g",(double) frame_delay); } if (change_timeout && ((p-chunk) < (ssize_t) (length-4))) { frame_timeout=1UL*image->ticks_per_second* mng_get_long(p); if (mng_info->ticks_per_second != 0) frame_timeout/=mng_info->ticks_per_second; else frame_timeout=PNG_UINT_31_MAX; if (change_timeout == 2) default_frame_timeout=frame_timeout; p+=4; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Framing_timeout=%.20g",(double) frame_timeout); } if (change_clipping && ((p-chunk) < (ssize_t) (length-16))) { fb=mng_read_box(previous_fb,(char) p[0],&p[1]); p+=16; previous_fb=fb; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Frame_clip: L=%.20g R=%.20g T=%.20g B=%.20g", (double) fb.left,(double) fb.right,(double) fb.top, (double) fb.bottom); if (change_clipping == 2) default_fb=fb; } } } mng_info->clip=fb; mng_info->clip=mng_minimum_box(fb,mng_info->frame); subframe_width=(size_t) (mng_info->clip.right -mng_info->clip.left); subframe_height=(size_t) (mng_info->clip.bottom -mng_info->clip.top); /* Insert a background layer behind the frame if framing_mode is 4. */ #if defined(MNG_INSERT_LAYERS) if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " subframe_width=%.20g, subframe_height=%.20g",(double) subframe_width,(double) subframe_height); if (insert_layers && (mng_info->framing_mode == 4) && (subframe_width) && (subframe_height)) { /* Allocate next image structure. */ if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; image->delay=0; if (SetImageBackgroundColor(image,exception) == MagickFalse) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); return(DestroyImageList(image)); } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert backgd layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left, (double) mng_info->clip.right, (double) mng_info->clip.top, (double) mng_info->clip.bottom); } #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLIP,4) == 0) { unsigned int first_object, last_object; /* Read CLIP. */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(int) first_object; i <= (int) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i]) { MngBox box; box=mng_info->object_clip[i]; if ((p-chunk) < (ssize_t) (length-17)) mng_info->object_clip[i]= mng_read_box(box,(char) p[0],&p[1]); } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_SAVE,4) == 0) { for (i=1; i < MNG_MAX_OBJECTS; i++) if (mng_info->exists[i]) { mng_info->frozen[i]=MagickTrue; #ifdef MNG_OBJECT_BUFFERS if (mng_info->ob[i] != (MngBuffer *) NULL) mng_info->ob[i]->frozen=MagickTrue; #endif } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if ((memcmp(type,mng_DISC,4) == 0) || (memcmp(type,mng_SEEK,4) == 0)) { /* Read DISC or SEEK. */ if ((length == 0) || (length % 2) || !memcmp(type,mng_SEEK,4)) { for (i=1; i < MNG_MAX_OBJECTS; i++) MngInfoDiscardObject(mng_info,i); } else { register ssize_t j; for (j=1; j < (ssize_t) length; j+=2) { i=p[j-1] << 8 | p[j]; MngInfoDiscardObject(mng_info,i); } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_MOVE,4) == 0) { size_t first_object, last_object; /* read MOVE */ if (length > 3) { first_object=(p[0] << 8) | p[1]; last_object=(p[2] << 8) | p[3]; p+=4; for (i=(ssize_t) first_object; i <= (ssize_t) last_object; i++) { if ((i < 0) || (i >= MNG_MAX_OBJECTS)) continue; if (mng_info->exists[i] && !mng_info->frozen[i] && (p-chunk) < (ssize_t) (length-8)) { MngPair new_pair; MngPair old_pair; old_pair.a=mng_info->x_off[i]; old_pair.b=mng_info->y_off[i]; new_pair=mng_read_pair(old_pair,(int) p[0],&p[1]); mng_info->x_off[i]=new_pair.a; mng_info->y_off[i]=new_pair.b; } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_LOOP,4) == 0) { ssize_t loop_iters=1; if (length > 4) { loop_level=chunk[0]; mng_info->loop_active[loop_level]=1; /* mark loop active */ /* Record starting point. */ loop_iters=mng_get_long(&chunk[1]); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " LOOP level %.20g has %.20g iterations ", (double) loop_level, (double) loop_iters); if (loop_iters <= 0) skipping_loop=loop_level; else { if ((MagickSizeType) loop_iters > GetMagickResourceLimit(ListLengthResource)) loop_iters=GetMagickResourceLimit(ListLengthResource); if (loop_iters >= 2147483647L) loop_iters=2147483647L; mng_info->loop_jump[loop_level]=TellBlob(image); mng_info->loop_count[loop_level]=loop_iters; } mng_info->loop_iteration[loop_level]=0; } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_ENDL,4) == 0) { if (length > 0) { loop_level=chunk[0]; if (skipping_loop > 0) { if (skipping_loop == loop_level) { /* Found end of zero-iteration loop. */ skipping_loop=(-1); mng_info->loop_active[loop_level]=0; } } else { if (mng_info->loop_active[loop_level] == 1) { mng_info->loop_count[loop_level]--; mng_info->loop_iteration[loop_level]++; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " ENDL: LOOP level %.20g has %.20g remaining iters", (double) loop_level,(double) mng_info->loop_count[loop_level]); if (mng_info->loop_count[loop_level] > 0) { offset= SeekBlob(image,mng_info->loop_jump[loop_level], SEEK_SET); if (offset < 0) { chunk=(unsigned char *) RelinquishMagickMemory( chunk); ThrowReaderException(CorruptImageError, "ImproperImageHeader"); } } else { short last_level; /* Finished loop. */ mng_info->loop_active[loop_level]=0; last_level=(-1); for (i=0; i < loop_level; i++) if (mng_info->loop_active[i] == 1) last_level=(short) i; loop_level=last_level; } } } } chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_CLON,4) == 0) { if (mng_info->clon_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"CLON is not implemented yet","`%s'", image->filename); mng_info->clon_warning++; } if (memcmp(type,mng_MAGN,4) == 0) { png_uint_16 magn_first, magn_last, magn_mb, magn_ml, magn_mr, magn_mt, magn_mx, magn_my, magn_methx, magn_methy; if (length > 1) magn_first=(p[0] << 8) | p[1]; else magn_first=0; if (length > 3) magn_last=(p[2] << 8) | p[3]; else magn_last=magn_first; #ifndef MNG_OBJECT_BUFFERS if (magn_first || magn_last) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "MAGN is not implemented yet for nonzero objects", "`%s'",image->filename); mng_info->magn_warning++; } #endif if (length > 4) magn_methx=p[4]; else magn_methx=0; if (length > 6) magn_mx=(p[5] << 8) | p[6]; else magn_mx=1; if (magn_mx == 0) magn_mx=1; if (length > 8) magn_my=(p[7] << 8) | p[8]; else magn_my=magn_mx; if (magn_my == 0) magn_my=1; if (length > 10) magn_ml=(p[9] << 8) | p[10]; else magn_ml=magn_mx; if (magn_ml == 0) magn_ml=1; if (length > 12) magn_mr=(p[11] << 8) | p[12]; else magn_mr=magn_mx; if (magn_mr == 0) magn_mr=1; if (length > 14) magn_mt=(p[13] << 8) | p[14]; else magn_mt=magn_my; if (magn_mt == 0) magn_mt=1; if (length > 16) magn_mb=(p[15] << 8) | p[16]; else magn_mb=magn_my; if (magn_mb == 0) magn_mb=1; if (length > 17) magn_methy=p[17]; else magn_methy=magn_methx; if (magn_methx > 5 || magn_methy > 5) if (mng_info->magn_warning == 0) { (void) ThrowMagickException(exception, GetMagickModule(),CoderError, "Unknown MAGN method in MNG datastream","`%s'", image->filename); mng_info->magn_warning++; } #ifdef MNG_OBJECT_BUFFERS /* Magnify existing objects in the range magn_first to magn_last */ #endif if (magn_first == 0 || magn_last == 0) { /* Save the magnification factors for object 0 */ mng_info->magn_mb=magn_mb; mng_info->magn_ml=magn_ml; mng_info->magn_mr=magn_mr; mng_info->magn_mt=magn_mt; mng_info->magn_mx=magn_mx; mng_info->magn_my=magn_my; mng_info->magn_methx=magn_methx; mng_info->magn_methy=magn_methy; } } if (memcmp(type,mng_PAST,4) == 0) { if (mng_info->past_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"PAST is not implemented yet","`%s'", image->filename); mng_info->past_warning++; } if (memcmp(type,mng_SHOW,4) == 0) { if (mng_info->show_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"SHOW is not implemented yet","`%s'", image->filename); mng_info->show_warning++; } if (memcmp(type,mng_sBIT,4) == 0) { if (length < 4) mng_info->have_global_sbit=MagickFalse; else { mng_info->global_sbit.gray=p[0]; mng_info->global_sbit.red=p[0]; mng_info->global_sbit.green=p[1]; mng_info->global_sbit.blue=p[2]; mng_info->global_sbit.alpha=p[3]; mng_info->have_global_sbit=MagickTrue; } } if (memcmp(type,mng_pHYs,4) == 0) { if (length > 8) { mng_info->global_x_pixels_per_unit= (size_t) mng_get_long(p); mng_info->global_y_pixels_per_unit= (size_t) mng_get_long(&p[4]); mng_info->global_phys_unit_type=p[8]; mng_info->have_global_phys=MagickTrue; } else mng_info->have_global_phys=MagickFalse; } if (memcmp(type,mng_pHYg,4) == 0) { if (mng_info->phyg_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"pHYg is not implemented.","`%s'",image->filename); mng_info->phyg_warning++; } if (memcmp(type,mng_BASI,4) == 0) { skip_to_iend=MagickTrue; if (mng_info->basi_warning == 0) (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"BASI is not implemented yet","`%s'", image->filename); mng_info->basi_warning++; #ifdef MNG_BASI_SUPPORTED basi_width=(unsigned long) mng_get_long(p); basi_width=(unsigned long) mng_get_long(&p[4]); basi_color_type=p[8]; basi_compression_method=p[9]; basi_filter_type=p[10]; basi_interlace_method=p[11]; if (length > 11) basi_red=((png_uint_32) p[12] << 8) & (png_uint_32) p[13]; else basi_red=0; if (length > 13) basi_green=((png_uint_32) p[14] << 8) & (png_uint_32) p[15]; else basi_green=0; if (length > 15) basi_blue=((png_uint_32) p[16] << 8) & (png_uint_32) p[17]; else basi_blue=0; if (length > 17) basi_alpha=((png_uint_32) p[18] << 8) & (png_uint_32) p[19]; else { if (basi_sample_depth == 16) basi_alpha=65535L; else basi_alpha=255; } if (length > 19) basi_viewable=p[20]; else basi_viewable=0; #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } if (memcmp(type,mng_IHDR,4) #if defined(JNG_SUPPORTED) && memcmp(type,mng_JHDR,4) #endif ) { /* Not an IHDR or JHDR chunk */ chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } /* Process IHDR */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing %c%c%c%c chunk",type[0],type[1],type[2],type[3]); mng_info->exists[object_id]=MagickTrue; mng_info->viewable[object_id]=MagickTrue; if (mng_info->invisible[object_id]) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Skipping invisible object"); skip_to_iend=MagickTrue; chunk=(unsigned char *) RelinquishMagickMemory(chunk); continue; } #if defined(MNG_INSERT_LAYERS) if (length < 8) { chunk=(unsigned char *) RelinquishMagickMemory(chunk); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } image_width=(size_t) mng_get_long(p); image_height=(size_t) mng_get_long(&p[4]); #endif chunk=(unsigned char *) RelinquishMagickMemory(chunk); /* Insert a transparent background layer behind the entire animation if it is not full screen. */ #if defined(MNG_INSERT_LAYERS) if (insert_layers && mng_type && first_mng_object) { if ((mng_info->clip.left > 0) || (mng_info->clip.top > 0) || (image_width < mng_info->mng_width) || (mng_info->clip.right < (ssize_t) mng_info->mng_width) || (image_height < mng_info->mng_height) || (mng_info->clip.bottom < (ssize_t) mng_info->mng_height)) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; /* Make a background rectangle. */ image->delay=0; image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Inserted transparent background layer, W=%.20g, H=%.20g", (double) mng_info->mng_width,(double) mng_info->mng_height); } } /* Insert a background layer behind the upcoming image if framing_mode is 3, and we haven't already inserted one. */ if (insert_layers && (mng_info->framing_mode == 3) && (subframe_width) && (subframe_height) && (simplicity == 0 || (simplicity & 0x08))) { if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; if (term_chunk_found) { image->start_loop=MagickTrue; image->iterations=mng_iterations; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; image->delay=0; image->columns=subframe_width; image->rows=subframe_height; image->page.width=subframe_width; image->page.height=subframe_height; image->page.x=mng_info->clip.left; image->page.y=mng_info->clip.top; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; (void) SetImageBackgroundColor(image,exception); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Insert background layer, L=%.20g, R=%.20g T=%.20g, B=%.20g", (double) mng_info->clip.left,(double) mng_info->clip.right, (double) mng_info->clip.top,(double) mng_info->clip.bottom); } #endif /* MNG_INSERT_LAYERS */ first_mng_object=MagickFalse; if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); image=SyncNextImageInList(image); } mng_info->image=image; status=SetImageProgress(image,LoadImagesTag,TellBlob(image), GetBlobSize(image)); if (status == MagickFalse) break; if (term_chunk_found) { image->start_loop=MagickTrue; term_chunk_found=MagickFalse; } else image->start_loop=MagickFalse; if (mng_info->framing_mode == 1 || mng_info->framing_mode == 3) { image->delay=frame_delay; frame_delay=default_frame_delay; } else image->delay=0; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=mng_info->x_off[object_id]; image->page.y=mng_info->y_off[object_id]; image->iterations=mng_iterations; /* Seek back to the beginning of the IHDR or JHDR chunk's length field. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Seeking back to beginning of %c%c%c%c chunk",type[0],type[1], type[2],type[3]); offset=SeekBlob(image,-((ssize_t) length+12),SEEK_CUR); if (offset < 0) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } mng_info->image=image; mng_info->mng_type=mng_type; mng_info->object_id=object_id; if (memcmp(type,mng_IHDR,4) == 0) image=ReadOnePNGImage(mng_info,image_info,exception); #if defined(JNG_SUPPORTED) else image=ReadOneJNGImage(mng_info,image_info,exception); #endif if (image == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "exit ReadJNGImage() with error"); return((Image *) NULL); } if (image->columns == 0 || image->rows == 0) { (void) CloseBlob(image); return(DestroyImageList(image)); } mng_info->image=image; if (mng_type) { MngBox crop_box; if (((mng_info->magn_methx > 0) && (mng_info->magn_methx <= 5)) && ((mng_info->magn_methy > 0) && (mng_info->magn_methy <= 5))) { png_uint_32 magnified_height, magnified_width; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Processing MNG MAGN chunk"); if (mng_info->magn_methx == 1) { magnified_width=mng_info->magn_ml; if (image->columns > 1) magnified_width += mng_info->magn_mr; if (image->columns > 2) magnified_width += (png_uint_32) ((image->columns-2)*(mng_info->magn_mx)); } else { magnified_width=(png_uint_32) image->columns; if (image->columns > 1) magnified_width += mng_info->magn_ml-1; if (image->columns > 2) magnified_width += mng_info->magn_mr-1; if (image->columns > 3) magnified_width += (png_uint_32) ((image->columns-3)*(mng_info->magn_mx-1)); } if (mng_info->magn_methy == 1) { magnified_height=mng_info->magn_mt; if (image->rows > 1) magnified_height += mng_info->magn_mb; if (image->rows > 2) magnified_height += (png_uint_32) ((image->rows-2)*(mng_info->magn_my)); } else { magnified_height=(png_uint_32) image->rows; if (image->rows > 1) magnified_height += mng_info->magn_mt-1; if (image->rows > 2) magnified_height += mng_info->magn_mb-1; if (image->rows > 3) magnified_height += (png_uint_32) ((image->rows-3)*(mng_info->magn_my-1)); } if (magnified_height > image->rows || magnified_width > image->columns) { Image *large_image; int yy; Quantum *next, *prev; png_uint_16 magn_methx, magn_methy; ssize_t m, y; register Quantum *n, *q; register ssize_t x; /* Allocate next image structure. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocate magnified image"); AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) return(DestroyImageList(image)); large_image=SyncNextImageInList(image); large_image->columns=magnified_width; large_image->rows=magnified_height; magn_methx=mng_info->magn_methx; magn_methy=mng_info->magn_methy; #if (MAGICKCORE_QUANTUM_DEPTH > 16) #define QM unsigned short if (magn_methx != 1 || magn_methy != 1) { /* Scale pixels to unsigned shorts to prevent overflow of intermediate values of interpolations */ 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=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleQuantumToShort( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleQuantumToShort( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleQuantumToShort( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleQuantumToShort( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #else #define QM Quantum #endif if (image->alpha_trait != UndefinedPixelTrait) (void) SetImageBackgroundColor(large_image,exception); else { large_image->background_color.alpha=OpaqueAlpha; (void) SetImageBackgroundColor(large_image,exception); if (magn_methx == 4) magn_methx=2; if (magn_methx == 5) magn_methx=3; if (magn_methy == 4) magn_methy=2; if (magn_methy == 5) magn_methy=3; } /* magnify the rows into the right side of the large image */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the rows to %.20g", (double) large_image->rows); m=(ssize_t) mng_info->magn_mt; yy=0; length=(size_t) GetPixelChannels(image)*image->columns; next=(Quantum *) AcquireQuantumMemory(length,sizeof(*next)); prev=(Quantum *) AcquireQuantumMemory(length,sizeof(*prev)); if ((prev == (Quantum *) NULL) || (next == (Quantum *) NULL)) { if (prev != (Quantum *) NULL) prev=(Quantum *) RelinquishMagickMemory(prev); if (next != (Quantum *) NULL) next=(Quantum *) RelinquishMagickMemory(next); image=DestroyImageList(image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } n=GetAuthenticPixels(image,0,0,image->columns,1,exception); (void) memcpy(next,n,length); for (y=0; y < (ssize_t) image->rows; y++) { if (y == 0) m=(ssize_t) mng_info->magn_mt; else if (magn_methy > 1 && y == (ssize_t) image->rows-2) m=(ssize_t) mng_info->magn_mb; else if (magn_methy <= 1 && y == (ssize_t) image->rows-1) m=(ssize_t) mng_info->magn_mb; else if (magn_methy > 1 && y == (ssize_t) image->rows-1) m=1; else m=(ssize_t) mng_info->magn_my; n=prev; prev=next; next=n; if (y < (ssize_t) image->rows-1) { n=GetAuthenticPixels(image,0,y+1,image->columns,1, exception); (void) memcpy(next,n,length); } for (i=0; i < m; i++, yy++) { register Quantum *pixels; assert(yy < (ssize_t) large_image->rows); pixels=prev; n=next; q=GetAuthenticPixels(large_image,0,yy,large_image->columns, 1,exception); if (q == (Quantum *) NULL) break; q+=(large_image->columns-image->columns)* GetPixelChannels(large_image); for (x=(ssize_t) image->columns-1; x >= 0; x--) { /* To do: get color as function of indexes[x] */ /* if (image->storage_class == PseudoClass) { } */ if (magn_methy <= 1) { /* replicate previous */ SetPixelRed(large_image,GetPixelRed(image,pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else if (magn_methy == 2 || magn_methy == 4) { if (i == 0) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { /* Interpolate */ SetPixelRed(large_image,((QM) (((ssize_t) (2*i*(GetPixelRed(image,n) -GetPixelRed(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelRed(image,pixels)))),q); SetPixelGreen(large_image,((QM) (((ssize_t) (2*i*(GetPixelGreen(image,n) -GetPixelGreen(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelGreen(image,pixels)))),q); SetPixelBlue(large_image,((QM) (((ssize_t) (2*i*(GetPixelBlue(image,n) -GetPixelBlue(image,pixels)+m))/ ((ssize_t) (m*2)) +GetPixelBlue(image,pixels)))),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(large_image, ((QM) (((ssize_t) (2*i*(GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)+m)) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)))),q); } if (magn_methy == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); else SetPixelAlpha(large_image,GetPixelAlpha(image, n),q); } } else /* if (magn_methy == 3 || magn_methy == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(large_image,GetPixelRed(image, pixels),q); SetPixelGreen(large_image,GetPixelGreen(image, pixels),q); SetPixelBlue(large_image,GetPixelBlue(image, pixels),q); SetPixelAlpha(large_image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(large_image,GetPixelRed(image,n),q); SetPixelGreen(large_image,GetPixelGreen(image,n), q); SetPixelBlue(large_image,GetPixelBlue(image,n), q); SetPixelAlpha(large_image,GetPixelAlpha(image,n), q); } if (magn_methy == 5) { SetPixelAlpha(large_image,(QM) (((ssize_t) (2*i* (GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels)) +m))/((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } n+=GetPixelChannels(image); q+=GetPixelChannels(large_image); pixels+=GetPixelChannels(image); } /* x */ if (SyncAuthenticPixels(large_image,exception) == 0) break; } /* i */ } /* y */ prev=(Quantum *) RelinquishMagickMemory(prev); next=(Quantum *) RelinquishMagickMemory(next); length=image->columns; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Delete original image"); DeleteImageFromList(&image); image=large_image; mng_info->image=image; /* magnify the columns */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Magnify the columns to %.20g", (double) image->columns); for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *pixels; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) break; pixels=q+(image->columns-length)*GetPixelChannels(image); n=pixels+GetPixelChannels(image); for (x=(ssize_t) (image->columns-length); x < (ssize_t) image->columns; x++) { /* To do: Rewrite using Get/Set***PixelChannel() */ if (x == (ssize_t) (image->columns-length)) m=(ssize_t) mng_info->magn_ml; else if (magn_methx > 1 && x == (ssize_t) image->columns-2) m=(ssize_t) mng_info->magn_mr; else if (magn_methx <= 1 && x == (ssize_t) image->columns-1) m=(ssize_t) mng_info->magn_mr; else if (magn_methx > 1 && x == (ssize_t) image->columns-1) m=1; else m=(ssize_t) mng_info->magn_mx; for (i=0; i < m; i++) { if (magn_methx <= 1) { /* replicate previous */ SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } else if (magn_methx == 2 || magn_methx == 4) { if (i == 0) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image,pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image,pixels),q); } /* To do: Rewrite using Get/Set***PixelChannel() */ else { /* Interpolate */ SetPixelRed(image,(QM) ((2*i*( GetPixelRed(image,n) -GetPixelRed(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelRed(image,pixels)),q); SetPixelGreen(image,(QM) ((2*i*( GetPixelGreen(image,n) -GetPixelGreen(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelGreen(image,pixels)),q); SetPixelBlue(image,(QM) ((2*i*( GetPixelBlue(image,n) -GetPixelBlue(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelBlue(image,pixels)),q); if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,(QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m) /((ssize_t) (m*2))+ GetPixelAlpha(image,pixels)),q); } if (magn_methx == 4) { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelAlpha(image, GetPixelAlpha(image,pixels)+0,q); } else { SetPixelAlpha(image, GetPixelAlpha(image,n)+0,q); } } } else /* if (magn_methx == 3 || magn_methx == 5) */ { /* Replicate nearest */ if (i <= ((m+1) << 1)) { SetPixelRed(image,GetPixelRed(image,pixels),q); SetPixelGreen(image,GetPixelGreen(image, pixels),q); SetPixelBlue(image,GetPixelBlue(image,pixels),q); SetPixelAlpha(image,GetPixelAlpha(image, pixels),q); } else { SetPixelRed(image,GetPixelRed(image,n),q); SetPixelGreen(image,GetPixelGreen(image,n),q); SetPixelBlue(image,GetPixelBlue(image,n),q); SetPixelAlpha(image,GetPixelAlpha(image,n),q); } if (magn_methx == 5) { /* Interpolate */ SetPixelAlpha(image, (QM) ((2*i*( GetPixelAlpha(image,n) -GetPixelAlpha(image,pixels))+m)/ ((ssize_t) (m*2)) +GetPixelAlpha(image,pixels)),q); } } q+=GetPixelChannels(image); } n+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } #if (MAGICKCORE_QUANTUM_DEPTH > 16) if (magn_methx != 1 || magn_methy != 1) { /* Rescale pixels to Quantum */ 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=(ssize_t) image->columns-1; x >= 0; x--) { SetPixelRed(image,ScaleShortToQuantum( GetPixelRed(image,q)),q); SetPixelGreen(image,ScaleShortToQuantum( GetPixelGreen(image,q)),q); SetPixelBlue(image,ScaleShortToQuantum( GetPixelBlue(image,q)),q); SetPixelAlpha(image,ScaleShortToQuantum( GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } } #endif if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished MAGN processing"); } } /* Crop_box is with respect to the upper left corner of the MNG. */ crop_box.left=mng_info->image_box.left+mng_info->x_off[object_id]; crop_box.right=mng_info->image_box.right+mng_info->x_off[object_id]; crop_box.top=mng_info->image_box.top+mng_info->y_off[object_id]; crop_box.bottom=mng_info->image_box.bottom+mng_info->y_off[object_id]; crop_box=mng_minimum_box(crop_box,mng_info->clip); crop_box=mng_minimum_box(crop_box,mng_info->frame); crop_box=mng_minimum_box(crop_box,mng_info->object_clip[object_id]); if ((crop_box.left != (mng_info->image_box.left +mng_info->x_off[object_id])) || (crop_box.right != (mng_info->image_box.right +mng_info->x_off[object_id])) || (crop_box.top != (mng_info->image_box.top +mng_info->y_off[object_id])) || (crop_box.bottom != (mng_info->image_box.bottom +mng_info->y_off[object_id]))) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Crop the PNG image"); if ((crop_box.left < crop_box.right) && (crop_box.top < crop_box.bottom)) { Image *im; RectangleInfo crop_info; /* Crop_info is with respect to the upper left corner of the image. */ crop_info.x=(crop_box.left-mng_info->x_off[object_id]); crop_info.y=(crop_box.top-mng_info->y_off[object_id]); crop_info.width=(size_t) (crop_box.right-crop_box.left); crop_info.height=(size_t) (crop_box.bottom-crop_box.top); image->page.width=image->columns; image->page.height=image->rows; image->page.x=0; image->page.y=0; im=CropImage(image,&crop_info,exception); if (im != (Image *) NULL) { image->columns=im->columns; image->rows=im->rows; im=DestroyImage(im); image->page.width=image->columns; image->page.height=image->rows; image->page.x=crop_box.left; image->page.y=crop_box.top; } } else { /* No pixels in crop area. The MNG spec still requires a layer, though, so make a single transparent pixel in the top left corner. */ image->columns=1; image->rows=1; image->colors=2; (void) SetImageBackgroundColor(image,exception); image->page.width=1; image->page.height=1; image->page.x=0; image->page.y=0; } } #ifndef PNG_READ_EMPTY_PLTE_SUPPORTED image=mng_info->image; #endif } #if (MAGICKCORE_QUANTUM_DEPTH > 16) /* PNG does not handle depths greater than 16 so reduce it even * if lossy. */ if (image->depth > 16) image->depth=16; #endif #if (MAGICKCORE_QUANTUM_DEPTH > 8) if (image->depth > 8) { /* To do: fill low byte properly */ image->depth=16; } if (LosslessReduceDepthOK(image,exception) != MagickFalse) image->depth = 8; #endif if (image_info->number_scenes != 0) { if (mng_info->scenes_found > (ssize_t) (image_info->first_scene+image_info->number_scenes)) break; } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading image datastream."); } while (LocaleCompare(image_info->magick,"MNG") == 0); (void) CloseBlob(image); if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Finished reading all image datastreams."); #if defined(MNG_INSERT_LAYERS) if (insert_layers && !mng_info->image_found && (mng_info->mng_width) && (mng_info->mng_height)) { /* Insert a background layer if nothing else was found. */ if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No images found. Inserting a background layer."); if (GetAuthenticPixelQueue(image) != (Quantum *) NULL) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Allocation failed, returning NULL."); return(DestroyImageList(image));; } image=SyncNextImageInList(image); } image->columns=mng_info->mng_width; image->rows=mng_info->mng_height; image->page.width=mng_info->mng_width; image->page.height=mng_info->mng_height; image->page.x=0; image->page.y=0; image->background_color=mng_background_color; image->alpha_trait=UndefinedPixelTrait; if (image_info->ping == MagickFalse) (void) SetImageBackgroundColor(image,exception); mng_info->image_found++; } #endif image->iterations=mng_iterations; if (mng_iterations == 1) image->start_loop=MagickTrue; while (GetPreviousImageInList(image) != (Image *) NULL) { image_count++; if (image_count > 10*mng_info->image_found) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," No beginning"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted, beginning of list not found", "`%s'",image_info->filename); return(DestroyImageList(image)); } image=GetPreviousImageInList(image); if (GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule()," Corrupt list"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"Linked list is corrupted; next_image is NULL","`%s'", image_info->filename); } } if (mng_info->ticks_per_second && mng_info->image_found > 1 && GetNextImageInList(image) == (Image *) NULL) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " First image null"); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"image->next for first image is NULL but shouldn't be.", "`%s'",image_info->filename); } if (mng_info->image_found == 0) { if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " No visible images found."); (void) ThrowMagickException(exception,GetMagickModule(), CoderError,"No visible images in file","`%s'",image_info->filename); return(DestroyImageList(image)); } if (mng_info->ticks_per_second) final_delay=1UL*MagickMax(image->ticks_per_second,1L)* final_delay/mng_info->ticks_per_second; else image->start_loop=MagickTrue; /* Find final nonzero image delay */ final_image_delay=0; while (GetNextImageInList(image) != (Image *) NULL) { if (image->delay) final_image_delay=image->delay; image=GetNextImageInList(image); } if (final_delay < final_image_delay) final_delay=final_image_delay; image->delay=final_delay; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image->delay=%.20g, final_delay=%.20g",(double) image->delay, (double) final_delay); if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Before coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g",(double) image->delay); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g",(double) scene++, (double) image->delay); } } image=GetFirstImageInList(image); #ifdef MNG_COALESCE_LAYERS if (insert_layers && image->next) { Image *next_image, *next; size_t scene; if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Coalesce Images"); scene=image->scene; next_image=CoalesceImages(image,exception); image=DestroyImageList(image); if (next_image == (Image *) NULL) { mng_info=MngInfoFreeStruct(mng_info); return((Image *) NULL); } image=next_image; for (next=image; next != (Image *) NULL; next=next_image) { next->page.width=mng_info->mng_width; next->page.height=mng_info->mng_height; next->page.x=0; next->page.y=0; next->scene=scene++; next_image=GetNextImageInList(next); if (next_image == (Image *) NULL) break; if (next->delay == 0) { scene--; next_image->previous=GetPreviousImageInList(next); if (GetPreviousImageInList(next) == (Image *) NULL) image=next_image; else next->previous->next=next_image; next=DestroyImage(next); } } } #endif while (GetNextImageInList(image) != (Image *) NULL) image=GetNextImageInList(image); image->dispose=BackgroundDispose; if (logging != MagickFalse) { int scene; scene=0; image=GetFirstImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " After coalesce:"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene 0 delay=%.20g dispose=%.20g",(double) image->delay, (double) image->dispose); while (GetNextImageInList(image) != (Image *) NULL) { image=GetNextImageInList(image); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " scene %.20g delay=%.20g dispose=%.20g",(double) scene++, (double) image->delay,(double) image->dispose); } } if (logging != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " exit ReadOneMNGImage();"); return(image); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'Removed invalid free reported in #1791.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: Magick_png_write_raw_profile(const ImageInfo *image_info,png_struct *ping, png_info *ping_info, unsigned char *profile_type, unsigned char *profile_description, unsigned char *profile_data, png_uint_32 length) { png_textp text; register ssize_t i; unsigned char *sp; png_charp dp; png_uint_32 allocated_length, description_length; unsigned char hex[16]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; if (LocaleNCompare((char *) profile_type+1, "ng-chunk-",9) == 0) return; if (image_info->verbose) { (void) printf("writing raw profile: type=%s, length=%.20g\n", (char *) profile_type, (double) length); } #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 description_length=(png_uint_32) strlen((const char *) profile_description); allocated_length=(png_uint_32) (length*2 + (length >> 5) + 20 + description_length); #if PNG_LIBPNG_VER >= 10400 text[0].text=(png_charp) png_malloc(ping, (png_alloc_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_alloc_size_t) 80); #else text[0].text=(png_charp) png_malloc(ping, (png_size_t) allocated_length); text[0].key=(png_charp) png_malloc(ping, (png_size_t) 80); #endif text[0].key[0]='\0'; (void) ConcatenateMagickString(text[0].key, "Raw profile type ",MaxTextExtent); (void) ConcatenateMagickString(text[0].key,(const char *) profile_type,62); sp=profile_data; dp=text[0].text; *dp++='\n'; (void) CopyMagickString(dp,(const char *) profile_description, allocated_length); dp+=description_length; *dp++='\n'; (void) FormatLocaleString(dp,allocated_length- (png_size_t) (dp-text[0].text),"%8lu ",(unsigned long) length); dp+=8; for (i=0; i < (ssize_t) length; i++) { if (i%36 == 0) *dp++='\n'; *(dp++)=(char) hex[((*sp >> 4) & 0x0f)]; *(dp++)=(char) hex[((*sp++ ) & 0x0f)]; } *dp++='\n'; *dp='\0'; text[0].text_length=(png_size_t) (dp-text[0].text); text[0].compression=image_info->compression == NoCompression || (image_info->compression == UndefinedCompression && text[0].text_length < 128) ? -1 : 0; if (text[0].text_length <= allocated_length) png_set_text(ping,ping_info,text,1); png_free(ping,text[0].text); png_free(ping,text[0].key); png_free(ping,text); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1561'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags) { u64 runtime, runtime_expires; int throttled; /* no need to continue the timer with no bandwidth constraint */ if (cfs_b->quota == RUNTIME_INF) goto out_deactivate; throttled = !list_empty(&cfs_b->throttled_cfs_rq); cfs_b->nr_periods += overrun; /* * idle depends on !throttled (for the case of a large deficit), and if * we're going inactive then everything else can be deferred */ if (cfs_b->idle && !throttled) goto out_deactivate; __refill_cfs_bandwidth_runtime(cfs_b); if (!throttled) { /* mark as potentially idle for the upcoming period */ cfs_b->idle = 1; return 0; } /* account preceding periods in which throttling occurred */ cfs_b->nr_throttled += overrun; runtime_expires = cfs_b->runtime_expires; /* * This check is repeated as we are holding onto the new bandwidth while * we unthrottle. This can potentially race with an unthrottled group * trying to acquire new bandwidth from the global pool. This can result * in us over-using our runtime if it is all used during this loop, but * only by limited amounts in that extreme case. */ while (throttled && cfs_b->runtime > 0 && !cfs_b->distribute_running) { runtime = cfs_b->runtime; cfs_b->distribute_running = 1; raw_spin_unlock_irqrestore(&cfs_b->lock, flags); /* we can't nest cfs_b->lock while distributing bandwidth */ runtime = distribute_cfs_runtime(cfs_b, runtime, runtime_expires); raw_spin_lock_irqsave(&cfs_b->lock, flags); cfs_b->distribute_running = 0; throttled = !list_empty(&cfs_b->throttled_cfs_rq); lsub_positive(&cfs_b->runtime, runtime); } /* * While we are ensured activity in the period following an * unthrottle, this also covers the case in which the new bandwidth is * insufficient to cover the existing bandwidth deficit. (Forcing the * timer to remain active while there are any throttled entities.) */ cfs_b->idle = 0; return 0; out_deactivate: return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices It has been observed, that highly-threaded, non-cpu-bound applications running under cpu.cfs_quota_us constraints can hit a high percentage of periods throttled while simultaneously not consuming the allocated amount of quota. This use case is typical of user-interactive non-cpu bound applications, such as those running in kubernetes or mesos when run on multiple cpu cores. This has been root caused to cpu-local run queue being allocated per cpu bandwidth slices, and then not fully using that slice within the period. At which point the slice and quota expires. This expiration of unused slice results in applications not being able to utilize the quota for which they are allocated. The non-expiration of per-cpu slices was recently fixed by 'commit 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition")'. Prior to that it appears that this had been broken since at least 'commit 51f2176d74ac ("sched/fair: Fix unlocked reads of some cfs_b->quota/period")' which was introduced in v3.16-rc1 in 2014. That added the following conditional which resulted in slices never being expired. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) { /* extend local deadline, drift is bounded above by 2 ticks */ cfs_rq->runtime_expires += TICK_NSEC; Because this was broken for nearly 5 years, and has recently been fixed and is now being noticed by many users running kubernetes (https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion that the mechanisms around expiring runtime should be removed altogether. This allows quota already allocated to per-cpu run-queues to live longer than the period boundary. This allows threads on runqueues that do not use much CPU to continue to use their remaining slice over a longer period of time than cpu.cfs_period_us. However, this helps prevent the above condition of hitting throttling while also not fully utilizing your cpu quota. This theoretically allows a machine to use slightly more than its allotted quota in some periods. This overflow would be bounded by the remaining quota left on each per-cpu runqueueu. This is typically no more than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will change nothing, as they should theoretically fully utilize all of their quota in each period. For user-interactive tasks as described above this provides a much better user/application experience as their cpu utilization will more closely match the amount they requested when they hit throttling. This means that cpu limits no longer strictly apply per period for non-cpu bound applications, but that they are still accurate over longer timeframes. This greatly improves performance of high-thread-count, non-cpu bound applications with low cfs_quota_us allocation on high-core-count machines. In the case of an artificial testcase (10ms/100ms of quota on 80 CPU machine), this commit resulted in almost 30x performance improvement, while still maintaining correct cpu quota restrictions. That testcase is available at https://github.com/indeedeng/fibtest. Fixes: 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition") Signed-off-by: Dave Chiluk <chiluk+linux@indeed.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Reviewed-by: Phil Auld <pauld@redhat.com> Reviewed-by: Ben Segall <bsegall@google.com> Cc: Ingo Molnar <mingo@redhat.com> Cc: John Hammond <jhammond@indeed.com> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Kyle Anderson <kwa@yelp.com> Cc: Gabriel Munos <gmunoz@netflix.com> Cc: Peter Oskolkov <posk@posk.io> Cc: Cong Wang <xiyou.wangcong@gmail.com> Cc: Brendan Gregg <bgregg@netflix.com> Link: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static u64 distribute_cfs_runtime(struct cfs_bandwidth *cfs_b, u64 remaining, u64 expires) { struct cfs_rq *cfs_rq; u64 runtime; u64 starting_runtime = remaining; rcu_read_lock(); list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq, throttled_list) { struct rq *rq = rq_of(cfs_rq); struct rq_flags rf; rq_lock_irqsave(rq, &rf); if (!cfs_rq_throttled(cfs_rq)) goto next; runtime = -cfs_rq->runtime_remaining + 1; if (runtime > remaining) runtime = remaining; remaining -= runtime; cfs_rq->runtime_remaining += runtime; cfs_rq->runtime_expires = expires; /* we check whether we're throttled above */ if (cfs_rq->runtime_remaining > 0) unthrottle_cfs_rq(cfs_rq); next: rq_unlock_irqrestore(rq, &rf); if (!remaining) break; } rcu_read_unlock(); return starting_runtime - remaining; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices It has been observed, that highly-threaded, non-cpu-bound applications running under cpu.cfs_quota_us constraints can hit a high percentage of periods throttled while simultaneously not consuming the allocated amount of quota. This use case is typical of user-interactive non-cpu bound applications, such as those running in kubernetes or mesos when run on multiple cpu cores. This has been root caused to cpu-local run queue being allocated per cpu bandwidth slices, and then not fully using that slice within the period. At which point the slice and quota expires. This expiration of unused slice results in applications not being able to utilize the quota for which they are allocated. The non-expiration of per-cpu slices was recently fixed by 'commit 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition")'. Prior to that it appears that this had been broken since at least 'commit 51f2176d74ac ("sched/fair: Fix unlocked reads of some cfs_b->quota/period")' which was introduced in v3.16-rc1 in 2014. That added the following conditional which resulted in slices never being expired. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) { /* extend local deadline, drift is bounded above by 2 ticks */ cfs_rq->runtime_expires += TICK_NSEC; Because this was broken for nearly 5 years, and has recently been fixed and is now being noticed by many users running kubernetes (https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion that the mechanisms around expiring runtime should be removed altogether. This allows quota already allocated to per-cpu run-queues to live longer than the period boundary. This allows threads on runqueues that do not use much CPU to continue to use their remaining slice over a longer period of time than cpu.cfs_period_us. However, this helps prevent the above condition of hitting throttling while also not fully utilizing your cpu quota. This theoretically allows a machine to use slightly more than its allotted quota in some periods. This overflow would be bounded by the remaining quota left on each per-cpu runqueueu. This is typically no more than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will change nothing, as they should theoretically fully utilize all of their quota in each period. For user-interactive tasks as described above this provides a much better user/application experience as their cpu utilization will more closely match the amount they requested when they hit throttling. This means that cpu limits no longer strictly apply per period for non-cpu bound applications, but that they are still accurate over longer timeframes. This greatly improves performance of high-thread-count, non-cpu bound applications with low cfs_quota_us allocation on high-core-count machines. In the case of an artificial testcase (10ms/100ms of quota on 80 CPU machine), this commit resulted in almost 30x performance improvement, while still maintaining correct cpu quota restrictions. That testcase is available at https://github.com/indeedeng/fibtest. Fixes: 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition") Signed-off-by: Dave Chiluk <chiluk+linux@indeed.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Reviewed-by: Phil Auld <pauld@redhat.com> Reviewed-by: Ben Segall <bsegall@google.com> Cc: Ingo Molnar <mingo@redhat.com> Cc: John Hammond <jhammond@indeed.com> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Kyle Anderson <kwa@yelp.com> Cc: Gabriel Munos <gmunoz@netflix.com> Cc: Peter Oskolkov <posk@posk.io> Cc: Cong Wang <xiyou.wangcong@gmail.com> Cc: Brendan Gregg <bgregg@netflix.com> Link: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq) { struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime; if (slack_runtime <= 0) return; raw_spin_lock(&cfs_b->lock); if (cfs_b->quota != RUNTIME_INF && cfs_rq->runtime_expires == cfs_b->runtime_expires) { cfs_b->runtime += slack_runtime; /* we are under rq->lock, defer unthrottling using a timer */ if (cfs_b->runtime > sched_cfs_bandwidth_slice() && !list_empty(&cfs_b->throttled_cfs_rq)) start_cfs_slack_bandwidth(cfs_b); } raw_spin_unlock(&cfs_b->lock); /* even if it's not valid for return we don't want to try again */ cfs_rq->runtime_remaining -= slack_runtime; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices It has been observed, that highly-threaded, non-cpu-bound applications running under cpu.cfs_quota_us constraints can hit a high percentage of periods throttled while simultaneously not consuming the allocated amount of quota. This use case is typical of user-interactive non-cpu bound applications, such as those running in kubernetes or mesos when run on multiple cpu cores. This has been root caused to cpu-local run queue being allocated per cpu bandwidth slices, and then not fully using that slice within the period. At which point the slice and quota expires. This expiration of unused slice results in applications not being able to utilize the quota for which they are allocated. The non-expiration of per-cpu slices was recently fixed by 'commit 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition")'. Prior to that it appears that this had been broken since at least 'commit 51f2176d74ac ("sched/fair: Fix unlocked reads of some cfs_b->quota/period")' which was introduced in v3.16-rc1 in 2014. That added the following conditional which resulted in slices never being expired. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) { /* extend local deadline, drift is bounded above by 2 ticks */ cfs_rq->runtime_expires += TICK_NSEC; Because this was broken for nearly 5 years, and has recently been fixed and is now being noticed by many users running kubernetes (https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion that the mechanisms around expiring runtime should be removed altogether. This allows quota already allocated to per-cpu run-queues to live longer than the period boundary. This allows threads on runqueues that do not use much CPU to continue to use their remaining slice over a longer period of time than cpu.cfs_period_us. However, this helps prevent the above condition of hitting throttling while also not fully utilizing your cpu quota. This theoretically allows a machine to use slightly more than its allotted quota in some periods. This overflow would be bounded by the remaining quota left on each per-cpu runqueueu. This is typically no more than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will change nothing, as they should theoretically fully utilize all of their quota in each period. For user-interactive tasks as described above this provides a much better user/application experience as their cpu utilization will more closely match the amount they requested when they hit throttling. This means that cpu limits no longer strictly apply per period for non-cpu bound applications, but that they are still accurate over longer timeframes. This greatly improves performance of high-thread-count, non-cpu bound applications with low cfs_quota_us allocation on high-core-count machines. In the case of an artificial testcase (10ms/100ms of quota on 80 CPU machine), this commit resulted in almost 30x performance improvement, while still maintaining correct cpu quota restrictions. That testcase is available at https://github.com/indeedeng/fibtest. Fixes: 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition") Signed-off-by: Dave Chiluk <chiluk+linux@indeed.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Reviewed-by: Phil Auld <pauld@redhat.com> Reviewed-by: Ben Segall <bsegall@google.com> Cc: Ingo Molnar <mingo@redhat.com> Cc: John Hammond <jhammond@indeed.com> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Kyle Anderson <kwa@yelp.com> Cc: Gabriel Munos <gmunoz@netflix.com> Cc: Peter Oskolkov <posk@posk.io> Cc: Cong Wang <xiyou.wangcong@gmail.com> Cc: Brendan Gregg <bgregg@netflix.com> Link: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq) { struct task_group *tg = cfs_rq->tg; struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(tg); u64 amount = 0, min_amount, expires; int expires_seq; /* note: this is a positive sum as runtime_remaining <= 0 */ min_amount = sched_cfs_bandwidth_slice() - cfs_rq->runtime_remaining; raw_spin_lock(&cfs_b->lock); if (cfs_b->quota == RUNTIME_INF) amount = min_amount; else { start_cfs_bandwidth(cfs_b); if (cfs_b->runtime > 0) { amount = min(cfs_b->runtime, min_amount); cfs_b->runtime -= amount; cfs_b->idle = 0; } } expires_seq = cfs_b->expires_seq; expires = cfs_b->runtime_expires; raw_spin_unlock(&cfs_b->lock); cfs_rq->runtime_remaining += amount; /* * we may have advanced our local expiration to account for allowed * spread between our sched_clock and the one on which runtime was * issued. */ if (cfs_rq->expires_seq != expires_seq) { cfs_rq->expires_seq = expires_seq; cfs_rq->runtime_expires = expires; } return cfs_rq->runtime_remaining > 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'sched/fair: Fix low cpu usage with high throttling by removing expiration of cpu-local slices It has been observed, that highly-threaded, non-cpu-bound applications running under cpu.cfs_quota_us constraints can hit a high percentage of periods throttled while simultaneously not consuming the allocated amount of quota. This use case is typical of user-interactive non-cpu bound applications, such as those running in kubernetes or mesos when run on multiple cpu cores. This has been root caused to cpu-local run queue being allocated per cpu bandwidth slices, and then not fully using that slice within the period. At which point the slice and quota expires. This expiration of unused slice results in applications not being able to utilize the quota for which they are allocated. The non-expiration of per-cpu slices was recently fixed by 'commit 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition")'. Prior to that it appears that this had been broken since at least 'commit 51f2176d74ac ("sched/fair: Fix unlocked reads of some cfs_b->quota/period")' which was introduced in v3.16-rc1 in 2014. That added the following conditional which resulted in slices never being expired. if (cfs_rq->runtime_expires != cfs_b->runtime_expires) { /* extend local deadline, drift is bounded above by 2 ticks */ cfs_rq->runtime_expires += TICK_NSEC; Because this was broken for nearly 5 years, and has recently been fixed and is now being noticed by many users running kubernetes (https://github.com/kubernetes/kubernetes/issues/67577) it is my opinion that the mechanisms around expiring runtime should be removed altogether. This allows quota already allocated to per-cpu run-queues to live longer than the period boundary. This allows threads on runqueues that do not use much CPU to continue to use their remaining slice over a longer period of time than cpu.cfs_period_us. However, this helps prevent the above condition of hitting throttling while also not fully utilizing your cpu quota. This theoretically allows a machine to use slightly more than its allotted quota in some periods. This overflow would be bounded by the remaining quota left on each per-cpu runqueueu. This is typically no more than min_cfs_rq_runtime=1ms per cpu. For CPU bound tasks this will change nothing, as they should theoretically fully utilize all of their quota in each period. For user-interactive tasks as described above this provides a much better user/application experience as their cpu utilization will more closely match the amount they requested when they hit throttling. This means that cpu limits no longer strictly apply per period for non-cpu bound applications, but that they are still accurate over longer timeframes. This greatly improves performance of high-thread-count, non-cpu bound applications with low cfs_quota_us allocation on high-core-count machines. In the case of an artificial testcase (10ms/100ms of quota on 80 CPU machine), this commit resulted in almost 30x performance improvement, while still maintaining correct cpu quota restrictions. That testcase is available at https://github.com/indeedeng/fibtest. Fixes: 512ac999d275 ("sched/fair: Fix bandwidth timer clock drift condition") Signed-off-by: Dave Chiluk <chiluk+linux@indeed.com> Signed-off-by: Peter Zijlstra (Intel) <peterz@infradead.org> Reviewed-by: Phil Auld <pauld@redhat.com> Reviewed-by: Ben Segall <bsegall@google.com> Cc: Ingo Molnar <mingo@redhat.com> Cc: John Hammond <jhammond@indeed.com> Cc: Jonathan Corbet <corbet@lwn.net> Cc: Kyle Anderson <kwa@yelp.com> Cc: Gabriel Munos <gmunoz@netflix.com> Cc: Peter Oskolkov <posk@posk.io> Cc: Cong Wang <xiyou.wangcong@gmail.com> Cc: Brendan Gregg <bgregg@netflix.com> Link: https://lkml.kernel.org/r/1563900266-19734-2-git-send-email-chiluk+linux@indeed.com'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static MagickBooleanType WriteSGIImage(const ImageInfo *image_info,Image *image) { CompressionType compression; const char *value; MagickBooleanType status; MagickOffsetType scene; MagickSizeType number_pixels; MemoryInfo *pixel_info; SGIInfo iris_info; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; size_t imageListLength; ssize_t y, z; unsigned char *pixels, *packets; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->columns > 65535UL) || (image->rows > 65535UL)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); scene=0; imageListLength=GetImageListLength(image); do { /* Initialize SGI raster file header. */ (void) TransformImageColorspace(image,sRGBColorspace); (void) memset(&iris_info,0,sizeof(iris_info)); iris_info.magic=0x01DA; compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (image->depth > 8) compression=NoCompression; if (compression == NoCompression) iris_info.storage=(unsigned char) 0x00; else iris_info.storage=(unsigned char) 0x01; iris_info.bytes_per_pixel=(unsigned char) (image->depth > 8 ? 2 : 1); iris_info.dimension=3; iris_info.columns=(unsigned short) image->columns; iris_info.rows=(unsigned short) image->rows; if (image->matte != MagickFalse) iris_info.depth=4; else { if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { iris_info.dimension=2; iris_info.depth=1; } else iris_info.depth=3; } iris_info.minimum_value=0; iris_info.maximum_value=(size_t) (image->depth <= 8 ? 1UL*ScaleQuantumToChar(QuantumRange) : 1UL*ScaleQuantumToShort(QuantumRange)); /* Write SGI header. */ (void) WriteBlobMSBShort(image,iris_info.magic); (void) WriteBlobByte(image,iris_info.storage); (void) WriteBlobByte(image,iris_info.bytes_per_pixel); (void) WriteBlobMSBShort(image,iris_info.dimension); (void) WriteBlobMSBShort(image,iris_info.columns); (void) WriteBlobMSBShort(image,iris_info.rows); (void) WriteBlobMSBShort(image,iris_info.depth); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.minimum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.maximum_value); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.sans); value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) CopyMagickString(iris_info.name,value,sizeof(iris_info.name)); (void) WriteBlob(image,sizeof(iris_info.name),(unsigned char *) iris_info.name); (void) WriteBlobMSBLong(image,(unsigned int) iris_info.pixel_format); (void) WriteBlob(image,sizeof(iris_info.filler),iris_info.filler); /* Allocate SGI pixels. */ number_pixels=(MagickSizeType) image->columns*image->rows; if ((4*iris_info.bytes_per_pixel*number_pixels) != ((MagickSizeType) (size_t) (4*iris_info.bytes_per_pixel*number_pixels))) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixel_info=AcquireVirtualMemory((size_t) number_pixels,4* iris_info.bytes_per_pixel*sizeof(*pixels)); if (pixel_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=(unsigned char *) GetVirtualMemoryBlob(pixel_info); /* Convert image pixels to uncompressed SGI pixels. */ for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; if (image->depth <= 8) for (x=0; x < (ssize_t) image->columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToChar(GetPixelRed(p)); *q++=ScaleQuantumToChar(GetPixelGreen(p)); *q++=ScaleQuantumToChar(GetPixelBlue(p)); *q++=ScaleQuantumToChar(GetPixelAlpha(p)); p++; } else for (x=0; x < (ssize_t) image->columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=((iris_info.rows-1)-y)*(4*iris_info.columns)+4*x; *q++=ScaleQuantumToShort(GetPixelRed(p)); *q++=ScaleQuantumToShort(GetPixelGreen(p)); *q++=ScaleQuantumToShort(GetPixelBlue(p)); *q++=ScaleQuantumToShort(GetPixelAlpha(p)); p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } switch (compression) { case NoCompression: { /* Write uncompressed SGI pixels. */ for (z=0; z < (ssize_t) iris_info.depth; z++) { for (y=0; y < (ssize_t) iris_info.rows; y++) { if (image->depth <= 8) for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned char *q; q=(unsigned char *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobByte(image,*q); } else for (x=0; x < (ssize_t) iris_info.columns; x++) { register unsigned short *q; q=(unsigned short *) pixels; q+=y*(4*iris_info.columns)+4*x+z; (void) WriteBlobMSBShort(image,*q); } } } break; } default: { MemoryInfo *packet_info; size_t length, number_packets, *runlength; ssize_t offset, *offsets; /* Convert SGI uncompressed pixels. */ offsets=(ssize_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*offsets)); runlength=(size_t *) AcquireQuantumMemory(iris_info.rows, iris_info.depth*sizeof(*runlength)); packet_info=AcquireVirtualMemory((2*(size_t) iris_info.columns+10)* image->rows,4*sizeof(*packets)); if ((offsets == (ssize_t *) NULL) || (runlength == (size_t *) NULL) || (packet_info == (MemoryInfo *) NULL)) { if (offsets != (ssize_t *) NULL) offsets=(ssize_t *) RelinquishMagickMemory(offsets); if (runlength != (size_t *) NULL) runlength=(size_t *) RelinquishMagickMemory(runlength); if (packet_info != (MemoryInfo *) NULL) packet_info=RelinquishVirtualMemory(packet_info); pixel_info=RelinquishVirtualMemory(pixel_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } packets=(unsigned char *) GetVirtualMemoryBlob(packet_info); offset=512+4*2*((ssize_t) iris_info.rows*iris_info.depth); number_packets=0; q=pixels; for (y=0; y < (ssize_t) iris_info.rows; y++) { for (z=0; z < (ssize_t) iris_info.depth; z++) { length=SGIEncode(q+z,(size_t) iris_info.columns,packets+ number_packets); number_packets+=length; offsets[y+z*iris_info.rows]=offset; runlength[y+z*iris_info.rows]=(size_t) length; offset+=(ssize_t) length; } q+=(iris_info.columns*4); } /* Write out line start and length tables and runlength-encoded pixels. */ for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) offsets[i]); for (i=0; i < (ssize_t) (iris_info.rows*iris_info.depth); i++) (void) WriteBlobMSBLong(image,(unsigned int) runlength[i]); (void) WriteBlob(image,number_packets,packets); /* Relinquish resources. */ offsets=(ssize_t *) RelinquishMagickMemory(offsets); runlength=(size_t *) RelinquishMagickMemory(runlength); packet_info=RelinquishVirtualMemory(packet_info); break; } } pixel_info=RelinquishVirtualMemory(pixel_info); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++,imageListLength); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) CloseBlob(image); return(MagickTrue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/1562'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lyd_new_output_leaf(struct lyd_node *parent, const struct lys_module *module, const char *name, const char *val_str) { const struct lys_node *snode = NULL, *siblings; if ((!parent && !module) || !name) { LOGARG; return NULL; } siblings = lyd_new_find_schema(parent, module, 1); if (!siblings) { LOGARG; return NULL; } if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_LEAFLIST | LYS_LEAF, &snode) || !snode) { LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".", name, lys_node_module(siblings)->name, siblings->name); return NULL; } return _lyd_new_leaf(parent, snode, val_str, 0, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema Fixes #723'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lyd_dup_to_ctx(const struct lyd_node *node, int options, struct ly_ctx *ctx) { struct ly_ctx *log_ctx; struct lys_node_list *slist; struct lys_node *schema; const char *yang_data_name; const struct lys_module *trg_mod; const struct lyd_node *next, *elem; struct lyd_node *ret, *parent, *key, *key_dup, *new_node = NULL; uint16_t i; if (!node) { LOGARG; return NULL; } log_ctx = (ctx ? ctx : node->schema->module->ctx); if (ctx == node->schema->module->ctx) { /* target context is actually the same as the source context, * ignore the target context */ ctx = NULL; } ret = NULL; parent = NULL; /* LY_TREE_DFS */ for (elem = next = node; elem; elem = next) { /* find the correct schema */ if (ctx) { schema = NULL; if (parent) { trg_mod = lyp_get_module(parent->schema->module, NULL, 0, lyd_node_module(elem)->name, strlen(lyd_node_module(elem)->name), 1); if (!trg_mod) { LOGERR(log_ctx, LY_EINVAL, "Target context does not contain model for the data node being duplicated (%s).", lyd_node_module(elem)->name); goto error; } /* we know its parent, so we can start with it */ lys_getnext_data(trg_mod, parent->schema, elem->schema->name, strlen(elem->schema->name), elem->schema->nodetype, (const struct lys_node **)&schema); } else { /* we have to search in complete context */ schema = lyd_get_schema_inctx(elem, ctx); } if (!schema) { yang_data_name = lyp_get_yang_data_template_name(elem); if (yang_data_name) { LOGERR(log_ctx, LY_EINVAL, "Target context does not contain schema node for the data node being duplicated " "(%s:#%s/%s).", lyd_node_module(elem)->name, yang_data_name, elem->schema->name); } else { LOGERR(log_ctx, LY_EINVAL, "Target context does not contain schema node for the data node being duplicated " "(%s:%s).", lyd_node_module(elem)->name, elem->schema->name); } goto error; } } else { schema = elem->schema; } /* make node copy */ new_node = _lyd_dup_node(elem, schema, log_ctx, options); if (!new_node) { goto error; } if (parent && lyd_insert(parent, new_node)) { goto error; } if (!ret) { ret = new_node; } if (!(options & LYD_DUP_OPT_RECURSIVE)) { break; } /* LY_TREE_DFS_END */ /* select element for the next run - children first, * child exception for lyd_node_leaf and lyd_node_leaflist */ if (elem->schema->nodetype & (LYS_LEAF | LYS_LEAFLIST | LYS_ANYDATA)) { next = NULL; } else { next = elem->child; } if (!next) { if (elem->parent == node->parent) { break; } /* no children, so try siblings */ next = elem->next; } else { parent = new_node; } new_node = NULL; while (!next) { /* no siblings, go back through parents */ elem = elem->parent; if (elem->parent == node->parent) { break; } if (!parent) { LOGINT(log_ctx); goto error; } parent = parent->parent; /* parent is already processed, go to its sibling */ next = elem->next; } } /* dup all the parents */ if (options & LYD_DUP_OPT_WITH_PARENTS) { parent = ret; for (elem = node->parent; elem; elem = elem->parent) { new_node = lyd_dup(elem, options & LYD_DUP_OPT_NO_ATTR); LY_CHECK_ERR_GOTO(!new_node, LOGMEM(log_ctx), error); /* dup all list keys */ if (new_node->schema->nodetype == LYS_LIST) { slist = (struct lys_node_list *)new_node->schema; for (key = elem->child, i = 0; key && (i < slist->keys_size); ++i, key = key->next) { if (key->schema != (struct lys_node *)slist->keys[i]) { LOGVAL(log_ctx, LYE_PATH_INKEY, LY_VLOG_LYD, new_node, slist->keys[i]->name); goto error; } key_dup = lyd_dup(key, options & LYD_DUP_OPT_NO_ATTR); LY_CHECK_ERR_GOTO(!key_dup, LOGMEM(log_ctx), error); if (lyd_insert(new_node, key_dup)) { lyd_free(key_dup); goto error; } } if (!key && (i < slist->keys_size)) { LOGVAL(log_ctx, LYE_PATH_INKEY, LY_VLOG_LYD, new_node, slist->keys[i]->name); goto error; } } /* link together */ if (lyd_insert(new_node, parent)) { ret = parent; goto error; } parent = new_node; } } return ret; error: lyd_free(ret); return NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema Fixes #723'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lyd_new_anydata(struct lyd_node *parent, const struct lys_module *module, const char *name, void *value, LYD_ANYDATA_VALUETYPE value_type) { const struct lys_node *siblings, *snode; if ((!parent && !module) || !name) { LOGARG; return NULL; } siblings = lyd_new_find_schema(parent, module, 0); if (!siblings) { LOGARG; return NULL; } if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_ANYDATA, &snode) || !snode) { LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".", name, lys_node_module(siblings)->name, siblings->name); return NULL; } return lyd_create_anydata(parent, snode, value, value_type); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema Fixes #723'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lyd_new_yangdata(const struct lys_module *module, const char *name_template, const char *name) { const struct lys_node *schema = NULL, *snode; if (!module || !name_template || !name) { LOGARG; return NULL; } schema = lyp_get_yang_data_template(module, name_template, strlen(name_template)); if (!schema) { LOGERR(module->ctx, LY_EINVAL, "Failed to find yang-data template \"%s\".", name_template); return NULL; } if (lys_getnext_data(module, schema, name, strlen(name), LYS_CONTAINER, &snode) || !snode) { LOGERR(module->ctx, LY_EINVAL, "Failed to find \"%s\" as a container child of \"%s:%s\".", name, module->name, schema->name); return NULL; } return _lyd_new(NULL, snode, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema Fixes #723'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lys_getnext_data(const struct lys_module *mod, const struct lys_node *parent, const char *name, int nam_len, LYS_NODE type, const struct lys_node **ret) { const struct lys_node *node; assert((mod || parent) && name); assert(!(type & (LYS_AUGMENT | LYS_USES | LYS_GROUPING | LYS_CHOICE | LYS_CASE | LYS_INPUT | LYS_OUTPUT))); if (!mod) { mod = lys_node_module(parent); } /* try to find the node */ node = NULL; while ((node = lys_getnext(node, parent, mod, 0))) { if (!type || (node->nodetype & type)) { /* module check */ if (lys_node_module(node) != lys_main_module(mod)) { continue; } /* direct name check */ if (!strncmp(node->name, name, nam_len) && !node->name[nam_len]) { if (ret) { *ret = node; } return EXIT_SUCCESS; } } } return EXIT_FAILURE; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema Fixes #723'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: lyd_new_leaf(struct lyd_node *parent, const struct lys_module *module, const char *name, const char *val_str) { const struct lys_node *snode = NULL, *siblings; if ((!parent && !module) || !name) { LOGARG; return NULL; } siblings = lyd_new_find_schema(parent, module, 0); if (!siblings) { LOGARG; return NULL; } if (lys_getnext_data(module, lys_parent(siblings), name, strlen(name), LYS_LEAFLIST | LYS_LEAF, &snode) || !snode) { LOGERR(siblings->module->ctx, LY_EINVAL, "Failed to find \"%s\" as a sibling to \"%s:%s\".", name, lys_node_module(siblings)->name, siblings->name); return NULL; } return _lyd_new_leaf(parent, snode, val_str, 0, 0); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'schema tree BUGFIX do not check features while still resolving schema Fixes #723'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: void yyerror(YYLTYPE *yylloc, void *scanner, struct yang_parameter *param, ...) { free(*param->value); if (yylloc->first_line != -1) { if (*param->data_node && (*param->data_node) == (*param->actual_node)) { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_LYS, *param->data_node, yyget_text(scanner)); } else { LOGVAL(param->module->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'yang parser BUGFIX double free Fixes #739'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int yyparse (void *scanner, struct yang_parameter *param) { /* The lookahead symbol. */ int yychar; char *s = NULL, *tmp_s = NULL, *ext_name = NULL; struct lys_module *trg = NULL; struct lys_node *tpdf_parent = NULL, *data_node = NULL; struct lys_ext_instance_complex *ext_instance = NULL; int is_ext_instance; void *actual = NULL; enum yytokentype backup_type, actual_type = MODULE_KEYWORD; int64_t cnt_val = 0; int is_value = 0; void *yang_type = NULL; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* User initialization code. */ { yylloc.last_column = 0; if (param->flags & EXT_INSTANCE_SUBSTMT) { is_ext_instance = 1; ext_instance = (struct lys_ext_instance_complex *)param->actual_node; ext_name = (char *)param->data_node; } else { is_ext_instance = 0; } yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ param->value = &s; param->data_node = (void **)&data_node; param->actual_node = &actual; backup_type = NODE; trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; } yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = (yytype_int16) yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, &yylloc, scanner); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: { if (yyget_text(scanner)[0] == '"') { char *tmp; s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) { YYABORT; } s = tmp; } else { s = calloc(1, yyget_leng(scanner) - 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2); } (yyval.p_str) = &s; } break; case 8: { if (yyget_leng(scanner) > 2) { int length_s = strlen(s), length_tmp = yyget_leng(scanner); char *tmp; tmp = realloc(s, length_s + length_tmp - 1); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } s = tmp; if (yyget_text(scanner)[0] == '"') { if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) { YYABORT; } s = tmp; } else { memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2); s[length_s + length_tmp - 2] = '\0'; } } } break; case 10: { if (param->submodule) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module"); YYABORT; } trg = param->module; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = MODULE_KEYWORD; } break; case 12: { if (!param->module->ns) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module"); YYABORT; } if (!param->module->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module"); YYABORT; } } break; case 13: { (yyval.i) = 0; } break; case 14: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 15: { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) { YYABORT; } s = NULL; } break; case 16: { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } s = NULL; } break; case 17: { if (!param->submodule) { free(s); LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL); YYABORT; } trg = (struct lys_module *)param->submodule; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = SUBMODULE_KEYWORD; } break; case 19: { if (!param->submodule->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); YYABORT; } if (!(yyvsp[0].i)) { /* check version compatibility with the main module */ if (param->module->version > 1) { LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL); YYABORT; } } } break; case 20: { (yyval.i) = 0; } break; case 21: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 23: { backup_type = actual_type; actual_type = YANG_VERSION_KEYWORD; } break; case 25: { backup_type = actual_type; actual_type = NAMESPACE_KEYWORD; } break; case 30: { actual_type = (yyvsp[-4].token); backup_type = NODE; actual = NULL; } break; case 31: { YANG_ADDELEM(trg->imp, trg->imp_size, "imports"); /* HACK for unres */ ((struct lys_import *)actual)->module = (struct lys_module *)s; s = NULL; (yyval.token) = actual_type; actual_type = IMPORT_KEYWORD; } break; case 32: { (yyval.i) = 0; } break; case 33: { if (yang_read_prefix(trg, actual, s)) { YYABORT; } s = NULL; } break; case 34: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 35: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 36: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import"); free(s); YYABORT; } memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 37: { YANG_ADDELEM(trg->inc, trg->inc_size, "includes"); /* HACK for unres */ ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s; s = NULL; (yyval.token) = actual_type; actual_type = INCLUDE_KEYWORD; } break; case 38: { actual_type = (yyvsp[-1].token); backup_type = NODE; actual = NULL; } break; case 41: { (yyval.i) = 0; } break; case 42: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 43: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 44: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include"); free(s); YYABORT; } memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 45: { backup_type = actual_type; actual_type = REVISION_DATE_KEYWORD; } break; case 47: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, s, 0, LY_STMT_BELONGSTO)) { YYABORT; } } else { if (param->submodule->prefix) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); free(s); YYABORT; } if (!ly_strequal(s, param->submodule->belongsto->name, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to"); free(s); YYABORT; } free(s); } s = NULL; actual_type = BELONGS_TO_KEYWORD; } break; case 48: { if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", s, LY_STMT_BELONGSTO, LY_STMT_PREFIX)) { YYABORT; } } else { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } } s = NULL; actual_type = (yyvsp[-4].token); } break; case 49: { backup_type = actual_type; actual_type = PREFIX_KEYWORD; } break; case 52: { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) { YYABORT; } s = NULL; } break; case 53: { if (yang_read_common(trg, s, CONTACT_KEYWORD)) { YYABORT; } s = NULL; } break; case 54: { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s = NULL; } break; case 55: { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s=NULL; } break; case 56: { backup_type = actual_type; actual_type = ORGANIZATION_KEYWORD; } break; case 58: { backup_type = actual_type; actual_type = CONTACT_KEYWORD; } break; case 60: { backup_type = actual_type; actual_type = DESCRIPTION_KEYWORD; } break; case 62: { backup_type = actual_type; actual_type = REFERENCE_KEYWORD; } break; case 64: { if (trg->rev_size) { struct lys_revision *tmp; tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->rev = tmp; } } break; case 65: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!is_ext_instance) { YANG_ADDELEM(trg->rev, trg->rev_size, "revisions"); } memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE); free(s); s = NULL; actual_type = REVISION_KEYWORD; } break; case 67: { int i; /* check uniqueness of the revision date - not required by RFC */ for (i = 0; i < (trg->rev_size - 1); i++) { if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", trg->rev[trg->rev_size - 1].date); break; } } } break; case 68: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 72: { if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 73: { if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 74: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 76: { if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 77: { void *tmp; if (trg->tpdf_size) { tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->tpdf = tmp; } if (trg->features_size) { tmp = realloc(trg->features, trg->features_size * sizeof *trg->features); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->features = tmp; } if (trg->ident_size) { tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->ident = tmp; } if (trg->augment_size) { tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->augment = tmp; } if (trg->extensions_size) { tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->extensions = tmp; } } break; case 78: { /* check the module with respect to the context now */ if (!param->submodule) { switch (lyp_ctx_check_module(trg)) { case -1: YYABORT; case 0: break; case 1: /* it's already there */ param->flags |= YANG_EXIST_MODULE; YYABORT; } } param->flags &= (~YANG_REMOVE_IMPORT); if (yang_check_imports(trg, param->unres)) { YYABORT; } actual = NULL; } break; case 79: { actual = NULL; } break; case 90: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions"); trg->extensions_size--; ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_ext *)actual)->module = trg; if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) { trg->extensions_size++; YYABORT; } trg->extensions_size++; s = NULL; actual_type = EXTENSION_KEYWORD; } break; case 91: { struct lys_ext *ext = actual; ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 96: { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension"); YYABORT; } ((struct lys_ext *)actual)->flags |= (yyvsp[0].i); } break; case 97: { if (yang_read_description(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 98: { if (yang_read_reference(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 99: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, s, 0, LY_STMT_ARGUMENT)) { YYABORT; } } else { if (((struct lys_ext *)actual)->argument) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension"); free(s); YYABORT; } ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s); } s = NULL; actual_type = ARGUMENT_KEYWORD; } break; case 100: { actual_type = (yyvsp[-1].token); } break; case 103: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = YIN_ELEMENT_KEYWORD; } break; case 105: { if (is_ext_instance) { int c; const char ***p; uint8_t *val; struct lyext_substmt *info; c = 0; p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info); if (info->cardinality >= LY_STMT_CARD_SOME) { /* get the index in the array to add new item */ for (c = 0; p[0][c + 1]; c++); val = (uint8_t *)p[1]; } else { val = (uint8_t *)(p + 1); } val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2; } else { ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint); } } break; case 106: { (yyval.uint) = LYS_YINELEM; } break; case 107: { (yyval.uint) = 0; } break; case 108: { if (!strcmp(s, "true")) { (yyval.uint) = LYS_YINELEM; } else if (!strcmp(s, "false")) { (yyval.uint) = 0; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 109: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = STATUS_KEYWORD; } break; case 110: { (yyval.i) = (yyvsp[-1].i); } break; case 111: { (yyval.i) = LYS_STATUS_CURR; } break; case 112: { (yyval.i) = LYS_STATUS_OBSLT; } break; case 113: { (yyval.i) = LYS_STATUS_DEPRC; } break; case 114: { if (!strcmp(s, "current")) { (yyval.i) = LYS_STATUS_CURR; } else if (!strcmp(s, "obsolete")) { (yyval.i) = LYS_STATUS_OBSLT; } else if (!strcmp(s, "deprecated")) { (yyval.i) = LYS_STATUS_DEPRC; } else { LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 115: { /* check uniqueness of feature's names */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) { free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->features, trg->features_size, "features"); ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s); ((struct lys_feature *)actual)->module = trg; s = NULL; actual_type = FEATURE_KEYWORD; } break; case 116: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 118: { struct lys_iffeature *tmp; if (((struct lys_feature *)actual)->iffeature_size) { tmp = realloc(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_feature *)actual)->iffeature = tmp; } } break; case 121: { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature"); YYABORT; } ((struct lys_feature *)actual)->flags |= (yyvsp[0].i); } break; case 122: { if (yang_read_description(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 123: { if (yang_read_reference(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 124: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case FEATURE_KEYWORD: YANG_ADDELEM(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size, "if-features"); break; case IDENTITY_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size, "if-features"); break; case ENUM_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size, "if-features"); break; case BIT_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size, "if-features"); break; case REFINE_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_refine *)actual)->iffeature, ((struct lys_refine *)actual)->iffeature_size, "if-features"); break; case EXTENSION_INSTANCE: /* nothing change */ break; default: /* lys_node_* */ YANG_ADDELEM(((struct lys_node *)actual)->iffeature, ((struct lys_node *)actual)->iffeature_size, "if-features"); break; } ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s; s = NULL; actual_type = IF_FEATURE_KEYWORD; } break; case 125: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 128: { const char *tmp; tmp = lydict_insert_zc(trg->ctx, s); s = NULL; if (dup_identities_check(tmp, trg)) { lydict_remove(trg->ctx, tmp); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->ident, trg->ident_size, "identities"); ((struct lys_ident *)actual)->name = tmp; ((struct lys_ident *)actual)->module = trg; actual_type = IDENTITY_KEYWORD; } break; case 129: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 131: { void *tmp; if (((struct lys_ident *)actual)->base_size) { tmp = realloc(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->base = tmp; } if (((struct lys_ident *)actual)->iffeature_size) { tmp = realloc(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->iffeature = tmp; } } break; case 133: { void *identity; if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) { free(s); LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity"); YYABORT; } identity = actual; YANG_ADDELEM(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size, "bases"); *((struct lys_ident **)actual) = (struct lys_ident *)s; s = NULL; actual = identity; } break; case 135: { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity"); YYABORT; } ((struct lys_ident *)actual)->flags |= (yyvsp[0].i); } break; case 136: { if (yang_read_description(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 137: { if (yang_read_reference(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 138: { backup_type = actual_type; actual_type = BASE_KEYWORD; } break; case 140: { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) { free(s); YYABORT; } switch (actual_type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs"); break; case GROUPING_KEYWORD: YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf, ((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs"); break; case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf, ((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf, ((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs"); break; case RPC_KEYWORD: case ACTION_KEYWORD: YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf, ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf, ((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs"); break; case NOTIFICATION_KEYWORD: YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf, ((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs"); break; case EXTENSION_INSTANCE: /* typedef is already allocated */ break; default: /* another type of nodetype is error*/ LOGINT(trg->ctx); free(s); YYABORT; } ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_tpdf *)actual)->module = trg; s = NULL; actual_type = TYPEDEF_KEYWORD; } break; case 141: { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 142: { (yyval.nodes).node.ptr_tpdf = actual; (yyval.nodes).node.flag = 0; } break; case 143: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 144: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 145: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 146: { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef"); YYABORT; } (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i); } break; case 147: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 148: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 149: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 150: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) { YYABORT; } s = NULL; actual_type = TYPE_KEYWORD; } break; case 153: { if (((struct yang_type *)actual)->base == LY_TYPE_STRING && ((struct yang_type *)actual)->type->info.str.pat_count) { void *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns = tmp; #ifdef LY_ENABLED_CACHE if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) { tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre, 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp; } #endif } if (((struct yang_type *)actual)->base == LY_TYPE_UNION) { struct lys_type *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.uni.types, ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.uni.types = tmp; } if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) { struct lys_ident **tmp; tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.ident.ref = tmp; } } break; case 157: { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) { YYABORT; } } break; case 158: { /* leafref_specification */ if (yang_read_leafref_path(trg, actual, s)) { YYABORT; } s = NULL; } break; case 159: { /* identityref_specification */ if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); return EXIT_FAILURE; } ((struct yang_type *)actual)->base = LY_TYPE_IDENT; yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count, "identity refs"); *((struct lys_ident **)actual) = (struct lys_ident *)s; actual = yang_type; s = NULL; } break; case 162: { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) { YYABORT; } } break; case 165: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 166: { struct yang_type *stype = (struct yang_type *)actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (stype->base != 0 && stype->base != LY_TYPE_UNION) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement."); YYABORT; } stype->base = LY_TYPE_UNION; if (strcmp(stype->name, "union")) { /* type can be a substatement only in "union" type, not in derived types */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type"); YYABORT; } YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types") actual_type = UNION_KEYWORD; } break; case 167: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = FRACTION_DIGITS_KEYWORD; } break; case 168: { (yyval.uint) = (yyvsp[-1].uint); } break; case 169: { (yyval.uint) = (yyvsp[-1].uint); } break; case 170: { char *endptr = NULL; unsigned long val; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits"); free(s); s = NULL; YYABORT; } (yyval.uint) = (uint32_t) val; free(s); s =NULL; } break; case 171: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 172: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = LENGTH_KEYWORD; s = NULL; } break; case 175: { switch (actual_type) { case MUST_KEYWORD: (yyval.str) = "must"; break; case LENGTH_KEYWORD: (yyval.str) = "length"; break; case RANGE_KEYWORD: (yyval.str) = "range"; break; default: LOGINT(trg->ctx); YYABORT; break; } } break; case 176: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 177: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 178: { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 179: { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 180: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; } break; case 181: {struct lys_restr *pattern = actual; actual = NULL; #ifdef LY_ENABLED_CACHE if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE && !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); ++c; YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); actual = &(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1)]; } #endif if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { YYABORT; } actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 182: { if (actual_type != EXTENSION_INSTANCE) { if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) { free(s); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement."); YYABORT; } ((struct yang_type *)actual)->base = LY_TYPE_STRING; YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count, "patterns"); } (yyval.str) = s; s = NULL; actual_type = PATTERN_KEYWORD; } break; case 183: { (yyval.ch) = 0x06; } break; case 184: { (yyval.ch) = (yyvsp[-1].ch); } break; case 185: { (yyval.ch) = 0x06; /* ACK */ } break; case 186: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier"); YYABORT; } if ((yyvsp[-1].ch) != 0x06) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern"); YYABORT; } (yyval.ch) = (yyvsp[0].ch); } break; case 187: { if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 188: { if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 189: { if (yang_read_description(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 190: { if (yang_read_reference(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 191: { backup_type = actual_type; actual_type = MODIFIER_KEYWORD; } break; case 192: { if (!strcmp(s, "invert-match")) { (yyval.ch) = 0x15; free(s); s = NULL; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } } break; case 193: { struct lys_type_enum * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.enums.enm = tmp; } break; case 196: { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 197: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums"); if (yang_read_enum(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = ENUM_KEYWORD; } break; case 199: { if (((struct lys_type_enum *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_enum *)actual)->iffeature = tmp; } } break; case 202: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->value = (yyvsp[0].i); /* keep the highest enum value for automatic increment */ if ((yyvsp[0].i) >= cnt_val) { cnt_val = (yyvsp[0].i) + 1; } is_value = 1; } break; case 203: { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i); } break; case 204: { if (yang_read_description(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 205: { if (yang_read_reference(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 206: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = VALUE_KEYWORD; } break; case 207: { (yyval.i) = (yyvsp[-1].i); } break; case 208: { (yyval.i) = (yyvsp[-1].i); } break; case 209: { /* convert it to int32_t */ int64_t val; char *endptr; val = strtoll(s, &endptr, 10); if (val < INT32_MIN || val > INT32_MAX || *endptr) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value"); free(s); YYABORT; } free(s); s = NULL; (yyval.i) = (int32_t) val; } break; case 210: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 213: { backup_type = actual_type; actual_type = PATH_KEYWORD; } break; case 215: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = REQUIRE_INSTANCE_KEYWORD; } break; case 216: { (yyval.i) = (yyvsp[-1].i); } break; case 217: { (yyval.i) = 1; } break; case 218: { (yyval.i) = -1; } break; case 219: { if (!strcmp(s,"true")) { (yyval.i) = 1; } else if (!strcmp(s,"false")) { (yyval.i) = -1; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance"); free(s); YYABORT; } free(s); s = NULL; } break; case 220: { struct lys_type_bit * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.bits.bit = tmp; } break; case 223: { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-2].backup_token).actual; actual_type = (yyvsp[-2].backup_token).token; } break; case 224: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count, "bits"); if (yang_read_bit(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = BIT_KEYWORD; } break; case 226: { if (((struct lys_type_bit *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_bit *)actual)->iffeature = tmp; } } break; case 229: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint); /* keep the highest position value for automatic increment */ if ((yyvsp[0].uint) >= cnt_val) { cnt_val = (yyvsp[0].uint) + 1; } is_value = 1; } break; case 230: { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i); } break; case 231: { if (yang_read_description(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 232: { if (yang_read_reference(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 233: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = POSITION_KEYWORD; } break; case 234: { (yyval.uint) = (yyvsp[-1].uint); } break; case 235: { (yyval.uint) = (yyvsp[-1].uint); } break; case 236: { /* convert it to uint32_t */ unsigned long val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position"); free(s); YYABORT; } free(s); s = NULL; (yyval.uint) = (uint32_t) val; } break; case 237: { backup_type = actual_type; actual_type = ERROR_MESSAGE_KEYWORD; } break; case 239: { backup_type = actual_type; actual_type = ERROR_APP_TAG_KEYWORD; } break; case 241: { backup_type = actual_type; actual_type = UNITS_KEYWORD; } break; case 243: { backup_type = actual_type; actual_type = DEFAULT_KEYWORD; } break; case 245: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) { YYABORT; } s = NULL; data_node = actual; actual_type = GROUPING_KEYWORD; } break; case 246: { LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 249: { (yyval.nodes).grouping = actual; } break; case 250: { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping"); YYABORT; } (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i); } break; case 251: { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 252: { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 257: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification"); YYABORT; } } break; case 266: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CONTAINER_KEYWORD; } break; case 267: { LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 269: { void *tmp; if ((yyvsp[-1].nodes).container->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->iffeature = tmp; } if ((yyvsp[-1].nodes).container->must_size) { tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->must = tmp; } } break; case 270: { (yyval.nodes).container = actual; } break; case 274: { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) { YYABORT; } s = NULL; } break; case 275: { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 276: { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 277: { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 278: { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 281: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification"); YYABORT; } } break; case 284: { void *tmp; if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->must = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 285: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_KEYWORD; } break; case 286: { (yyval.nodes).node.ptr_leaf = actual; (yyval.nodes).node.flag = 0; } break; case 289: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 290: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 292: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 293: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 294: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 295: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 296: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 297: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 298: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_LIST_KEYWORD; } break; case 299: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F; } if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 300: { (yyval.nodes).node.ptr_leaflist = actual; (yyval.nodes).node.flag = 0; } break; case 303: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 304: { if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default"); YYABORT; } YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults"); (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_leaflist; } break; case 305: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) { YYABORT; } s = NULL; } break; case 307: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 308: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 309: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 310: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 311: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 312: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 313: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 314: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LIST_KEYWORD; } break; case 315: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->unique_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->unique = tmp; } LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 316: { (yyval.nodes).node.ptr_list = actual; (yyval.nodes).node.flag = 0; } break; case 320: { if ((yyvsp[-1].nodes).node.ptr_list->keys) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; } break; case 321: { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_list; } break; case 322: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 323: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 324: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 325: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 326: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 327: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 328: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 332: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification"); YYABORT; } } break; case 334: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CHOICE_KEYWORD; } break; case 335: { LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 337: { struct lys_iffeature *tmp; if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp; } } break; case 338: { (yyval.nodes).node.ptr_choice = actual; (yyval.nodes).node.flag = 0; } break; case 341: { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT; } break; case 342: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 343: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 344: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 345: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 346: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 356: { if (trg->version < 2 ) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice"); YYABORT; } } break; case 357: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CASE_KEYWORD; } break; case 358: { LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 360: { struct lys_iffeature *tmp; if ((yyvsp[-1].nodes).cs->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).cs->iffeature = tmp; } } break; case 361: { (yyval.nodes).cs = actual; } break; case 364: { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case"); YYABORT; } (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i); } break; case 365: { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 366: { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 368: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYXML_KEYWORD; } break; case 369: { LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 370: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYDATA_KEYWORD; } break; case 371: { LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 373: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->must = tmp; } } break; case 374: { (yyval.nodes).node.ptr_anydata = actual; (yyval.nodes).node.flag = actual_type; } break; case 378: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 379: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 380: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 381: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 382: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 383: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) { YYABORT; } data_node = actual; s = NULL; actual_type = USES_KEYWORD; } break; case 384: { LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 386: { void *tmp; if ((yyvsp[-1].nodes).uses->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->iffeature = tmp; } if ((yyvsp[-1].nodes).uses->refine_size) { tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->refine = tmp; } if ((yyvsp[-1].nodes).uses->augment_size) { tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->augment = tmp; } } break; case 387: { (yyval.nodes).uses = actual; } break; case 390: { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses"); YYABORT; } (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i); } break; case 391: { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 392: { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 397: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->refine, ((struct lys_node_uses *)actual)->refine_size, "refines"); ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s); free(s); s = NULL; if (!((struct lys_refine *)actual)->target_name) { YYABORT; } actual_type = REFINE_KEYWORD; } break; case 398: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 400: { void *tmp; if ((yyvsp[-1].nodes).refine->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->iffeature = tmp; } if ((yyvsp[-1].nodes).refine->must_size) { tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->must = tmp; } if ((yyvsp[-1].nodes).refine->dflt_size) { tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->dflt = tmp; } } break; case 401: { (yyval.nodes).refine = actual; actual_type = REFINE_KEYWORD; } break; case 402: { actual = (yyvsp[-2].nodes).refine; actual_type = REFINE_KEYWORD; if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML; } } break; case 403: { /* leaf, leaf-list, list, container or anyxml */ /* check possibility of statements combination */ if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA; } } break; case 404: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) { if ((yyvsp[-1].nodes).refine->mod.presence) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine"); free(s); YYABORT; } (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 405: { int i; if ((yyvsp[-1].nodes).refine->dflt_size) { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine"); YYABORT; } if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST; } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if ((yyvsp[-1].nodes).refine->target_type) { if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE); } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if (trg->version < 2) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE; } else { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE; } } } /* check for duplicity */ for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) { if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s); YYABORT; } } YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); actual = (yyvsp[-1].nodes).refine; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 406: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 407: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML); if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 408: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 409: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 410: { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 411: { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 414: { void *parent; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; parent = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->augment, ((struct lys_node_uses *)actual)->augment_size, "augments"); if (yang_read_augment(trg, parent, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 415: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 418: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->augment, trg->augment_size, "augments"); if (yang_read_augment(trg, NULL, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 419: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 420: { (yyval.nodes).augment = actual; } break; case 423: { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment"); YYABORT; } (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i); } break; case 424: { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 425: { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 428: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification"); YYABORT; } } break; case 430: { if (param->module->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action"); free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ACTION_KEYWORD; } break; case 431: { LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 432: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = RPC_KEYWORD; } break; case 433: { LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 435: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp; } } break; case 436: { (yyval.nodes).node.ptr_rpc = actual; (yyval.nodes).node.flag = 0; } break; case 438: { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc"); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i); } break; case 439: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 440: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 443: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 444: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 445: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("input"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = INPUT_KEYWORD; } break; case 446: { void *tmp; struct lys_node_inout *input = actual; if (input->must_size) { tmp = realloc(input->must, input->must_size * sizeof *input->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->must = tmp; } if (input->tpdf_size) { tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 452: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("output"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = OUTPUT_KEYWORD; } break; case 453: { void *tmp; struct lys_node_inout *output = actual; if (output->must_size) { tmp = realloc(output->must, output->must_size * sizeof *output->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->must = tmp; } if (output->tpdf_size) { tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 454: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) { YYABORT; } data_node = actual; actual_type = NOTIFICATION_KEYWORD; } break; case 455: { LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 457: { void *tmp; if ((yyvsp[-1].nodes).notif->must_size) { tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->must = tmp; } if ((yyvsp[-1].nodes).notif->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->iffeature = tmp; } if ((yyvsp[-1].nodes).notif->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->tpdf = tmp; } } break; case 458: { (yyval.nodes).notif = actual; } break; case 461: { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification"); YYABORT; } (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i); } break; case 462: { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 463: { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 467: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations"); ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s); free(s); if (!((struct lys_deviation *)actual)->target_name) { YYABORT; } s = NULL; actual_type = DEVIATION_KEYWORD; } break; case 468: { void *tmp; if ((yyvsp[-1].dev)->deviate_size) { tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate); if (!tmp) { LOGINT(trg->ctx); YYABORT; } (yyvsp[-1].dev)->deviate = tmp; } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 469: { (yyval.dev) = actual; } break; case 470: { if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 471: { if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 477: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) { YYABORT; } actual_type = NOT_SUPPORTED_KEYWORD; } break; case 478: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 484: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) { YYABORT; } actual_type = ADD_KEYWORD; } break; case 485: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 487: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 488: { (yyval.deviate) = actual; } break; case 489: { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 491: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate)= (yyvsp[-1].deviate); } break; case 492: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 493: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 494: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 495: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 496: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 497: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) { YYABORT; } actual_type = DELETE_KEYWORD; } break; case 498: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 500: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 501: { (yyval.deviate) = actual; } break; case 502: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 504: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 505: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 506: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) { YYABORT; } actual_type = REPLACE_KEYWORD; } break; case 507: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 509: { void *tmp; if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 510: { (yyval.deviate) = actual; } break; case 512: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 513: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 514: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 515: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 516: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 517: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 518: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_when(trg, actual, actual_type, s))) { YYABORT; } s = NULL; actual_type = WHEN_KEYWORD; } break; case 519: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 523: { if (yang_read_description(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 524: { if (yang_read_reference(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 525: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = CONFIG_KEYWORD; } break; case 526: { (yyval.i) = (yyvsp[-1].i); } break; case 527: { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } break; case 528: { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } break; case 529: { if (!strcmp(s, "true")) { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config"); free(s); YYABORT; } free(s); s = NULL; } break; case 530: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = MANDATORY_KEYWORD; } break; case 531: { (yyval.i) = (yyvsp[-1].i); } break; case 532: { (yyval.i) = LYS_MAND_TRUE; } break; case 533: { (yyval.i) = LYS_MAND_FALSE; } break; case 534: { if (!strcmp(s, "true")) { (yyval.i) = LYS_MAND_TRUE; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_MAND_FALSE; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory"); free(s); YYABORT; } free(s); s = NULL; } break; case 535: { backup_type = actual_type; actual_type = PRESENCE_KEYWORD; } break; case 537: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MIN_ELEMENTS_KEYWORD; } break; case 538: { (yyval.uint) = (yyvsp[-1].uint); } break; case 539: { (yyval.uint) = (yyvsp[-1].uint); } break; case 540: { if (strlen(s) == 1 && s[0] == '0') { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 541: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MAX_ELEMENTS_KEYWORD; } break; case 542: { (yyval.uint) = (yyvsp[-1].uint); } break; case 543: { (yyval.uint) = 0; } break; case 544: { (yyval.uint) = (yyvsp[-1].uint); } break; case 545: { if (!strcmp(s, "unbounded")) { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 546: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = ORDERED_BY_KEYWORD; } break; case 547: { (yyval.i) = (yyvsp[-1].i); } break; case 548: { (yyval.i) = LYS_USERORDERED; } break; case 549: { (yyval.i) = LYS_SYSTEMORDERED; } break; case 550: { if (!strcmp(s, "user")) { (yyval.i) = LYS_USERORDERED; } else if (!strcmp(s, "system")) { (yyval.i) = LYS_SYSTEMORDERED; } else { free(s); YYABORT; } free(s); s=NULL; } break; case 551: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)actual)->must, ((struct lys_node_container *)actual)->must_size, "musts"); break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: YANG_ADDELEM(((struct lys_node_anydata *)actual)->must, ((struct lys_node_anydata *)actual)->must_size, "musts"); break; case LEAF_KEYWORD: YANG_ADDELEM(((struct lys_node_leaf *)actual)->must, ((struct lys_node_leaf *)actual)->must_size, "musts"); break; case LEAF_LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must, ((struct lys_node_leaflist *)actual)->must_size, "musts"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)actual)->must, ((struct lys_node_list *)actual)->must_size, "musts"); break; case REFINE_KEYWORD: YANG_ADDELEM(((struct lys_refine *)actual)->must, ((struct lys_refine *)actual)->must_size, "musts"); break; case ADD_KEYWORD: case DELETE_KEYWORD: YANG_ADDELEM(((struct lys_deviate *)actual)->must, ((struct lys_deviate *)actual)->must_size, "musts"); break; case NOTIFICATION_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_notif *)actual)->must, ((struct lys_node_notif *)actual)->must_size, "musts"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_inout *)actual)->must, ((struct lys_node_inout *)actual)->must_size, "musts"); break; case EXTENSION_INSTANCE: /* must is already allocated */ break; default: free(s); LOGINT(trg->ctx); YYABORT; } ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s); free(s); if (!((struct lys_restr *)actual)->expr) { YYABORT; } s = NULL; actual_type = MUST_KEYWORD; } break; case 552: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 555: { backup_type = actual_type; actual_type = UNIQUE_KEYWORD; } break; case 559: { backup_type = actual_type; actual_type = KEY_KEYWORD; } break; case 561: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 564: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = RANGE_KEYWORD; s = NULL; } break; case 565: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s,"/"); strcat(s, yyget_text(scanner)); } else { s = malloc(yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[0]='/'; memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1); } } break; case 569: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s, yyget_text(scanner)); } else { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } } break; case 571: { tmp_s = yyget_text(scanner); } break; case 572: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 573: { tmp_s = yyget_text(scanner); } break; case 574: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 598: { /* convert it to uint32_t */ unsigned long val; val = strtoul(yyget_text(scanner), NULL, 10); if (val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long."); YYABORT; } (yyval.uint) = (uint32_t) val; } break; case 599: { (yyval.uint) = 0; } break; case 600: { (yyval.uint) = (yyvsp[0].uint); } break; case 601: { (yyval.i) = 0; } break; case 602: { /* convert it to int32_t */ int64_t val; val = strtoll(yyget_text(scanner), NULL, 10); if (val < INT32_MIN || val > INT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val); YYABORT; } (yyval.i) = (int32_t) val; } break; case 608: { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } break; case 613: { char *tmp; if ((tmp = strchr(s, ':'))) { *tmp = '\0'; /* check prefix */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } /* check identifier */ if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } *tmp = ':'; } else { /* check identifier */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } } break; case 614: { s = (yyvsp[-1].str); } break; case 615: { s = (yyvsp[-3].str); } break; case 616: { actual_type = backup_type; backup_type = NODE; (yyval.str) = s; s = NULL; } break; case 617: { actual_type = backup_type; backup_type = NODE; } break; case 618: { (yyval.str) = s; s = NULL; } break; case 622: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 623: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s, actual_type, backup_type, is_ext_instance))) { YYABORT; } s = NULL; actual_type = EXTENSION_INSTANCE; } break; case 624: { (yyval.str) = s; s = NULL; } break; case 639: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length = 0, old_length = 0; char *tmp_value; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2; tmp_value = realloc(substmt->ext_substmt, old_length + length + 1); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_substmt = tmp_value; tmp_value += old_length - 2; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = ' '; tmp_value[length + 1] = '\0'; tmp_value[length + 2] = '\0'; } break; case 640: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length; char *tmp_value, **array; int i = 0; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); if (!substmt->ext_modules) { array = malloc(2 * sizeof *substmt->ext_modules); } else { for (i = 0; substmt->ext_modules[i]; ++i); array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules); } if (!array) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_modules = array; array[i + 1] = NULL; tmp_value = malloc(length + 2); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } array[i] = tmp_value; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = '\0'; tmp_value[length + 1] = '\0'; } break; case 643: { (yyval.str) = yyget_text(scanner); } break; case 644: { (yyval.str) = yyget_text(scanner); } break; case 656: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 749: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 750: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 751: { struct lys_type **type; type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "type", LY_STMT_TYPE); if (!type) { YYABORT; } /* allocate type structure */ (*type) = calloc(1, sizeof **type); if (!*type) { LOGMEM(trg->ctx); YYABORT; } /* HACK for unres */ (*type)->parent = (struct lys_tpdf *)ext_instance; (yyval.v) = actual = *type; is_ext_instance = 0; } break; case 752: { struct lys_tpdf **tpdf; tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "typedef", LY_STMT_TYPEDEF); if (!tpdf) { YYABORT; } /* allocate typedef structure */ (*tpdf) = calloc(1, sizeof **tpdf); if (!*tpdf) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *tpdf; is_ext_instance = 0; } break; case 753: { struct lys_iffeature **iffeature; iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "if-feature", LY_STMT_IFFEATURE); if (!iffeature) { YYABORT; } /* allocate typedef structure */ (*iffeature) = calloc(1, sizeof **iffeature); if (!*iffeature) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *iffeature; } break; case 754: { struct lys_restr **restr; LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "must")) { stmt = LY_STMT_MUST; } else if (!strcmp(s, "pattern")) { stmt = LY_STMT_PATTERN; } else if (!strcmp(s, "range")) { stmt = LY_STMT_RANGE; } else { stmt = LY_STMT_LENGTH; } restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt); if (!restr) { YYABORT; } /* allocate structure for must */ (*restr) = calloc(1, sizeof(struct lys_restr)); if (!*restr) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *restr; s = NULL; } break; case 755: { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN); if (!actual) { YYABORT; } (yyval.v) = actual; } break; case 756: { struct lys_revision **rev; int i; rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name, "revision", LY_STMT_REVISION); if (!rev) { YYABORT; } rev[i] = calloc(1, sizeof **rev); if (!rev[i]) { LOGMEM(trg->ctx); YYABORT; } actual = rev[i]; (yyval.revisions).revision = rev; (yyval.revisions).index = i; } break; case 757: { LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "action")) { stmt = LY_STMT_ACTION; } else if (!strcmp(s, "anydata")) { stmt = LY_STMT_ANYDATA; } else if (!strcmp(s, "anyxml")) { stmt = LY_STMT_ANYXML; } else if (!strcmp(s, "case")) { stmt = LY_STMT_CASE; } else if (!strcmp(s, "choice")) { stmt = LY_STMT_CHOICE; } else if (!strcmp(s, "container")) { stmt = LY_STMT_CONTAINER; } else if (!strcmp(s, "grouping")) { stmt = LY_STMT_GROUPING; } else if (!strcmp(s, "input")) { stmt = LY_STMT_INPUT; } else if (!strcmp(s, "leaf")) { stmt = LY_STMT_LEAF; } else if (!strcmp(s, "leaf-list")) { stmt = LY_STMT_LEAFLIST; } else if (!strcmp(s, "list")) { stmt = LY_STMT_LIST; } else if (!strcmp(s, "notification")) { stmt = LY_STMT_NOTIFICATION; } else if (!strcmp(s, "output")) { stmt = LY_STMT_OUTPUT; } else { stmt = LY_STMT_USES; } if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) { YYABORT; } actual = NULL; s = NULL; is_ext_instance = 0; } break; case 758: { LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); } break; case 790: { actual_type = EXTENSION_INSTANCE; actual = ext_instance; if (!is_ext_instance) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); YYABORT; } (yyval.i) = 0; } break; case 792: { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, s, 0, LY_STMT_PREFIX)) { YYABORT; } } break; case 793: { if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, s, 0, LY_STMT_DESCRIPTION)) { YYABORT; } } break; case 794: { if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, s, 0, LY_STMT_REFERENCE)) { YYABORT; } } break; case 795: { if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, s, 0, LY_STMT_UNITS)) { YYABORT; } } break; case 796: { if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, s, 0, LY_STMT_BASE)) { YYABORT; } } break; case 797: { if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, s, 0, LY_STMT_CONTACT)) { YYABORT; } } break; case 798: { if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, s, 0, LY_STMT_DEFAULT)) { YYABORT; } } break; case 799: { if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, s, 0, LY_STMT_ERRMSG)) { YYABORT; } } break; case 800: { if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, s, 0, LY_STMT_ERRTAG)) { YYABORT; } } break; case 801: { if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, s, 0, LY_STMT_KEY)) { YYABORT; } } break; case 802: { if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, s, 0, LY_STMT_NAMESPACE)) { YYABORT; } } break; case 803: { if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, s, 0, LY_STMT_ORGANIZATION)) { YYABORT; } } break; case 804: { if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, s, 0, LY_STMT_PATH)) { YYABORT; } } break; case 805: { if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, s, 0, LY_STMT_PRESENCE)) { YYABORT; } } break; case 806: { if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, s, 0, LY_STMT_REVISIONDATE)) { YYABORT; } } break; case 807: { struct lys_type *type = (yyvsp[-2].v); if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) { yang_type_free(trg->ctx, type); YYABORT; } if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) { yang_type_free(trg->ctx, type); YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 808: { struct lys_tpdf *tpdf = (yyvsp[-2].v); if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) { yang_type_free(trg->ctx, &tpdf->type); } if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) { YYABORT; } if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) { yang_type_free(trg->ctx, &tpdf->type); YYABORT; } /* check default value*/ if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) { YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 809: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS, (yyvsp[0].i), LYS_STATUS_MASK)) { YYABORT; } } break; case 810: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG, (yyvsp[0].i), LYS_CONFIG_MASK)) { YYABORT; } } break; case 811: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY, (yyvsp[0].i), LYS_MAND_MASK)) { YYABORT; } } break; case 812: { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY, (yyvsp[0].i), LYS_USERORDERED)) { YYABORT; } } (yyvsp[-1].i) |= (yyvsp[0].i); (yyval.i) = (yyvsp[-1].i); } break; case 813: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance", LY_STMT_REQINSTANCE, (yyvsp[0].i))) { YYABORT; } } break; case 814: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) { YYABORT; } } break; case 815: { /* range check */ if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits"); YYABORT; } if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) { YYABORT; } } break; case 816: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "min-elements", LY_STMT_MIN); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 817: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "max-elements", LY_STMT_MAX); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 818: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "position", LY_STMT_POSITION); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 819: { int32_t **val; val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "value", LY_STMT_VALUE); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(int32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].i); } break; case 820: { struct lys_unique **unique; int rc; unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "unique", LY_STMT_UNIQUE); if (!unique) { YYABORT; } *unique = calloc(1, sizeof(struct lys_unique)); if (!*unique) { LOGMEM(trg->ctx); YYABORT; } rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres); free(s); s = NULL; if (rc) { YYABORT; } } break; case 821: { struct lys_iffeature *iffeature; iffeature = (yyvsp[-2].v); s = (char *)iffeature->features; iffeature->features = NULL; if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) { YYABORT; } if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) { YYABORT; } s = NULL; actual = ext_instance; } break; case 823: { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 824: { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size, *(struct lys_when **)(yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 825: { int i; for (i = 0; i < (yyvsp[-2].revisions).index; ++i) { if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date); break; } } if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) { YYABORT; } actual = ext_instance; } break; case 826: { actual = ext_instance; is_ext_instance = 1; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, scanner, param, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, scanner, param, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, scanner, param); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, scanner, param, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, scanner, param); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'yang parser BUGFIX double free Fixes #742'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int yyparse (void *scanner, struct yang_parameter *param) { /* The lookahead symbol. */ int yychar; char *s = NULL, *tmp_s = NULL, *ext_name = NULL; struct lys_module *trg = NULL; struct lys_node *tpdf_parent = NULL, *data_node = NULL; struct lys_ext_instance_complex *ext_instance = NULL; int is_ext_instance; void *actual = NULL; enum yytokentype backup_type, actual_type = MODULE_KEYWORD; int64_t cnt_val = 0; int is_value = 0; void *yang_type = NULL; /* The semantic value of the lookahead symbol. */ /* Default value used for initialization, for pacifying older GCCs or non-GCC compilers. */ YY_INITIAL_VALUE (static YYSTYPE yyval_default;) YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); /* Location data for the lookahead symbol. */ static YYLTYPE yyloc_default # if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL = { 1, 1, 1, 1 } # endif ; YYLTYPE yylloc = yyloc_default; /* Number of syntax errors so far. */ int yynerrs; int yystate; /* Number of tokens to shift before error messages enabled. */ int yyerrstatus; /* The stacks and their tools: 'yyss': related to states. 'yyvs': related to semantic values. 'yyls': related to locations. Refer to the stacks through separate pointers, to allow yyoverflow to reallocate them elsewhere. */ /* The state stack. */ yytype_int16 yyssa[YYINITDEPTH]; yytype_int16 *yyss; yytype_int16 *yyssp; /* The semantic value stack. */ YYSTYPE yyvsa[YYINITDEPTH]; YYSTYPE *yyvs; YYSTYPE *yyvsp; /* The location stack. */ YYLTYPE yylsa[YYINITDEPTH]; YYLTYPE *yyls; YYLTYPE *yylsp; /* The locations where the error started and ended. */ YYLTYPE yyerror_range[3]; YYSIZE_T yystacksize; int yyn; int yyresult; /* Lookahead token as an internal (translated) token number. */ int yytoken = 0; /* The variables used to return semantic value and location from the action routines. */ YYSTYPE yyval; YYLTYPE yyloc; #if YYERROR_VERBOSE /* Buffer for error messages, and its allocated size. */ char yymsgbuf[128]; char *yymsg = yymsgbuf; YYSIZE_T yymsg_alloc = sizeof yymsgbuf; #endif #define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) /* The number of symbols on the RHS of the reduced rule. Keep to zero when no symbol should be popped. */ int yylen = 0; yyssp = yyss = yyssa; yyvsp = yyvs = yyvsa; yylsp = yyls = yylsa; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ /* User initialization code. */ { yylloc.last_column = 0; if (param->flags & EXT_INSTANCE_SUBSTMT) { is_ext_instance = 1; ext_instance = (struct lys_ext_instance_complex *)param->actual_node; ext_name = (char *)param->data_node; } else { is_ext_instance = 0; } yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ param->value = &s; param->data_node = (void **)&data_node; param->actual_node = &actual; backup_type = NODE; trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; } yylsp[0] = yylloc; goto yysetstate; /*------------------------------------------------------------. | yynewstate -- Push a new state, which is found in yystate. | `------------------------------------------------------------*/ yynewstate: /* In all cases, when you get here, the value and location stacks have just been pushed. So pushing a state here evens the stacks. */ yyssp++; yysetstate: *yyssp = (yytype_int16) yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); #ifdef yyoverflow { /* Give user a chance to reallocate the stack. Use copies of these so that the &'s don't force the real ones into memory. */ YYSTYPE *yyvs1 = yyvs; yytype_int16 *yyss1 = yyss; YYLTYPE *yyls1 = yyls; /* Each stack pointer address is followed by the size of the data in use in that stack, in bytes. This used to be a conditional around just the two extra args, but that might be undefined if yyoverflow is a macro. */ yyoverflow (YY_("memory exhausted"), &yyss1, yysize * sizeof (*yyssp), &yyvs1, yysize * sizeof (*yyvsp), &yyls1, yysize * sizeof (*yylsp), &yystacksize); yyss = yyss1; yyvs = yyvs1; yyls = yyls1; } #else /* no yyoverflow */ # ifndef YYSTACK_RELOCATE goto yyexhaustedlab; # else /* Extend the stack our own way. */ if (YYMAXDEPTH <= yystacksize) goto yyexhaustedlab; yystacksize *= 2; if (YYMAXDEPTH < yystacksize) yystacksize = YYMAXDEPTH; { yytype_int16 *yyss1 = yyss; union yyalloc *yyptr = (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); if (! yyptr) goto yyexhaustedlab; YYSTACK_RELOCATE (yyss_alloc, yyss); YYSTACK_RELOCATE (yyvs_alloc, yyvs); YYSTACK_RELOCATE (yyls_alloc, yyls); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; yylsp = yyls + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long) yystacksize)); if (yyss + yystacksize - 1 <= yyssp) YYABORT; } YYDPRINTF ((stderr, "Entering state %d\n", yystate)); if (yystate == YYFINAL) YYACCEPT; goto yybackup; /*-----------. | yybackup. | `-----------*/ yybackup: /* Do appropriate processing given the current state. Read a lookahead token if we need one and don't already have one. */ /* First try to decide what to do without reference to lookahead token. */ yyn = yypact[yystate]; if (yypact_value_is_default (yyn)) goto yydefault; /* Not known => get a lookahead token if don't already have one. */ /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ if (yychar == YYEMPTY) { YYDPRINTF ((stderr, "Reading a token: ")); yychar = yylex (&yylval, &yylloc, scanner); } if (yychar <= YYEOF) { yychar = yytoken = YYEOF; YYDPRINTF ((stderr, "Now at end of input.\n")); } else { yytoken = YYTRANSLATE (yychar); YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); } /* If the proper action on seeing token YYTOKEN is to reduce or to detect an error, take that action. */ yyn += yytoken; if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) goto yydefault; yyn = yytable[yyn]; if (yyn <= 0) { if (yytable_value_is_error (yyn)) goto yyerrlab; yyn = -yyn; goto yyreduce; } /* Count tokens shifted since error; after three, turn off error status. */ if (yyerrstatus) yyerrstatus--; /* Shift the lookahead token. */ YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); /* Discard the shifted token. */ yychar = YYEMPTY; yystate = yyn; YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END *++yylsp = yylloc; goto yynewstate; /*-----------------------------------------------------------. | yydefault -- do the default action for the current state. | `-----------------------------------------------------------*/ yydefault: yyn = yydefact[yystate]; if (yyn == 0) goto yyerrlab; goto yyreduce; /*-----------------------------. | yyreduce -- Do a reduction. | `-----------------------------*/ yyreduce: /* yyn is the number of a rule to reduce with. */ yylen = yyr2[yyn]; /* If YYLEN is nonzero, implement the default value of the action: '$$ = $1'. Otherwise, the following line sets YYVAL to garbage. This behavior is undocumented and Bison users should not rely upon it. Assigning to YYVAL unconditionally makes the parser a bit smaller, and it avoids a GCC warning that YYVAL may be used uninitialized. */ yyval = yyvsp[1-yylen]; /* Default location. */ YYLLOC_DEFAULT (yyloc, (yylsp - yylen), yylen); yyerror_range[1] = yyloc; YY_REDUCE_PRINT (yyn); switch (yyn) { case 5: { if (yyget_text(scanner)[0] == '"') { char *tmp; s = malloc(yyget_leng(scanner) - 1 + 7 * yylval.i); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, yyget_leng(scanner) - 2, 0, yylloc.first_column))) { YYABORT; } s = tmp; } else { s = calloc(1, yyget_leng(scanner) - 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } memcpy(s, yyget_text(scanner) + 1, yyget_leng(scanner) - 2); } (yyval.p_str) = &s; } break; case 8: { if (yyget_leng(scanner) > 2) { int length_s = strlen(s), length_tmp = yyget_leng(scanner); char *tmp; tmp = realloc(s, length_s + length_tmp - 1); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } s = tmp; if (yyget_text(scanner)[0] == '"') { if (!(tmp = yang_read_string(trg->ctx, yyget_text(scanner) + 1, s, length_tmp - 2, length_s, yylloc.first_column))) { YYABORT; } s = tmp; } else { memcpy(s + length_s, yyget_text(scanner) + 1, length_tmp - 2); s[length_s + length_tmp - 2] = '\0'; } } } break; case 10: { if (param->submodule) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "module"); YYABORT; } trg = param->module; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = MODULE_KEYWORD; } break; case 12: { if (!param->module->ns) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "namespace", "module"); YYABORT; } if (!param->module->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "prefix", "module"); YYABORT; } } break; case 13: { (yyval.i) = 0; } break; case 14: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 15: { if (yang_read_common(param->module, s, NAMESPACE_KEYWORD)) { YYABORT; } s = NULL; } break; case 16: { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } s = NULL; } break; case 17: { if (!param->submodule) { free(s); LOGVAL(trg->ctx, LYE_SUBMODULE, LY_VLOG_NONE, NULL); YYABORT; } trg = (struct lys_module *)param->submodule; yang_read_common(trg,s,MODULE_KEYWORD); s = NULL; actual_type = SUBMODULE_KEYWORD; } break; case 19: { if (!param->submodule->prefix) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); YYABORT; } if (!(yyvsp[0].i)) { /* check version compatibility with the main module */ if (param->module->version > 1) { LOGVAL(trg->ctx, LYE_INVER, LY_VLOG_NONE, NULL); YYABORT; } } } break; case 20: { (yyval.i) = 0; } break; case 21: { if (yang_check_version(param->module, param->submodule, s, (yyvsp[-1].i))) { YYABORT; } (yyval.i) = 1; s = NULL; } break; case 23: { backup_type = actual_type; actual_type = YANG_VERSION_KEYWORD; } break; case 25: { backup_type = actual_type; actual_type = NAMESPACE_KEYWORD; } break; case 30: { actual_type = (yyvsp[-4].token); backup_type = NODE; actual = NULL; } break; case 31: { YANG_ADDELEM(trg->imp, trg->imp_size, "imports"); /* HACK for unres */ ((struct lys_import *)actual)->module = (struct lys_module *)s; s = NULL; (yyval.token) = actual_type; actual_type = IMPORT_KEYWORD; } break; case 32: { (yyval.i) = 0; } break; case 33: { if (yang_read_prefix(trg, actual, s)) { YYABORT; } s = NULL; } break; case 34: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 35: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "import", IMPORT_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 36: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "import"); free(s); YYABORT; } memcpy(((struct lys_import *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 37: { YANG_ADDELEM(trg->inc, trg->inc_size, "includes"); /* HACK for unres */ ((struct lys_include *)actual)->submodule = (struct lys_submodule *)s; s = NULL; (yyval.token) = actual_type; actual_type = INCLUDE_KEYWORD; } break; case 38: { actual_type = (yyvsp[-1].token); backup_type = NODE; actual = NULL; } break; case 41: { (yyval.i) = 0; } break; case 42: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "description"); free(s); YYABORT; } if (yang_read_description(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 43: { if (trg->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "reference"); free(s); YYABORT; } if (yang_read_reference(trg, actual, s, "include", INCLUDE_KEYWORD)) { YYABORT; } s = NULL; (yyval.i) = (yyvsp[-1].i); } break; case 44: { if ((yyvsp[-1].i)) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "revision-date", "include"); free(s); YYABORT; } memcpy(((struct lys_include *)actual)->rev, s, LY_REV_SIZE-1); free(s); s = NULL; (yyval.i) = 1; } break; case 45: { backup_type = actual_type; actual_type = REVISION_DATE_KEYWORD; } break; case 47: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "belongs-to", ext_name, &s, 0, LY_STMT_BELONGSTO)) { YYABORT; } } else { if (param->submodule->prefix) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "belongs-to", "submodule"); free(s); YYABORT; } if (!ly_strequal(s, param->submodule->belongsto->name, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "belongs-to"); free(s); YYABORT; } free(s); } s = NULL; actual_type = BELONGS_TO_KEYWORD; } break; case 48: { if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", "belongs-to", &s, LY_STMT_BELONGSTO, LY_STMT_PREFIX)) { YYABORT; } } else { if (yang_read_prefix(trg, NULL, s)) { YYABORT; } } s = NULL; actual_type = (yyvsp[-4].token); } break; case 49: { backup_type = actual_type; actual_type = PREFIX_KEYWORD; } break; case 52: { if (yang_read_common(trg, s, ORGANIZATION_KEYWORD)) { YYABORT; } s = NULL; } break; case 53: { if (yang_read_common(trg, s, CONTACT_KEYWORD)) { YYABORT; } s = NULL; } break; case 54: { if (yang_read_description(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s = NULL; } break; case 55: { if (yang_read_reference(trg, NULL, s, NULL, MODULE_KEYWORD)) { YYABORT; } s=NULL; } break; case 56: { backup_type = actual_type; actual_type = ORGANIZATION_KEYWORD; } break; case 58: { backup_type = actual_type; actual_type = CONTACT_KEYWORD; } break; case 60: { backup_type = actual_type; actual_type = DESCRIPTION_KEYWORD; } break; case 62: { backup_type = actual_type; actual_type = REFERENCE_KEYWORD; } break; case 64: { if (trg->rev_size) { struct lys_revision *tmp; tmp = realloc(trg->rev, trg->rev_size * sizeof *trg->rev); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->rev = tmp; } } break; case 65: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!is_ext_instance) { YANG_ADDELEM(trg->rev, trg->rev_size, "revisions"); } memcpy(((struct lys_revision *)actual)->date, s, LY_REV_SIZE); free(s); s = NULL; actual_type = REVISION_KEYWORD; } break; case 67: { int i; /* check uniqueness of the revision date - not required by RFC */ for (i = 0; i < (trg->rev_size - 1); i++) { if (!strcmp(trg->rev[i].date, trg->rev[trg->rev_size - 1].date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", trg->rev[trg->rev_size - 1].date); break; } } } break; case 68: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 72: { if (yang_read_description(trg, actual, s, "revision",REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 73: { if (yang_read_reference(trg, actual, s, "revision", REVISION_KEYWORD)) { YYABORT; } s = NULL; } break; case 74: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 76: { if (lyp_check_date(trg->ctx, s)) { free(s); YYABORT; } } break; case 77: { void *tmp; if (trg->tpdf_size) { tmp = realloc(trg->tpdf, trg->tpdf_size * sizeof *trg->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->tpdf = tmp; } if (trg->features_size) { tmp = realloc(trg->features, trg->features_size * sizeof *trg->features); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->features = tmp; } if (trg->ident_size) { tmp = realloc(trg->ident, trg->ident_size * sizeof *trg->ident); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->ident = tmp; } if (trg->augment_size) { tmp = realloc(trg->augment, trg->augment_size * sizeof *trg->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->augment = tmp; } if (trg->extensions_size) { tmp = realloc(trg->extensions, trg->extensions_size * sizeof *trg->extensions); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } trg->extensions = tmp; } } break; case 78: { /* check the module with respect to the context now */ if (!param->submodule) { switch (lyp_ctx_check_module(trg)) { case -1: YYABORT; case 0: break; case 1: /* it's already there */ param->flags |= YANG_EXIST_MODULE; YYABORT; } } param->flags &= (~YANG_REMOVE_IMPORT); if (yang_check_imports(trg, param->unres)) { YYABORT; } actual = NULL; } break; case 79: { actual = NULL; } break; case 90: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->extensions, trg->extensions_size, "extensions"); trg->extensions_size--; ((struct lys_ext *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_ext *)actual)->module = trg; if (lyp_check_identifier(trg->ctx, ((struct lys_ext *)actual)->name, LY_IDENT_EXTENSION, trg, NULL)) { trg->extensions_size++; YYABORT; } trg->extensions_size++; s = NULL; actual_type = EXTENSION_KEYWORD; } break; case 91: { struct lys_ext *ext = actual; ext->plugin = ext_get_plugin(ext->name, ext->module->name, ext->module->rev ? ext->module->rev[0].date : NULL); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 96: { if (((struct lys_ext *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "extension"); YYABORT; } ((struct lys_ext *)actual)->flags |= (yyvsp[0].i); } break; case 97: { if (yang_read_description(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 98: { if (yang_read_reference(trg, actual, s, "extension", NODE)) { YYABORT; } s = NULL; } break; case 99: { (yyval.token) = actual_type; if (is_ext_instance) { if (yang_read_extcomplex_str(trg, ext_instance, "argument", ext_name, &s, 0, LY_STMT_ARGUMENT)) { YYABORT; } } else { if (((struct lys_ext *)actual)->argument) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "argument", "extension"); free(s); YYABORT; } ((struct lys_ext *)actual)->argument = lydict_insert_zc(param->module->ctx, s); } s = NULL; actual_type = ARGUMENT_KEYWORD; } break; case 100: { actual_type = (yyvsp[-1].token); } break; case 103: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = YIN_ELEMENT_KEYWORD; } break; case 105: { if (is_ext_instance) { int c; const char ***p; uint8_t *val; struct lyext_substmt *info; c = 0; p = lys_ext_complex_get_substmt(LY_STMT_ARGUMENT, ext_instance, &info); if (info->cardinality >= LY_STMT_CARD_SOME) { /* get the index in the array to add new item */ for (c = 0; p[0][c + 1]; c++); val = (uint8_t *)p[1]; } else { val = (uint8_t *)(p + 1); } val[c] = ((yyvsp[-1].uint) == LYS_YINELEM) ? 1 : 2; } else { ((struct lys_ext *)actual)->flags |= (yyvsp[-1].uint); } } break; case 106: { (yyval.uint) = LYS_YINELEM; } break; case 107: { (yyval.uint) = 0; } break; case 108: { if (!strcmp(s, "true")) { (yyval.uint) = LYS_YINELEM; } else if (!strcmp(s, "false")) { (yyval.uint) = 0; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 109: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = STATUS_KEYWORD; } break; case 110: { (yyval.i) = (yyvsp[-1].i); } break; case 111: { (yyval.i) = LYS_STATUS_CURR; } break; case 112: { (yyval.i) = LYS_STATUS_OBSLT; } break; case 113: { (yyval.i) = LYS_STATUS_DEPRC; } break; case 114: { if (!strcmp(s, "current")) { (yyval.i) = LYS_STATUS_CURR; } else if (!strcmp(s, "obsolete")) { (yyval.i) = LYS_STATUS_OBSLT; } else if (!strcmp(s, "deprecated")) { (yyval.i) = LYS_STATUS_DEPRC; } else { LOGVAL(trg->ctx,LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } free(s); s = NULL; } break; case 115: { /* check uniqueness of feature's names */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_FEATURE, trg, NULL)) { free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->features, trg->features_size, "features"); ((struct lys_feature *)actual)->name = lydict_insert_zc(trg->ctx, s); ((struct lys_feature *)actual)->module = trg; s = NULL; actual_type = FEATURE_KEYWORD; } break; case 116: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 118: { struct lys_iffeature *tmp; if (((struct lys_feature *)actual)->iffeature_size) { tmp = realloc(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_feature *)actual)->iffeature = tmp; } } break; case 121: { if (((struct lys_feature *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "feature"); YYABORT; } ((struct lys_feature *)actual)->flags |= (yyvsp[0].i); } break; case 122: { if (yang_read_description(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 123: { if (yang_read_reference(trg, actual, s, "feature", NODE)) { YYABORT; } s = NULL; } break; case 124: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case FEATURE_KEYWORD: YANG_ADDELEM(((struct lys_feature *)actual)->iffeature, ((struct lys_feature *)actual)->iffeature_size, "if-features"); break; case IDENTITY_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "identity"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size, "if-features"); break; case ENUM_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size, "if-features"); break; case BIT_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature", "bit"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size, "if-features"); break; case REFINE_KEYWORD: if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "if-feature"); free(s); YYABORT; } YANG_ADDELEM(((struct lys_refine *)actual)->iffeature, ((struct lys_refine *)actual)->iffeature_size, "if-features"); break; case EXTENSION_INSTANCE: /* nothing change */ break; default: /* lys_node_* */ YANG_ADDELEM(((struct lys_node *)actual)->iffeature, ((struct lys_node *)actual)->iffeature_size, "if-features"); break; } ((struct lys_iffeature *)actual)->features = (struct lys_feature **)s; s = NULL; actual_type = IF_FEATURE_KEYWORD; } break; case 125: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 128: { const char *tmp; tmp = lydict_insert_zc(trg->ctx, s); s = NULL; if (dup_identities_check(tmp, trg)) { lydict_remove(trg->ctx, tmp); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->ident, trg->ident_size, "identities"); ((struct lys_ident *)actual)->name = tmp; ((struct lys_ident *)actual)->module = trg; actual_type = IDENTITY_KEYWORD; } break; case 129: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 131: { void *tmp; if (((struct lys_ident *)actual)->base_size) { tmp = realloc(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size * sizeof *((struct lys_ident *)actual)->base); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->base = tmp; } if (((struct lys_ident *)actual)->iffeature_size) { tmp = realloc(((struct lys_ident *)actual)->iffeature, ((struct lys_ident *)actual)->iffeature_size * sizeof *((struct lys_ident *)actual)->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ident *)actual)->iffeature = tmp; } } break; case 133: { void *identity; if ((trg->version < 2) && ((struct lys_ident *)actual)->base_size) { free(s); LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "base", "identity"); YYABORT; } identity = actual; YANG_ADDELEM(((struct lys_ident *)actual)->base, ((struct lys_ident *)actual)->base_size, "bases"); *((struct lys_ident **)actual) = (struct lys_ident *)s; s = NULL; actual = identity; } break; case 135: { if (((struct lys_ident *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "identity"); YYABORT; } ((struct lys_ident *)actual)->flags |= (yyvsp[0].i); } break; case 136: { if (yang_read_description(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 137: { if (yang_read_reference(trg, actual, s, "identity", NODE)) { YYABORT; } s = NULL; } break; case 138: { backup_type = actual_type; actual_type = BASE_KEYWORD; } break; case 140: { tpdf_parent = (actual_type == EXTENSION_INSTANCE) ? ext_instance : actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (lyp_check_identifier(trg->ctx, s, LY_IDENT_TYPE, trg, tpdf_parent)) { free(s); YYABORT; } switch (actual_type) { case MODULE_KEYWORD: case SUBMODULE_KEYWORD: YANG_ADDELEM(trg->tpdf, trg->tpdf_size, "typedefs"); break; case GROUPING_KEYWORD: YANG_ADDELEM(((struct lys_node_grp *)tpdf_parent)->tpdf, ((struct lys_node_grp *)tpdf_parent)->tpdf_size, "typedefs"); break; case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)tpdf_parent)->tpdf, ((struct lys_node_container *)tpdf_parent)->tpdf_size, "typedefs"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)tpdf_parent)->tpdf, ((struct lys_node_list *)tpdf_parent)->tpdf_size, "typedefs"); break; case RPC_KEYWORD: case ACTION_KEYWORD: YANG_ADDELEM(((struct lys_node_rpc_action *)tpdf_parent)->tpdf, ((struct lys_node_rpc_action *)tpdf_parent)->tpdf_size, "typedefs"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: YANG_ADDELEM(((struct lys_node_inout *)tpdf_parent)->tpdf, ((struct lys_node_inout *)tpdf_parent)->tpdf_size, "typedefs"); break; case NOTIFICATION_KEYWORD: YANG_ADDELEM(((struct lys_node_notif *)tpdf_parent)->tpdf, ((struct lys_node_notif *)tpdf_parent)->tpdf_size, "typedefs"); break; case EXTENSION_INSTANCE: /* typedef is already allocated */ break; default: /* another type of nodetype is error*/ LOGINT(trg->ctx); free(s); YYABORT; } ((struct lys_tpdf *)actual)->name = lydict_insert_zc(param->module->ctx, s); ((struct lys_tpdf *)actual)->module = trg; s = NULL; actual_type = TYPEDEF_KEYWORD; } break; case 141: { if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "type", "typedef"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 142: { (yyval.nodes).node.ptr_tpdf = actual; (yyval.nodes).node.flag = 0; } break; case 143: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 144: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 145: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, TYPEDEF_KEYWORD)) { YYABORT; } s = NULL; } break; case 146: { if ((yyvsp[-1].nodes).node.ptr_tpdf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "typedef"); YYABORT; } (yyvsp[-1].nodes).node.ptr_tpdf->flags |= (yyvsp[0].i); } break; case 147: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 148: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_tpdf, s, "typedef", NODE)) { YYABORT; } s = NULL; } break; case 149: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 150: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_type(trg->ctx, actual, s, actual_type))) { YYABORT; } s = NULL; actual_type = TYPE_KEYWORD; } break; case 153: { if (((struct yang_type *)actual)->base == LY_TYPE_STRING && ((struct yang_type *)actual)->type->info.str.pat_count) { void *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns = tmp; #ifdef LY_ENABLED_CACHE if (!(trg->ctx->models.flags & LY_CTX_TRUSTED) && ((struct yang_type *)actual)->type->info.str.patterns_pcre) { tmp = realloc(((struct yang_type *)actual)->type->info.str.patterns_pcre, 2 * ((struct yang_type *)actual)->type->info.str.pat_count * sizeof *((struct yang_type *)actual)->type->info.str.patterns_pcre); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.str.patterns_pcre = tmp; } #endif } if (((struct yang_type *)actual)->base == LY_TYPE_UNION) { struct lys_type *tmp; tmp = realloc(((struct yang_type *)actual)->type->info.uni.types, ((struct yang_type *)actual)->type->info.uni.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.uni.types = tmp; } if (((struct yang_type *)actual)->base == LY_TYPE_IDENT) { struct lys_ident **tmp; tmp = realloc(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count* sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.ident.ref = tmp; } } break; case 157: { if (yang_read_require_instance(trg->ctx, actual, (yyvsp[0].i))) { YYABORT; } } break; case 158: { /* leafref_specification */ if (yang_read_leafref_path(trg, actual, s)) { YYABORT; } s = NULL; } break; case 159: { /* identityref_specification */ if (((struct yang_type *)actual)->base && ((struct yang_type *)actual)->base != LY_TYPE_IDENT) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "base"); return EXIT_FAILURE; } ((struct yang_type *)actual)->base = LY_TYPE_IDENT; yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.ident.ref, ((struct yang_type *)actual)->type->info.ident.count, "identity refs"); *((struct lys_ident **)actual) = (struct lys_ident *)s; actual = yang_type; s = NULL; } break; case 162: { if (yang_read_fraction(trg->ctx, actual, (yyvsp[0].uint))) { YYABORT; } } break; case 165: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 166: { struct yang_type *stype = (struct yang_type *)actual; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (stype->base != 0 && stype->base != LY_TYPE_UNION) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected type statement."); YYABORT; } stype->base = LY_TYPE_UNION; if (strcmp(stype->name, "union")) { /* type can be a substatement only in "union" type, not in derived types */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_NONE, NULL, "type", "derived type"); YYABORT; } YANG_ADDELEM(stype->type->info.uni.types, stype->type->info.uni.count, "union types") actual_type = UNION_KEYWORD; } break; case 167: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = FRACTION_DIGITS_KEYWORD; } break; case 168: { (yyval.uint) = (yyvsp[-1].uint); } break; case 169: { (yyval.uint) = (yyvsp[-1].uint); } break; case 170: { char *endptr = NULL; unsigned long val; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "fraction-digits"); free(s); s = NULL; YYABORT; } (yyval.uint) = (uint32_t) val; free(s); s =NULL; } break; case 171: { actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 172: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_length(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = LENGTH_KEYWORD; s = NULL; } break; case 175: { switch (actual_type) { case MUST_KEYWORD: (yyval.str) = "must"; break; case LENGTH_KEYWORD: (yyval.str) = "length"; break; case RANGE_KEYWORD: (yyval.str) = "range"; break; default: LOGINT(trg->ctx); YYABORT; break; } } break; case 176: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 177: { if (yang_read_message(trg, actual, s, (yyvsp[-1].str), ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 178: { if (yang_read_description(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 179: { if (yang_read_reference(trg, actual, s, (yyvsp[-1].str), NODE)) { YYABORT; } s = NULL; } break; case 180: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; } break; case 181: {struct lys_restr *pattern = actual; actual = NULL; #ifdef LY_ENABLED_CACHE if ((yyvsp[-2].backup_token).token != EXTENSION_INSTANCE && !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); ++c; YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); actual = &(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1)]; } #endif if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { YYABORT; } actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 182: { if (actual_type != EXTENSION_INSTANCE) { if (((struct yang_type *)actual)->base != 0 && ((struct yang_type *)actual)->base != LY_TYPE_STRING) { free(s); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Unexpected pattern statement."); YYABORT; } ((struct yang_type *)actual)->base = LY_TYPE_STRING; YANG_ADDELEM(((struct yang_type *)actual)->type->info.str.patterns, ((struct yang_type *)actual)->type->info.str.pat_count, "patterns"); } (yyval.str) = s; s = NULL; actual_type = PATTERN_KEYWORD; } break; case 183: { (yyval.ch) = 0x06; } break; case 184: { (yyval.ch) = (yyvsp[-1].ch); } break; case 185: { (yyval.ch) = 0x06; /* ACK */ } break; case 186: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, "modifier"); YYABORT; } if ((yyvsp[-1].ch) != 0x06) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "modifier", "pattern"); YYABORT; } (yyval.ch) = (yyvsp[0].ch); } break; case 187: { if (yang_read_message(trg, actual, s, "pattern", ERROR_MESSAGE_KEYWORD)) { YYABORT; } s = NULL; } break; case 188: { if (yang_read_message(trg, actual, s, "pattern", ERROR_APP_TAG_KEYWORD)) { YYABORT; } s = NULL; } break; case 189: { if (yang_read_description(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 190: { if (yang_read_reference(trg, actual, s, "pattern", NODE)) { YYABORT; } s = NULL; } break; case 191: { backup_type = actual_type; actual_type = MODIFIER_KEYWORD; } break; case 192: { if (!strcmp(s, "invert-match")) { (yyval.ch) = 0x15; free(s); s = NULL; } else { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, s); free(s); YYABORT; } } break; case 193: { struct lys_type_enum * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.enums.enm = tmp; } break; case 196: { if (yang_check_enum(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-1].backup_token).actual; actual_type = (yyvsp[-1].backup_token).token; } break; case 197: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.enums.enm, ((struct yang_type *)actual)->type->info.enums.count, "enums"); if (yang_read_enum(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = ENUM_KEYWORD; } break; case 199: { if (((struct lys_type_enum *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_enum *)actual)->iffeature, ((struct lys_type_enum *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_enum *)actual)->iffeature = tmp; } } break; case 202: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "value", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->value = (yyvsp[0].i); /* keep the highest enum value for automatic increment */ if ((yyvsp[0].i) >= cnt_val) { cnt_val = (yyvsp[0].i) + 1; } is_value = 1; } break; case 203: { if (((struct lys_type_enum *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "enum"); YYABORT; } ((struct lys_type_enum *)actual)->flags |= (yyvsp[0].i); } break; case 204: { if (yang_read_description(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 205: { if (yang_read_reference(trg, actual, s, "enum", NODE)) { YYABORT; } s = NULL; } break; case 206: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = VALUE_KEYWORD; } break; case 207: { (yyval.i) = (yyvsp[-1].i); } break; case 208: { (yyval.i) = (yyvsp[-1].i); } break; case 209: { /* convert it to int32_t */ int64_t val; char *endptr; val = strtoll(s, &endptr, 10); if (val < INT32_MIN || val > INT32_MAX || *endptr) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "value"); free(s); YYABORT; } free(s); s = NULL; (yyval.i) = (int32_t) val; } break; case 210: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 213: { backup_type = actual_type; actual_type = PATH_KEYWORD; } break; case 215: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = REQUIRE_INSTANCE_KEYWORD; } break; case 216: { (yyval.i) = (yyvsp[-1].i); } break; case 217: { (yyval.i) = 1; } break; case 218: { (yyval.i) = -1; } break; case 219: { if (!strcmp(s,"true")) { (yyval.i) = 1; } else if (!strcmp(s,"false")) { (yyval.i) = -1; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "require-instance"); free(s); YYABORT; } free(s); s = NULL; } break; case 220: { struct lys_type_bit * tmp; cnt_val = 0; tmp = realloc(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct yang_type *)actual)->type->info.bits.bit = tmp; } break; case 223: { if (yang_check_bit(trg->ctx, yang_type, actual, &cnt_val, is_value)) { YYABORT; } actual = (yyvsp[-2].backup_token).actual; actual_type = (yyvsp[-2].backup_token).token; } break; case 224: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = yang_type = actual; YANG_ADDELEM(((struct yang_type *)actual)->type->info.bits.bit, ((struct yang_type *)actual)->type->info.bits.count, "bits"); if (yang_read_bit(trg->ctx, yang_type, actual, s)) { YYABORT; } s = NULL; is_value = 0; actual_type = BIT_KEYWORD; } break; case 226: { if (((struct lys_type_bit *)actual)->iffeature_size) { struct lys_iffeature *tmp; tmp = realloc(((struct lys_type_bit *)actual)->iffeature, ((struct lys_type_bit *)actual)->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_type_bit *)actual)->iffeature = tmp; } } break; case 229: { if (is_value) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "position", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->pos = (yyvsp[0].uint); /* keep the highest position value for automatic increment */ if ((yyvsp[0].uint) >= cnt_val) { cnt_val = (yyvsp[0].uint) + 1; } is_value = 1; } break; case 230: { if (((struct lys_type_bit *)actual)->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "status", "bit"); YYABORT; } ((struct lys_type_bit *)actual)->flags |= (yyvsp[0].i); } break; case 231: { if (yang_read_description(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 232: { if (yang_read_reference(trg, actual, s, "bit", NODE)) { YYABORT; } s = NULL; } break; case 233: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = POSITION_KEYWORD; } break; case 234: { (yyval.uint) = (yyvsp[-1].uint); } break; case 235: { (yyval.uint) = (yyvsp[-1].uint); } break; case 236: { /* convert it to uint32_t */ unsigned long val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (s[0] == '-' || *endptr || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "position"); free(s); YYABORT; } free(s); s = NULL; (yyval.uint) = (uint32_t) val; } break; case 237: { backup_type = actual_type; actual_type = ERROR_MESSAGE_KEYWORD; } break; case 239: { backup_type = actual_type; actual_type = ERROR_APP_TAG_KEYWORD; } break; case 241: { backup_type = actual_type; actual_type = UNITS_KEYWORD; } break; case 243: { backup_type = actual_type; actual_type = DEFAULT_KEYWORD; } break; case 245: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_GROUPING, sizeof(struct lys_node_grp)))) { YYABORT; } s = NULL; data_node = actual; actual_type = GROUPING_KEYWORD; } break; case 246: { LOGDBG(LY_LDGYANG, "finished parsing grouping statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 249: { (yyval.nodes).grouping = actual; } break; case 250: { if ((yyvsp[-1].nodes).grouping->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).grouping, "status", "grouping"); YYABORT; } (yyvsp[-1].nodes).grouping->flags |= (yyvsp[0].i); } break; case 251: { if (yang_read_description(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 252: { if (yang_read_reference(trg, (yyvsp[-1].nodes).grouping, s, "grouping", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 257: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).grouping, "notification"); YYABORT; } } break; case 266: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CONTAINER, sizeof(struct lys_node_container)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CONTAINER_KEYWORD; } break; case 267: { LOGDBG(LY_LDGYANG, "finished parsing container statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 269: { void *tmp; if ((yyvsp[-1].nodes).container->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).container->iffeature, (yyvsp[-1].nodes).container->iffeature_size * sizeof *(yyvsp[-1].nodes).container->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->iffeature = tmp; } if ((yyvsp[-1].nodes).container->must_size) { tmp = realloc((yyvsp[-1].nodes).container->must, (yyvsp[-1].nodes).container->must_size * sizeof *(yyvsp[-1].nodes).container->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).container->must = tmp; } } break; case 270: { (yyval.nodes).container = actual; } break; case 274: { if (yang_read_presence(trg, (yyvsp[-1].nodes).container, s)) { YYABORT; } s = NULL; } break; case 275: { if ((yyvsp[-1].nodes).container->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "config", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 276: { if ((yyvsp[-1].nodes).container->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).container, "status", "container"); YYABORT; } (yyvsp[-1].nodes).container->flags |= (yyvsp[0].i); } break; case 277: { if (yang_read_description(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 278: { if (yang_read_reference(trg, (yyvsp[-1].nodes).container, s, "container", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 281: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).container, "notification"); YYABORT; } } break; case 284: { void *tmp; if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "type", "leaf"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->dflt && ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_TRUE)) { /* RFC 6020, 7.6.4 - default statement must not with mandatory true */ LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "The \"mandatory\" statement is forbidden on leaf with \"default\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaf->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->iffeature, (yyvsp[-1].nodes).node.ptr_leaf->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaf->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaf->must, (yyvsp[-1].nodes).node.ptr_leaf->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaf->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->must = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 285: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAF, sizeof(struct lys_node_leaf)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_KEYWORD; } break; case 286: { (yyval.nodes).node.ptr_leaf = actual; (yyval.nodes).node.flag = 0; } break; case 289: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 290: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 292: { if (yang_read_default(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, LEAF_KEYWORD)) { YYABORT; } s = NULL; } break; case 293: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "config", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 294: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "mandatory", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 295: { if ((yyvsp[-1].nodes).node.ptr_leaf->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaf, "status", "leaf"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaf->flags |= (yyvsp[0].i); } break; case 296: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 297: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaf, s, "leaf", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 298: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LEAFLIST, sizeof(struct lys_node_leaflist)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LEAF_LIST_KEYWORD; } break; case 299: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_R) { /* RFC 6020, 7.7.5 - ignore ordering when the list represents state data * ignore oredering MASK - 0x7F */ (yyvsp[-1].nodes).node.ptr_leaflist->flags &= 0x7F; } if (!((yyvsp[-1].nodes).node.flag & LYS_TYPE_DEF)) { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "type", "leaf-list"); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size && (yyvsp[-1].nodes).node.ptr_leaflist->min) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "The \"min-elements\" statement with non-zero value is forbidden on leaf-lists with the \"default\" statement."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->iffeature, (yyvsp[-1].nodes).node.ptr_leaflist->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->must, (yyvsp[-1].nodes).node.ptr_leaflist->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_leaflist->dflt_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size * sizeof *(yyvsp[-1].nodes).node.ptr_leaflist->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->dflt = tmp; } LOGDBG(LY_LDGYANG, "finished parsing leaf-list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 300: { (yyval.nodes).node.ptr_leaflist = actual; (yyval.nodes).node.flag = 0; } break; case 303: { (yyvsp[-2].nodes).node.flag |= LYS_TYPE_DEF; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 304: { if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "default"); YYABORT; } YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_leaflist->dflt, (yyvsp[-1].nodes).node.ptr_leaflist->dflt_size, "defaults"); (*(const char **)actual) = lydict_insert_zc(param->module->ctx, s); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_leaflist; } break; case 305: { if (yang_read_units(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, LEAF_LIST_KEYWORD)) { YYABORT; } s = NULL; } break; case 307: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "config", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 308: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "min-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->max && ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 309: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "max-elements", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_leaflist->min > (yyvsp[-1].nodes).node.ptr_leaflist->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "max-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 310: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "ordered by", "leaf-list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_leaflist->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 311: { if ((yyvsp[-1].nodes).node.ptr_leaflist->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_leaflist, "status", "leaf-list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_leaflist->flags |= (yyvsp[0].i); } break; case 312: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 313: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_leaflist, s, "leaf-list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 314: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_LIST, sizeof(struct lys_node_list)))) { YYABORT; } data_node = actual; s = NULL; actual_type = LIST_KEYWORD; } break; case 315: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_list->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->iffeature, (yyvsp[-1].nodes).node.ptr_list->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->must, (yyvsp[-1].nodes).node.ptr_list->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->must = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->tpdf, (yyvsp[-1].nodes).node.ptr_list->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->tpdf = tmp; } if ((yyvsp[-1].nodes).node.ptr_list->unique_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size * sizeof *(yyvsp[-1].nodes).node.ptr_list->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->unique = tmp; } LOGDBG(LY_LDGYANG, "finished parsing list statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 316: { (yyval.nodes).node.ptr_list = actual; (yyval.nodes).node.flag = 0; } break; case 320: { if ((yyvsp[-1].nodes).node.ptr_list->keys) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "key", "list"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->keys = (struct lys_node_leaf **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; } break; case 321: { YANG_ADDELEM((yyvsp[-1].nodes).node.ptr_list->unique, (yyvsp[-1].nodes).node.ptr_list->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; (yyval.nodes) = (yyvsp[-1].nodes); s = NULL; actual = (yyvsp[-1].nodes).node.ptr_list; } break; case 322: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "config", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 323: { if ((yyvsp[-1].nodes).node.flag & LYS_MIN_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "min-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->min = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MIN_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->max && ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max)) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"min-elements\" is bigger than \"max-elements\"."); YYABORT; } } break; case 324: { if ((yyvsp[-1].nodes).node.flag & LYS_MAX_ELEMENTS) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "max-elements", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->max = (yyvsp[0].uint); (yyvsp[-1].nodes).node.flag |= LYS_MAX_ELEMENTS; (yyval.nodes) = (yyvsp[-1].nodes); if ((yyvsp[-1].nodes).node.ptr_list->min > (yyvsp[-1].nodes).node.ptr_list->max) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "min-elements"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "\"max-elements\" is smaller than \"min-elements\"."); YYABORT; } } break; case 325: { if ((yyvsp[-1].nodes).node.flag & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "ordered by", "list"); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { (yyvsp[-1].nodes).node.ptr_list->flags |= LYS_USERORDERED; } (yyvsp[-1].nodes).node.flag |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 326: { if ((yyvsp[-1].nodes).node.ptr_list->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_list, "status", "list"); YYABORT; } (yyvsp[-1].nodes).node.ptr_list->flags |= (yyvsp[0].i); } break; case 327: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 328: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_list, s, "list", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 332: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_list, "notification"); YYABORT; } } break; case 334: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CHOICE, sizeof(struct lys_node_choice)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CHOICE_KEYWORD; } break; case 335: { LOGDBG(LY_LDGYANG, "finished parsing choice statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 337: { struct lys_iffeature *tmp; if (((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_TRUE) && (yyvsp[-1].nodes).node.ptr_choice->dflt) { LOGVAL(trg->ctx, LYE_INCHILDSTMT, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "The \"default\" statement is forbidden on choices with \"mandatory\"."); YYABORT; } if ((yyvsp[-1].nodes).node.ptr_choice->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_choice->iffeature, (yyvsp[-1].nodes).node.ptr_choice->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->iffeature = tmp; } } break; case 338: { (yyval.nodes).node.ptr_choice = actual; (yyval.nodes).node.flag = 0; } break; case 341: { if ((yyvsp[-1].nodes).node.flag & LYS_CHOICE_DEFAULT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "default", "choice"); free(s); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->dflt = (struct lys_node *) s; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); (yyval.nodes).node.flag |= LYS_CHOICE_DEFAULT; } break; case 342: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "config", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 343: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "mandatory", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 344: { if ((yyvsp[-1].nodes).node.ptr_choice->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_choice, "status", "choice"); YYABORT; } (yyvsp[-1].nodes).node.ptr_choice->flags |= (yyvsp[0].i); (yyval.nodes) = (yyvsp[-1].nodes); } break; case 345: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 346: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_choice, s, "choice", NODE_PRINT)) { YYABORT; } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 356: { if (trg->version < 2 ) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "choice"); YYABORT; } } break; case 357: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_CASE, sizeof(struct lys_node_case)))) { YYABORT; } data_node = actual; s = NULL; actual_type = CASE_KEYWORD; } break; case 358: { LOGDBG(LY_LDGYANG, "finished parsing case statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 360: { struct lys_iffeature *tmp; if ((yyvsp[-1].nodes).cs->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).cs->iffeature, (yyvsp[-1].nodes).cs->iffeature_size * sizeof *tmp); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).cs->iffeature = tmp; } } break; case 361: { (yyval.nodes).cs = actual; } break; case 364: { if ((yyvsp[-1].nodes).cs->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).cs, "status", "case"); YYABORT; } (yyvsp[-1].nodes).cs->flags |= (yyvsp[0].i); } break; case 365: { if (yang_read_description(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 366: { if (yang_read_reference(trg, (yyvsp[-1].nodes).cs, s, "case", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 368: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYXML, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYXML_KEYWORD; } break; case 369: { LOGDBG(LY_LDGYANG, "finished parsing anyxml statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 370: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ANYDATA, sizeof(struct lys_node_anydata)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ANYDATA_KEYWORD; } break; case 371: { LOGDBG(LY_LDGYANG, "finished parsing anydata statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 373: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_anydata->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->iffeature, (yyvsp[-1].nodes).node.ptr_anydata->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_anydata->must_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_anydata->must, (yyvsp[-1].nodes).node.ptr_anydata->must_size * sizeof *(yyvsp[-1].nodes).node.ptr_anydata->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->must = tmp; } } break; case 374: { (yyval.nodes).node.ptr_anydata = actual; (yyval.nodes).node.flag = actual_type; } break; case 378: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "config", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 379: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "mandatory", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 380: { if ((yyvsp[-1].nodes).node.ptr_anydata->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_anydata, "status", ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata"); YYABORT; } (yyvsp[-1].nodes).node.ptr_anydata->flags |= (yyvsp[0].i); } break; case 381: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 382: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_anydata, s, ((yyvsp[-1].nodes).node.flag == ANYXML_KEYWORD) ? "anyxml" : "anydata", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 383: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_USES, sizeof(struct lys_node_uses)))) { YYABORT; } data_node = actual; s = NULL; actual_type = USES_KEYWORD; } break; case 384: { LOGDBG(LY_LDGYANG, "finished parsing uses statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 386: { void *tmp; if ((yyvsp[-1].nodes).uses->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).uses->iffeature, (yyvsp[-1].nodes).uses->iffeature_size * sizeof *(yyvsp[-1].nodes).uses->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->iffeature = tmp; } if ((yyvsp[-1].nodes).uses->refine_size) { tmp = realloc((yyvsp[-1].nodes).uses->refine, (yyvsp[-1].nodes).uses->refine_size * sizeof *(yyvsp[-1].nodes).uses->refine); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->refine = tmp; } if ((yyvsp[-1].nodes).uses->augment_size) { tmp = realloc((yyvsp[-1].nodes).uses->augment, (yyvsp[-1].nodes).uses->augment_size * sizeof *(yyvsp[-1].nodes).uses->augment); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).uses->augment = tmp; } } break; case 387: { (yyval.nodes).uses = actual; } break; case 390: { if ((yyvsp[-1].nodes).uses->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).uses, "status", "uses"); YYABORT; } (yyvsp[-1].nodes).uses->flags |= (yyvsp[0].i); } break; case 391: { if (yang_read_description(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 392: { if (yang_read_reference(trg, (yyvsp[-1].nodes).uses, s, "uses", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 397: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->refine, ((struct lys_node_uses *)actual)->refine_size, "refines"); ((struct lys_refine *)actual)->target_name = transform_schema2json(trg, s); free(s); s = NULL; if (!((struct lys_refine *)actual)->target_name) { YYABORT; } actual_type = REFINE_KEYWORD; } break; case 398: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 400: { void *tmp; if ((yyvsp[-1].nodes).refine->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).refine->iffeature, (yyvsp[-1].nodes).refine->iffeature_size * sizeof *(yyvsp[-1].nodes).refine->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->iffeature = tmp; } if ((yyvsp[-1].nodes).refine->must_size) { tmp = realloc((yyvsp[-1].nodes).refine->must, (yyvsp[-1].nodes).refine->must_size * sizeof *(yyvsp[-1].nodes).refine->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->must = tmp; } if ((yyvsp[-1].nodes).refine->dflt_size) { tmp = realloc((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size * sizeof *(yyvsp[-1].nodes).refine->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).refine->dflt = tmp; } } break; case 401: { (yyval.nodes).refine = actual; actual_type = REFINE_KEYWORD; } break; case 402: { actual = (yyvsp[-2].nodes).refine; actual_type = REFINE_KEYWORD; if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "must", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYXML; } } break; case 403: { /* leaf, leaf-list, list, container or anyxml */ /* check possibility of statements combination */ if ((yyvsp[-2].nodes).refine->target_type) { if ((yyvsp[-2].nodes).refine->target_type & (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA)) { (yyvsp[-2].nodes).refine->target_type &= (LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "if-feature", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-2].nodes).refine->target_type = LYS_LEAF | LYS_LIST | LYS_LEAFLIST | LYS_CONTAINER | LYS_ANYDATA; } } break; case 404: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & LYS_CONTAINER) { if ((yyvsp[-1].nodes).refine->mod.presence) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "presence", "refine"); free(s); YYABORT; } (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "presence", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_CONTAINER; (yyvsp[-1].nodes).refine->mod.presence = lydict_insert_zc(trg->ctx, s); } s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 405: { int i; if ((yyvsp[-1].nodes).refine->dflt_size) { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "default", "refine"); YYABORT; } if ((yyvsp[-1].nodes).refine->target_type & LYS_LEAFLIST) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAFLIST; } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if ((yyvsp[-1].nodes).refine->target_type) { if (trg->version < 2 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE))) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE); } if (trg->version > 1 && ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE))) { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE); } else { free(s); LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "default", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { if (trg->version < 2) { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE; } else { /* YANG 1.1 */ (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_LEAFLIST | LYS_CHOICE; } } } /* check for duplicity */ for (i = 0; i < (yyvsp[-1].nodes).refine->dflt_size; ++i) { if (ly_strequal((yyvsp[-1].nodes).refine->dflt[i], s, 0)) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "default"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Duplicated default value \"%s\".", s); YYABORT; } } YANG_ADDELEM((yyvsp[-1].nodes).refine->dflt, (yyvsp[-1].nodes).refine->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); actual = (yyvsp[-1].nodes).refine; s = NULL; (yyval.nodes) = (yyvsp[-1].nodes); } break; case 406: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "config", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_LIST | LYS_CONTAINER | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 407: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LEAF | LYS_CHOICE | LYS_ANYXML)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LEAF | LYS_CHOICE | LYS_ANYXML); if ((yyvsp[-1].nodes).refine->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "mandatory", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LEAF | LYS_CHOICE | LYS_ANYXML; (yyvsp[-1].nodes).refine->flags |= (yyvsp[0].i); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 408: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MINSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "min-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MINSET; (yyvsp[-1].nodes).refine->mod.list.min = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 409: { if ((yyvsp[-1].nodes).refine->target_type) { if ((yyvsp[-1].nodes).refine->target_type & (LYS_LIST | LYS_LEAFLIST)) { (yyvsp[-1].nodes).refine->target_type &= (LYS_LIST | LYS_LEAFLIST); if ((yyvsp[-1].nodes).refine->flags & LYS_RFN_MAXSET) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "refine"); YYABORT; } (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "max-elements", "refine"); LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid refine target nodetype for the substatements."); YYABORT; } } else { (yyvsp[-1].nodes).refine->target_type = LYS_LIST | LYS_LEAFLIST; (yyvsp[-1].nodes).refine->flags |= LYS_RFN_MAXSET; (yyvsp[-1].nodes).refine->mod.list.max = (yyvsp[0].uint); } (yyval.nodes) = (yyvsp[-1].nodes); } break; case 410: { if (yang_read_description(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 411: { if (yang_read_reference(trg, (yyvsp[-1].nodes).refine, s, "refine", NODE)) { YYABORT; } s = NULL; } break; case 414: { void *parent; (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; parent = actual; YANG_ADDELEM(((struct lys_node_uses *)actual)->augment, ((struct lys_node_uses *)actual)->augment_size, "augments"); if (yang_read_augment(trg, parent, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 415: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 418: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->augment, trg->augment_size, "augments"); if (yang_read_augment(trg, NULL, actual, s)) { YYABORT; } data_node = actual; s = NULL; actual_type = AUGMENT_KEYWORD; } break; case 419: { LOGDBG(LY_LDGYANG, "finished parsing augment statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 420: { (yyval.nodes).augment = actual; } break; case 423: { if ((yyvsp[-1].nodes).augment->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).augment, "status", "augment"); YYABORT; } (yyvsp[-1].nodes).augment->flags |= (yyvsp[0].i); } break; case 424: { if (yang_read_description(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 425: { if (yang_read_reference(trg, (yyvsp[-1].nodes).augment, s, "augment", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 428: { if (trg->version < 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, (yyvsp[-2].nodes).augment, "notification"); YYABORT; } } break; case 430: { if (param->module->version != 2) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "action"); free(s); YYABORT; } (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_ACTION, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = ACTION_KEYWORD; } break; case 431: { LOGDBG(LY_LDGYANG, "finished parsing action statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 432: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, NULL, param->node, s, LYS_RPC, sizeof(struct lys_node_rpc_action)))) { YYABORT; } data_node = actual; s = NULL; actual_type = RPC_KEYWORD; } break; case 433: { LOGDBG(LY_LDGYANG, "finished parsing rpc statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 435: { void *tmp; if ((yyvsp[-1].nodes).node.ptr_rpc->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->iffeature, (yyvsp[-1].nodes).node.ptr_rpc->iffeature_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->iffeature = tmp; } if ((yyvsp[-1].nodes).node.ptr_rpc->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).node.ptr_rpc->tpdf, (yyvsp[-1].nodes).node.ptr_rpc->tpdf_size * sizeof *(yyvsp[-1].nodes).node.ptr_rpc->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->tpdf = tmp; } } break; case 436: { (yyval.nodes).node.ptr_rpc = actual; (yyval.nodes).node.flag = 0; } break; case 438: { if ((yyvsp[-1].nodes).node.ptr_rpc->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).node.ptr_rpc, "status", "rpc"); YYABORT; } (yyvsp[-1].nodes).node.ptr_rpc->flags |= (yyvsp[0].i); } break; case 439: { if (yang_read_description(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 440: { if (yang_read_reference(trg, (yyvsp[-1].nodes).node.ptr_rpc, s, "rpc", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 443: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_INPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "input", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_INPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 444: { if ((yyvsp[-2].nodes).node.flag & LYS_RPC_OUTPUT) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-2].nodes).node.ptr_rpc, "output", "rpc"); YYABORT; } (yyvsp[-2].nodes).node.flag |= LYS_RPC_OUTPUT; (yyval.nodes) = (yyvsp[-2].nodes); } break; case 445: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("input"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_INPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = INPUT_KEYWORD; } break; case 446: { void *tmp; struct lys_node_inout *input = actual; if (input->must_size) { tmp = realloc(input->must, input->must_size * sizeof *input->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->must = tmp; } if (input->tpdf_size) { tmp = realloc(input->tpdf, input->tpdf_size * sizeof *input->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } input->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing input statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 452: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; s = strdup("output"); if (!s) { LOGMEM(trg->ctx); YYABORT; } if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_OUTPUT, sizeof(struct lys_node_inout)))) { YYABORT; } data_node = actual; s = NULL; actual_type = OUTPUT_KEYWORD; } break; case 453: { void *tmp; struct lys_node_inout *output = actual; if (output->must_size) { tmp = realloc(output->must, output->must_size * sizeof *output->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->must = tmp; } if (output->tpdf_size) { tmp = realloc(output->tpdf, output->tpdf_size * sizeof *output->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } output->tpdf = tmp; } LOGDBG(LY_LDGYANG, "finished parsing output statement \"%s\"", data_node->name); actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; data_node = (yyvsp[-4].backup_token).actual; } break; case 454: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_node(trg, actual, param->node, s, LYS_NOTIF, sizeof(struct lys_node_notif)))) { YYABORT; } data_node = actual; actual_type = NOTIFICATION_KEYWORD; } break; case 455: { LOGDBG(LY_LDGYANG, "finished parsing notification statement \"%s\"", data_node->name); actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; data_node = (yyvsp[-1].backup_token).actual; } break; case 457: { void *tmp; if ((yyvsp[-1].nodes).notif->must_size) { tmp = realloc((yyvsp[-1].nodes).notif->must, (yyvsp[-1].nodes).notif->must_size * sizeof *(yyvsp[-1].nodes).notif->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->must = tmp; } if ((yyvsp[-1].nodes).notif->iffeature_size) { tmp = realloc((yyvsp[-1].nodes).notif->iffeature, (yyvsp[-1].nodes).notif->iffeature_size * sizeof *(yyvsp[-1].nodes).notif->iffeature); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->iffeature = tmp; } if ((yyvsp[-1].nodes).notif->tpdf_size) { tmp = realloc((yyvsp[-1].nodes).notif->tpdf, (yyvsp[-1].nodes).notif->tpdf_size * sizeof *(yyvsp[-1].nodes).notif->tpdf); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].nodes).notif->tpdf = tmp; } } break; case 458: { (yyval.nodes).notif = actual; } break; case 461: { if ((yyvsp[-1].nodes).notif->flags & LYS_STATUS_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_LYS, (yyvsp[-1].nodes).notif, "status", "notification"); YYABORT; } (yyvsp[-1].nodes).notif->flags |= (yyvsp[0].i); } break; case 462: { if (yang_read_description(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 463: { if (yang_read_reference(trg, (yyvsp[-1].nodes).notif, s, "notification", NODE_PRINT)) { YYABORT; } s = NULL; } break; case 467: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; YANG_ADDELEM(trg->deviation, trg->deviation_size, "deviations"); ((struct lys_deviation *)actual)->target_name = transform_schema2json(trg, s); free(s); if (!((struct lys_deviation *)actual)->target_name) { YYABORT; } s = NULL; actual_type = DEVIATION_KEYWORD; } break; case 468: { void *tmp; if ((yyvsp[-1].dev)->deviate_size) { tmp = realloc((yyvsp[-1].dev)->deviate, (yyvsp[-1].dev)->deviate_size * sizeof *(yyvsp[-1].dev)->deviate); if (!tmp) { LOGINT(trg->ctx); YYABORT; } (yyvsp[-1].dev)->deviate = tmp; } else { LOGVAL(trg->ctx, LYE_MISSCHILDSTMT, LY_VLOG_NONE, NULL, "deviate", "deviation"); YYABORT; } actual_type = (yyvsp[-4].backup_token).token; actual = (yyvsp[-4].backup_token).actual; } break; case 469: { (yyval.dev) = actual; } break; case 470: { if (yang_read_description(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 471: { if (yang_read_reference(trg, (yyvsp[-1].dev), s, "deviation", NODE)) { YYABORT; } s = NULL; (yyval.dev) = (yyvsp[-1].dev); } break; case 477: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate_unsupported(trg->ctx, actual))) { YYABORT; } actual_type = NOT_SUPPORTED_KEYWORD; } break; case 478: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 484: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_ADD))) { YYABORT; } actual_type = ADD_KEYWORD; } break; case 485: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 487: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 488: { (yyval.deviate) = actual; } break; case 489: { if (yang_read_units(trg, actual, s, ADD_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 491: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate)= (yyvsp[-1].deviate); } break; case 492: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 493: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 494: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 495: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 496: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 497: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_DEL))) { YYABORT; } actual_type = DELETE_KEYWORD; } break; case 498: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 500: { void *tmp; if ((yyvsp[-1].deviate)->must_size) { tmp = realloc((yyvsp[-1].deviate)->must, (yyvsp[-1].deviate)->must_size * sizeof *(yyvsp[-1].deviate)->must); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->must = tmp; } if ((yyvsp[-1].deviate)->unique_size) { tmp = realloc((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size * sizeof *(yyvsp[-1].deviate)->unique); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->unique = tmp; } if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 501: { (yyval.deviate) = actual; } break; case 502: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 504: { YANG_ADDELEM((yyvsp[-1].deviate)->unique, (yyvsp[-1].deviate)->unique_size, "uniques"); ((struct lys_unique *)actual)->expr = (const char **)s; s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 505: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 506: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_deviate(trg->ctx, actual, LY_DEVIATE_RPL))) { YYABORT; } actual_type = REPLACE_KEYWORD; } break; case 507: { actual_type = (yyvsp[-2].backup_token).token; actual = (yyvsp[-2].backup_token).actual; } break; case 509: { void *tmp; if ((yyvsp[-1].deviate)->dflt_size) { tmp = realloc((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size * sizeof *(yyvsp[-1].deviate)->dflt); if (!tmp) { LOGMEM(trg->ctx); YYABORT; } (yyvsp[-1].deviate)->dflt = tmp; } } break; case 510: { (yyval.deviate) = actual; } break; case 512: { if (yang_read_units(trg, actual, s, DELETE_KEYWORD)) { YYABORT; } s = NULL; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 513: { YANG_ADDELEM((yyvsp[-1].deviate)->dflt, (yyvsp[-1].deviate)->dflt_size, "defaults"); *((const char **)actual) = lydict_insert_zc(trg->ctx, s); s = NULL; actual = (yyvsp[-1].deviate); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 514: { if ((yyvsp[-1].deviate)->flags & LYS_CONFIG_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "config", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 515: { if ((yyvsp[-1].deviate)->flags & LYS_MAND_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "mandatory", "deviate"); YYABORT; } (yyvsp[-1].deviate)->flags = (yyvsp[0].i); (yyval.deviate) = (yyvsp[-1].deviate); } break; case 516: { if ((yyvsp[-1].deviate)->min_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "min-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->min = (yyvsp[0].uint); (yyvsp[-1].deviate)->min_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 517: { if ((yyvsp[-1].deviate)->max_set) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "max-elements", "deviation"); YYABORT; } (yyvsp[-1].deviate)->max = (yyvsp[0].uint); (yyvsp[-1].deviate)->max_set = 1; (yyval.deviate) = (yyvsp[-1].deviate); } break; case 518: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_when(trg, actual, actual_type, s))) { YYABORT; } s = NULL; actual_type = WHEN_KEYWORD; } break; case 519: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 523: { if (yang_read_description(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 524: { if (yang_read_reference(trg, actual, s, "when", NODE)) { YYABORT; } s = NULL; } break; case 525: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = CONFIG_KEYWORD; } break; case 526: { (yyval.i) = (yyvsp[-1].i); } break; case 527: { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } break; case 528: { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } break; case 529: { if (!strcmp(s, "true")) { (yyval.i) = LYS_CONFIG_W | LYS_CONFIG_SET; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_CONFIG_R | LYS_CONFIG_SET; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "config"); free(s); YYABORT; } free(s); s = NULL; } break; case 530: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = MANDATORY_KEYWORD; } break; case 531: { (yyval.i) = (yyvsp[-1].i); } break; case 532: { (yyval.i) = LYS_MAND_TRUE; } break; case 533: { (yyval.i) = LYS_MAND_FALSE; } break; case 534: { if (!strcmp(s, "true")) { (yyval.i) = LYS_MAND_TRUE; } else if (!strcmp(s, "false")) { (yyval.i) = LYS_MAND_FALSE; } else { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "mandatory"); free(s); YYABORT; } free(s); s = NULL; } break; case 535: { backup_type = actual_type; actual_type = PRESENCE_KEYWORD; } break; case 537: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MIN_ELEMENTS_KEYWORD; } break; case 538: { (yyval.uint) = (yyvsp[-1].uint); } break; case 539: { (yyval.uint) = (yyvsp[-1].uint); } break; case 540: { if (strlen(s) == 1 && s[0] == '0') { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "min-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 541: { (yyval.uint) = (yyvsp[0].uint); backup_type = actual_type; actual_type = MAX_ELEMENTS_KEYWORD; } break; case 542: { (yyval.uint) = (yyvsp[-1].uint); } break; case 543: { (yyval.uint) = 0; } break; case 544: { (yyval.uint) = (yyvsp[-1].uint); } break; case 545: { if (!strcmp(s, "unbounded")) { (yyval.uint) = 0; } else { /* convert it to uint32_t */ uint64_t val; char *endptr = NULL; errno = 0; val = strtoul(s, &endptr, 10); if (*endptr || s[0] == '-' || errno || val == 0 || val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_INARG, LY_VLOG_NONE, NULL, s, "max-elements"); free(s); YYABORT; } (yyval.uint) = (uint32_t) val; } free(s); s = NULL; } break; case 546: { (yyval.i) = (yyvsp[0].i); backup_type = actual_type; actual_type = ORDERED_BY_KEYWORD; } break; case 547: { (yyval.i) = (yyvsp[-1].i); } break; case 548: { (yyval.i) = LYS_USERORDERED; } break; case 549: { (yyval.i) = LYS_SYSTEMORDERED; } break; case 550: { if (!strcmp(s, "user")) { (yyval.i) = LYS_USERORDERED; } else if (!strcmp(s, "system")) { (yyval.i) = LYS_SYSTEMORDERED; } else { free(s); YYABORT; } free(s); s=NULL; } break; case 551: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; switch (actual_type) { case CONTAINER_KEYWORD: YANG_ADDELEM(((struct lys_node_container *)actual)->must, ((struct lys_node_container *)actual)->must_size, "musts"); break; case ANYDATA_KEYWORD: case ANYXML_KEYWORD: YANG_ADDELEM(((struct lys_node_anydata *)actual)->must, ((struct lys_node_anydata *)actual)->must_size, "musts"); break; case LEAF_KEYWORD: YANG_ADDELEM(((struct lys_node_leaf *)actual)->must, ((struct lys_node_leaf *)actual)->must_size, "musts"); break; case LEAF_LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_leaflist *)actual)->must, ((struct lys_node_leaflist *)actual)->must_size, "musts"); break; case LIST_KEYWORD: YANG_ADDELEM(((struct lys_node_list *)actual)->must, ((struct lys_node_list *)actual)->must_size, "musts"); break; case REFINE_KEYWORD: YANG_ADDELEM(((struct lys_refine *)actual)->must, ((struct lys_refine *)actual)->must_size, "musts"); break; case ADD_KEYWORD: case DELETE_KEYWORD: YANG_ADDELEM(((struct lys_deviate *)actual)->must, ((struct lys_deviate *)actual)->must_size, "musts"); break; case NOTIFICATION_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_notif *)actual)->must, ((struct lys_node_notif *)actual)->must_size, "musts"); break; case INPUT_KEYWORD: case OUTPUT_KEYWORD: if (trg->version < 2) { free(s); LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_LYS, actual, "must"); YYABORT; } YANG_ADDELEM(((struct lys_node_inout *)actual)->must, ((struct lys_node_inout *)actual)->must_size, "musts"); break; case EXTENSION_INSTANCE: /* must is already allocated */ break; default: free(s); LOGINT(trg->ctx); YYABORT; } ((struct lys_restr *)actual)->expr = transform_schema2json(trg, s); free(s); if (!((struct lys_restr *)actual)->expr) { YYABORT; } s = NULL; actual_type = MUST_KEYWORD; } break; case 552: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 555: { backup_type = actual_type; actual_type = UNIQUE_KEYWORD; } break; case 559: { backup_type = actual_type; actual_type = KEY_KEYWORD; } break; case 561: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 564: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_range(trg->ctx, actual, s, is_ext_instance))) { YYABORT; } actual_type = RANGE_KEYWORD; s = NULL; } break; case 565: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s,"/"); strcat(s, yyget_text(scanner)); } else { s = malloc(yyget_leng(scanner) + 2); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[0]='/'; memcpy(s + 1, yyget_text(scanner), yyget_leng(scanner) + 1); } } break; case 569: { if (s) { s = ly_realloc(s,strlen(s) + yyget_leng(scanner) + 1); if (!s) { LOGMEM(trg->ctx); YYABORT; } strcat(s, yyget_text(scanner)); } else { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } } break; case 571: { tmp_s = yyget_text(scanner); } break; case 572: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 573: { tmp_s = yyget_text(scanner); } break; case 574: { s = strdup(tmp_s); if (!s) { LOGMEM(trg->ctx); YYABORT; } s[strlen(s) - 1] = '\0'; } break; case 598: { /* convert it to uint32_t */ unsigned long val; val = strtoul(yyget_text(scanner), NULL, 10); if (val > UINT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Converted number is very long."); YYABORT; } (yyval.uint) = (uint32_t) val; } break; case 599: { (yyval.uint) = 0; } break; case 600: { (yyval.uint) = (yyvsp[0].uint); } break; case 601: { (yyval.i) = 0; } break; case 602: { /* convert it to int32_t */ int64_t val; val = strtoll(yyget_text(scanner), NULL, 10); if (val < INT32_MIN || val > INT32_MAX) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "The number is not in the correct range (INT32_MIN..INT32_MAX): \"%d\"",val); YYABORT; } (yyval.i) = (int32_t) val; } break; case 608: { if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } break; case 613: { char *tmp; if ((tmp = strchr(s, ':'))) { *tmp = '\0'; /* check prefix */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } /* check identifier */ if (lyp_check_identifier(trg->ctx, tmp + 1, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } *tmp = ':'; } else { /* check identifier */ if (lyp_check_identifier(trg->ctx, s, LY_IDENT_SIMPLE, trg, NULL)) { free(s); YYABORT; } } } break; case 614: { s = (yyvsp[-1].str); } break; case 615: { s = (yyvsp[-3].str); } break; case 616: { actual_type = backup_type; backup_type = NODE; (yyval.str) = s; s = NULL; } break; case 617: { actual_type = backup_type; backup_type = NODE; } break; case 618: { (yyval.str) = s; s = NULL; } break; case 622: { actual_type = (yyvsp[-1].backup_token).token; actual = (yyvsp[-1].backup_token).actual; } break; case 623: { (yyval.backup_token).token = actual_type; (yyval.backup_token).actual = actual; if (!(actual = yang_read_ext(trg, (actual) ? actual : trg, (yyvsp[-1].str), s, actual_type, backup_type, is_ext_instance))) { YYABORT; } s = NULL; actual_type = EXTENSION_INSTANCE; } break; case 624: { (yyval.str) = s; s = NULL; } break; case 639: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length = 0, old_length = 0; char *tmp_value; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); old_length = (substmt->ext_substmt) ? strlen(substmt->ext_substmt) + 2 : 2; tmp_value = realloc(substmt->ext_substmt, old_length + length + 1); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_substmt = tmp_value; tmp_value += old_length - 2; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = ' '; tmp_value[length + 1] = '\0'; tmp_value[length + 2] = '\0'; } break; case 640: { struct yang_ext_substmt *substmt = ((struct lys_ext_instance *)actual)->parent; int32_t length; char *tmp_value, **array; int i = 0; if (!substmt) { substmt = calloc(1, sizeof *substmt); if (!substmt) { LOGMEM(trg->ctx); YYABORT; } ((struct lys_ext_instance *)actual)->parent = substmt; } length = strlen((yyvsp[-2].str)); if (!substmt->ext_modules) { array = malloc(2 * sizeof *substmt->ext_modules); } else { for (i = 0; substmt->ext_modules[i]; ++i); array = realloc(substmt->ext_modules, (i + 2) * sizeof *substmt->ext_modules); } if (!array) { LOGMEM(trg->ctx); YYABORT; } substmt->ext_modules = array; array[i + 1] = NULL; tmp_value = malloc(length + 2); if (!tmp_value) { LOGMEM(trg->ctx); YYABORT; } array[i] = tmp_value; memcpy(tmp_value, (yyvsp[-2].str), length); tmp_value[length] = '\0'; tmp_value[length + 1] = '\0'; } break; case 643: { (yyval.str) = yyget_text(scanner); } break; case 644: { (yyval.str) = yyget_text(scanner); } break; case 656: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 749: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 750: { s = strdup(yyget_text(scanner)); if (!s) { LOGMEM(trg->ctx); YYABORT; } } break; case 751: { struct lys_type **type; type = (struct lys_type **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "type", LY_STMT_TYPE); if (!type) { YYABORT; } /* allocate type structure */ (*type) = calloc(1, sizeof **type); if (!*type) { LOGMEM(trg->ctx); YYABORT; } /* HACK for unres */ (*type)->parent = (struct lys_tpdf *)ext_instance; (yyval.v) = actual = *type; is_ext_instance = 0; } break; case 752: { struct lys_tpdf **tpdf; tpdf = (struct lys_tpdf **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "typedef", LY_STMT_TYPEDEF); if (!tpdf) { YYABORT; } /* allocate typedef structure */ (*tpdf) = calloc(1, sizeof **tpdf); if (!*tpdf) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *tpdf; is_ext_instance = 0; } break; case 753: { struct lys_iffeature **iffeature; iffeature = (struct lys_iffeature **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "if-feature", LY_STMT_IFFEATURE); if (!iffeature) { YYABORT; } /* allocate typedef structure */ (*iffeature) = calloc(1, sizeof **iffeature); if (!*iffeature) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *iffeature; } break; case 754: { struct lys_restr **restr; LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "must")) { stmt = LY_STMT_MUST; } else if (!strcmp(s, "pattern")) { stmt = LY_STMT_PATTERN; } else if (!strcmp(s, "range")) { stmt = LY_STMT_RANGE; } else { stmt = LY_STMT_LENGTH; } restr = (struct lys_restr **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, s, stmt); if (!restr) { YYABORT; } /* allocate structure for must */ (*restr) = calloc(1, sizeof(struct lys_restr)); if (!*restr) { LOGMEM(trg->ctx); YYABORT; } (yyval.v) = actual = *restr; s = NULL; } break; case 755: { actual = yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "when", LY_STMT_WHEN); if (!actual) { YYABORT; } (yyval.v) = actual; } break; case 756: { struct lys_revision **rev; int i; rev = (struct lys_revision **)yang_getplace_for_extcomplex_struct(ext_instance, &i, ext_name, "revision", LY_STMT_REVISION); if (!rev) { YYABORT; } rev[i] = calloc(1, sizeof **rev); if (!rev[i]) { LOGMEM(trg->ctx); YYABORT; } actual = rev[i]; (yyval.revisions).revision = rev; (yyval.revisions).index = i; } break; case 757: { LY_STMT stmt; s = yyget_text(scanner); if (!strcmp(s, "action")) { stmt = LY_STMT_ACTION; } else if (!strcmp(s, "anydata")) { stmt = LY_STMT_ANYDATA; } else if (!strcmp(s, "anyxml")) { stmt = LY_STMT_ANYXML; } else if (!strcmp(s, "case")) { stmt = LY_STMT_CASE; } else if (!strcmp(s, "choice")) { stmt = LY_STMT_CHOICE; } else if (!strcmp(s, "container")) { stmt = LY_STMT_CONTAINER; } else if (!strcmp(s, "grouping")) { stmt = LY_STMT_GROUPING; } else if (!strcmp(s, "input")) { stmt = LY_STMT_INPUT; } else if (!strcmp(s, "leaf")) { stmt = LY_STMT_LEAF; } else if (!strcmp(s, "leaf-list")) { stmt = LY_STMT_LEAFLIST; } else if (!strcmp(s, "list")) { stmt = LY_STMT_LIST; } else if (!strcmp(s, "notification")) { stmt = LY_STMT_NOTIFICATION; } else if (!strcmp(s, "output")) { stmt = LY_STMT_OUTPUT; } else { stmt = LY_STMT_USES; } if (yang_extcomplex_node(ext_instance, ext_name, s, *param->node, stmt)) { YYABORT; } actual = NULL; s = NULL; is_ext_instance = 0; } break; case 758: { LOGERR(trg->ctx, ly_errno, "Extension's substatement \"%s\" not supported.", yyget_text(scanner)); } break; case 790: { actual_type = EXTENSION_INSTANCE; actual = ext_instance; if (!is_ext_instance) { LOGVAL(trg->ctx, LYE_INSTMT, LY_VLOG_NONE, NULL, yyget_text(scanner)); YYABORT; } (yyval.i) = 0; } break; case 792: { if (yang_read_extcomplex_str(trg, ext_instance, "prefix", ext_name, &s, 0, LY_STMT_PREFIX)) { YYABORT; } } break; case 793: { if (yang_read_extcomplex_str(trg, ext_instance, "description", ext_name, &s, 0, LY_STMT_DESCRIPTION)) { YYABORT; } } break; case 794: { if (yang_read_extcomplex_str(trg, ext_instance, "reference", ext_name, &s, 0, LY_STMT_REFERENCE)) { YYABORT; } } break; case 795: { if (yang_read_extcomplex_str(trg, ext_instance, "units", ext_name, &s, 0, LY_STMT_UNITS)) { YYABORT; } } break; case 796: { if (yang_read_extcomplex_str(trg, ext_instance, "base", ext_name, &s, 0, LY_STMT_BASE)) { YYABORT; } } break; case 797: { if (yang_read_extcomplex_str(trg, ext_instance, "contact", ext_name, &s, 0, LY_STMT_CONTACT)) { YYABORT; } } break; case 798: { if (yang_read_extcomplex_str(trg, ext_instance, "default", ext_name, &s, 0, LY_STMT_DEFAULT)) { YYABORT; } } break; case 799: { if (yang_read_extcomplex_str(trg, ext_instance, "error-message", ext_name, &s, 0, LY_STMT_ERRMSG)) { YYABORT; } } break; case 800: { if (yang_read_extcomplex_str(trg, ext_instance, "error-app-tag", ext_name, &s, 0, LY_STMT_ERRTAG)) { YYABORT; } } break; case 801: { if (yang_read_extcomplex_str(trg, ext_instance, "key", ext_name, &s, 0, LY_STMT_KEY)) { YYABORT; } } break; case 802: { if (yang_read_extcomplex_str(trg, ext_instance, "namespace", ext_name, &s, 0, LY_STMT_NAMESPACE)) { YYABORT; } } break; case 803: { if (yang_read_extcomplex_str(trg, ext_instance, "organization", ext_name, &s, 0, LY_STMT_ORGANIZATION)) { YYABORT; } } break; case 804: { if (yang_read_extcomplex_str(trg, ext_instance, "path", ext_name, &s, 0, LY_STMT_PATH)) { YYABORT; } } break; case 805: { if (yang_read_extcomplex_str(trg, ext_instance, "presence", ext_name, &s, 0, LY_STMT_PRESENCE)) { YYABORT; } } break; case 806: { if (yang_read_extcomplex_str(trg, ext_instance, "revision-date", ext_name, &s, 0, LY_STMT_REVISIONDATE)) { YYABORT; } } break; case 807: { struct lys_type *type = (yyvsp[-2].v); if (yang_fill_type(trg, type, (struct yang_type *)type->der, ext_instance, param->unres)) { yang_type_free(trg->ctx, type); YYABORT; } if (unres_schema_add_node(trg, param->unres, type, UNRES_TYPE_DER_EXT, NULL) == -1) { yang_type_free(trg->ctx, type); YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 808: { struct lys_tpdf *tpdf = (yyvsp[-2].v); if (yang_fill_type(trg, &tpdf->type, (struct yang_type *)tpdf->type.der, tpdf, param->unres)) { yang_type_free(trg->ctx, &tpdf->type); } if (yang_check_ext_instance(trg, &tpdf->ext, tpdf->ext_size, tpdf, param->unres)) { YYABORT; } if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DER_TPDF, (struct lys_node *)ext_instance) == -1) { yang_type_free(trg->ctx, &tpdf->type); YYABORT; } /* check default value*/ if (unres_schema_add_node(trg, param->unres, &tpdf->type, UNRES_TYPE_DFLT, (struct lys_node *)(&tpdf->dflt)) == -1) { YYABORT; } actual = ext_instance; is_ext_instance = 1; } break; case 809: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "status", LY_STMT_STATUS, (yyvsp[0].i), LYS_STATUS_MASK)) { YYABORT; } } break; case 810: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "config", LY_STMT_CONFIG, (yyvsp[0].i), LYS_CONFIG_MASK)) { YYABORT; } } break; case 811: { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "mandatory", LY_STMT_MANDATORY, (yyvsp[0].i), LYS_MAND_MASK)) { YYABORT; } } break; case 812: { if ((yyvsp[-1].i) & LYS_ORDERED_MASK) { LOGVAL(trg->ctx, LYE_TOOMANY, LY_VLOG_NONE, NULL, "ordered by", ext_name); YYABORT; } if ((yyvsp[0].i) & LYS_USERORDERED) { if (yang_fill_extcomplex_flags(ext_instance, ext_name, "ordered-by", LY_STMT_ORDEREDBY, (yyvsp[0].i), LYS_USERORDERED)) { YYABORT; } } (yyvsp[-1].i) |= (yyvsp[0].i); (yyval.i) = (yyvsp[-1].i); } break; case 813: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "require-instance", LY_STMT_REQINSTANCE, (yyvsp[0].i))) { YYABORT; } } break; case 814: { if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "modifier", LY_STMT_MODIFIER, 0)) { YYABORT; } } break; case 815: { /* range check */ if ((yyvsp[0].uint) < 1 || (yyvsp[0].uint) > 18) { LOGVAL(trg->ctx, LYE_SPEC, LY_VLOG_NONE, NULL, "Invalid value \"%d\" of \"%s\".", (yyvsp[0].uint), "fraction-digits"); YYABORT; } if (yang_fill_extcomplex_uint8(ext_instance, ext_name, "fraction-digits", LY_STMT_DIGITS, (yyvsp[0].uint))) { YYABORT; } } break; case 816: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "min-elements", LY_STMT_MIN); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 817: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "max-elements", LY_STMT_MAX); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 818: { uint32_t **val; val = (uint32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "position", LY_STMT_POSITION); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(uint32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].uint); } break; case 819: { int32_t **val; val = (int32_t **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "value", LY_STMT_VALUE); if (!val) { YYABORT; } /* store the value */ *val = malloc(sizeof(int32_t)); if (!*val) { LOGMEM(trg->ctx); YYABORT; } **val = (yyvsp[0].i); } break; case 820: { struct lys_unique **unique; int rc; unique = (struct lys_unique **)yang_getplace_for_extcomplex_struct(ext_instance, NULL, ext_name, "unique", LY_STMT_UNIQUE); if (!unique) { YYABORT; } *unique = calloc(1, sizeof(struct lys_unique)); if (!*unique) { LOGMEM(trg->ctx); YYABORT; } rc = yang_fill_unique(trg, (struct lys_node_list *)ext_instance, *unique, s, param->unres); free(s); s = NULL; if (rc) { YYABORT; } } break; case 821: { struct lys_iffeature *iffeature; iffeature = (yyvsp[-2].v); s = (char *)iffeature->features; iffeature->features = NULL; if (yang_fill_iffeature(trg, iffeature, ext_instance, s, param->unres, 0)) { YYABORT; } if (yang_check_ext_instance(trg, &iffeature->ext, iffeature->ext_size, iffeature, param->unres)) { YYABORT; } s = NULL; actual = ext_instance; } break; case 823: { if (yang_check_ext_instance(trg, &((struct lys_restr *)(yyvsp[-2].v))->ext, ((struct lys_restr *)(yyvsp[-2].v))->ext_size, (yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 824: { if (yang_check_ext_instance(trg, &(*(struct lys_when **)(yyvsp[-2].v))->ext, (*(struct lys_when **)(yyvsp[-2].v))->ext_size, *(struct lys_when **)(yyvsp[-2].v), param->unres)) { YYABORT; } actual = ext_instance; } break; case 825: { int i; for (i = 0; i < (yyvsp[-2].revisions).index; ++i) { if (!strcmp((yyvsp[-2].revisions).revision[i]->date, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->date)) { LOGWRN(trg->ctx, "Module's revisions are not unique (%s).", (yyvsp[-2].revisions).revision[i]->date); break; } } if (yang_check_ext_instance(trg, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext, (yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index]->ext_size, &(yyvsp[-2].revisions).revision[(yyvsp[-2].revisions).index], param->unres)) { YYABORT; } actual = ext_instance; } break; case 826: { actual = ext_instance; is_ext_instance = 1; } break; default: break; } /* User semantic actions sometimes alter yychar, and that requires that yytoken be updated with the new translation. We take the approach of translating immediately before every use of yytoken. One alternative is translating here after every semantic action, but that translation would be missed if the semantic action invokes YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an incorrect destructor might then be invoked immediately. In the case of YYERROR or YYBACKUP, subsequent parser actions might lead to an incorrect destructor call or verbose syntax error message before the lookahead is translated. */ YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc); YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); *++yyvsp = yyval; *++yylsp = yyloc; /* Now 'shift' the result of the reduction. Determine what state that goes to, based on the state we popped back to and the rule number reduced by. */ { const int yylhs = yyr1[yyn] - YYNTOKENS; const int yyi = yypgoto[yylhs] + *yyssp; yystate = (0 <= yyi && yyi <= YYLAST && yycheck[yyi] == *yyssp ? yytable[yyi] : yydefgoto[yylhs]); } goto yynewstate; /*--------------------------------------. | yyerrlab -- here on detecting error. | `--------------------------------------*/ yyerrlab: /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar); /* If not already recovering from an error, report this error. */ if (!yyerrstatus) { ++yynerrs; #if ! YYERROR_VERBOSE yyerror (&yylloc, scanner, param, YY_("syntax error")); #else # define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \ yyssp, yytoken) { char const *yymsgp = YY_("syntax error"); int yysyntax_error_status; yysyntax_error_status = YYSYNTAX_ERROR; if (yysyntax_error_status == 0) yymsgp = yymsg; else if (yysyntax_error_status == 1) { if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc); if (!yymsg) { yymsg = yymsgbuf; yymsg_alloc = sizeof yymsgbuf; yysyntax_error_status = 2; } else { yysyntax_error_status = YYSYNTAX_ERROR; yymsgp = yymsg; } } yyerror (&yylloc, scanner, param, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } yyerror_range[1] = yylloc; if (yyerrstatus == 3) { /* If just tried and failed to reuse lookahead token after an error, discard it. */ if (yychar <= YYEOF) { /* Return failure if at end of input. */ if (yychar == YYEOF) YYABORT; } else { yydestruct ("Error: discarding", yytoken, &yylval, &yylloc, scanner, param); yychar = YYEMPTY; } } /* Else will try to reuse lookahead token after shifting the error token. */ goto yyerrlab1; /*---------------------------------------------------. | yyerrorlab -- error raised explicitly by YYERROR. | `---------------------------------------------------*/ yyerrorlab: /* Pacify compilers like GCC when the user code never invokes YYERROR and the label yyerrorlab therefore never appears in user code. */ if (/*CONSTCOND*/ 0) goto yyerrorlab; /* Do not reclaim the symbols of the rule whose action triggered this YYERROR. */ YYPOPSTACK (yylen); yylen = 0; YY_STACK_PRINT (yyss, yyssp); yystate = *yyssp; goto yyerrlab1; /*-------------------------------------------------------------. | yyerrlab1 -- common code for both syntax error and YYERROR. | `-------------------------------------------------------------*/ yyerrlab1: yyerrstatus = 3; /* Each real token shifted decrements this. */ for (;;) { yyn = yypact[yystate]; if (!yypact_value_is_default (yyn)) { yyn += YYTERROR; if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR) { yyn = yytable[yyn]; if (0 < yyn) break; } } /* Pop the current state because it cannot handle the error token. */ if (yyssp == yyss) YYABORT; yyerror_range[1] = *yylsp; yydestruct ("Error: popping", yystos[yystate], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END yyerror_range[2] = yylloc; /* Using YYLLOC is tempting, but would change the location of the lookahead. YYLOC is available though. */ YYLLOC_DEFAULT (yyloc, yyerror_range, 2); *++yylsp = yyloc; /* Shift the error token. */ YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp); yystate = yyn; goto yynewstate; /*-------------------------------------. | yyacceptlab -- YYACCEPT comes here. | `-------------------------------------*/ yyacceptlab: yyresult = 0; goto yyreturn; /*-----------------------------------. | yyabortlab -- YYABORT comes here. | `-----------------------------------*/ yyabortlab: yyresult = 1; goto yyreturn; #if !defined yyoverflow || YYERROR_VERBOSE /*-------------------------------------------------. | yyexhaustedlab -- memory exhaustion comes here. | `-------------------------------------------------*/ yyexhaustedlab: yyerror (&yylloc, scanner, param, YY_("memory exhausted")); yyresult = 2; /* Fall through. */ #endif yyreturn: if (yychar != YYEMPTY) { /* Make sure we have latest lookahead translation. See comments at user semantic actions for why this is necessary. */ yytoken = YYTRANSLATE (yychar); yydestruct ("Cleanup: discarding lookahead", yytoken, &yylval, &yylloc, scanner, param); } /* Do not reclaim the symbols of the rule whose action triggered this YYABORT or YYACCEPT. */ YYPOPSTACK (yylen); YY_STACK_PRINT (yyss, yyssp); while (yyssp != yyss) { yydestruct ("Cleanup: popping", yystos[*yyssp], yyvsp, yylsp, scanner, param); YYPOPSTACK (1); } #ifndef yyoverflow if (yyss != yyssa) YYSTACK_FREE (yyss); #endif #if YYERROR_VERBOSE if (yymsg != yymsgbuf) YYSTACK_FREE (yymsg); #endif return yyresult; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-415'], 'message': 'yang parser BUGFIX double free Fixes #769'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: 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; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'schema tree BUGFIX do not copy unresolved exts in groupings restrictions Fixes #773'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _cairo_image_surface_create_from_jpeg (GInputStream *istream, GthFileData *file_data, int requested_size, int *original_width_p, int *original_height_p, gboolean *loaded_original_p, gpointer user_data, GCancellable *cancellable, GError **error) { GthImage *image; JpegInfoFlags info_flags; gboolean load_scaled; GthTransform orientation; int output_width; int output_height; int destination_width; int destination_height; int line_start; int line_step; int pixel_step; void *in_buffer; gsize in_buffer_size; JpegInfoData jpeg_info; struct error_handler_data jsrcerr; struct jpeg_decompress_struct srcinfo; cairo_surface_t *surface; cairo_surface_metadata_t *metadata; unsigned char *surface_data; unsigned char *surface_row; JSAMPARRAY buffer; int buffer_stride; JDIMENSION n_lines; JSAMPARRAY buffer_row; int l; unsigned char *p_surface; guchar r, g, b; guint32 pixel; unsigned char *p_buffer; int x; gboolean read_all_scanlines = FALSE; gboolean finished = FALSE; image = gth_image_new (); surface = NULL; if (! _g_input_stream_read_all (istream, &in_buffer, &in_buffer_size, cancellable, error)) { return image; } _jpeg_info_data_init (&jpeg_info); info_flags = _JPEG_INFO_EXIF_ORIENTATION; #if HAVE_LCMS2 info_flags |= _JPEG_INFO_EXIF_COLOR_SPACE | _JPEG_INFO_ICC_PROFILE; #endif _jpeg_info_get_from_buffer (in_buffer, in_buffer_size, info_flags, &jpeg_info); if (jpeg_info.valid & _JPEG_INFO_EXIF_ORIENTATION) orientation = jpeg_info.orientation; else orientation = GTH_TRANSFORM_NONE; #if HAVE_LCMS2 { GthICCProfile *profile = NULL; if (jpeg_info.valid & _JPEG_INFO_ICC_PROFILE) { profile = gth_icc_profile_new (GTH_ICC_PROFILE_ID_UNKNOWN, cmsOpenProfileFromMem (jpeg_info.icc_data, jpeg_info.icc_data_size)); } else if (jpeg_info.valid & _JPEG_INFO_EXIF_COLOR_SPACE) { if (jpeg_info.color_space == GTH_COLOR_SPACE_SRGB) profile = gth_icc_profile_new_srgb (); } if (profile != NULL) { gth_image_set_icc_profile (image, profile); g_object_unref (profile); } } #endif _jpeg_info_data_dispose (&jpeg_info); srcinfo.err = jpeg_std_error (&(jsrcerr.pub)); jsrcerr.pub.error_exit = fatal_error_handler; jsrcerr.pub.output_message = output_message_handler; jsrcerr.error = error; jpeg_create_decompress (&srcinfo); if (sigsetjmp (jsrcerr.setjmp_buffer, 1)) goto stop_loading; _jpeg_memory_src (&srcinfo, in_buffer, in_buffer_size); jpeg_read_header (&srcinfo, TRUE); srcinfo.out_color_space = srcinfo.jpeg_color_space; /* make all the color space conversions manually */ load_scaled = (requested_size > 0) && (requested_size < srcinfo.image_width) && (requested_size < srcinfo.image_height); if (load_scaled) { for (srcinfo.scale_denom = 1; srcinfo.scale_denom <= 16; srcinfo.scale_denom++) { jpeg_calc_output_dimensions (&srcinfo); if ((srcinfo.output_width < requested_size) || (srcinfo.output_height < requested_size)) { srcinfo.scale_denom -= 1; break; } } if (srcinfo.scale_denom <= 0) { srcinfo.scale_denom = srcinfo.scale_num; load_scaled = FALSE; } } jpeg_calc_output_dimensions (&srcinfo); buffer_stride = srcinfo.output_width * srcinfo.output_components; buffer = (*srcinfo.mem->alloc_sarray) ((j_common_ptr) &srcinfo, JPOOL_IMAGE, buffer_stride, srcinfo.rec_outbuf_height); jpeg_start_decompress (&srcinfo); output_width = MIN (srcinfo.output_width, CAIRO_MAX_IMAGE_SIZE); output_height = MIN (srcinfo.output_height, CAIRO_MAX_IMAGE_SIZE); _cairo_image_surface_transform_get_steps (CAIRO_FORMAT_ARGB32, output_width, output_height, orientation, &destination_width, &destination_height, &line_start, &line_step, &pixel_step); #if 0 g_print ("requested: %d, original [%d, %d] ==> load at [%d, %d]\n", requested_size, srcinfo.image_width, srcinfo.image_height, destination_width, destination_height); #endif surface = _cairo_image_surface_create (CAIRO_FORMAT_ARGB32, destination_width, destination_height); if (surface == NULL) { jpeg_destroy_decompress (&srcinfo); g_free (in_buffer); return image; } metadata = _cairo_image_surface_get_metadata (surface); _cairo_metadata_set_has_alpha (metadata, FALSE); surface_data = _cairo_image_surface_flush_and_get_data (surface); surface_row = surface_data + line_start; switch (srcinfo.out_color_space) { case JCS_CMYK: { register unsigned char *cmyk_tab; int c, m, y, k, ki; CMYK_table_init (); cmyk_tab = CMYK_Tab; while (srcinfo.output_scanline < output_height) { if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; n_lines = jpeg_read_scanlines (&srcinfo, buffer, srcinfo.rec_outbuf_height); buffer_row = buffer; for (l = 0; l < n_lines; l++) { p_surface = surface_row; p_buffer = buffer_row[l]; if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; for (x = 0; x < output_width; x++) { if (srcinfo.saw_Adobe_marker) { c = p_buffer[0]; m = p_buffer[1]; y = p_buffer[2]; k = p_buffer[3]; } else { c = 255 - p_buffer[0]; m = 255 - p_buffer[1]; y = 255 - p_buffer[2]; k = 255 - p_buffer[3]; } ki = k << 8; /* ki = k * 256 */ r = cmyk_tab[ki + c]; g = cmyk_tab[ki + m]; b = cmyk_tab[ki + y]; pixel = CAIRO_RGBA_TO_UINT32 (r, g, b, 0xff); memcpy (p_surface, &pixel, sizeof (guint32)); p_surface += pixel_step; p_buffer += 4 /*srcinfo.output_components*/; } surface_row += line_step; buffer_row += buffer_stride; } } } break; case JCS_GRAYSCALE: { while (srcinfo.output_scanline < output_height) { if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; n_lines = jpeg_read_scanlines (&srcinfo, buffer, srcinfo.rec_outbuf_height); buffer_row = buffer; for (l = 0; l < n_lines; l++) { p_surface = surface_row; p_buffer = buffer_row[l]; if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; for (x = 0; x < output_width; x++) { r = g = b = p_buffer[0]; pixel = CAIRO_RGBA_TO_UINT32 (r, g, b, 0xff); memcpy (p_surface, &pixel, sizeof (guint32)); p_surface += pixel_step; p_buffer += 1 /*srcinfo.output_components*/; } surface_row += line_step; buffer_row += buffer_stride; } } } break; case JCS_RGB: { while (srcinfo.output_scanline < output_height) { if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; n_lines = jpeg_read_scanlines (&srcinfo, buffer, srcinfo.rec_outbuf_height); buffer_row = buffer; for (l = 0; l < n_lines; l++) { p_surface = surface_row; p_buffer = buffer_row[l]; if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; for (x = 0; x < output_width; x++) { r = p_buffer[0]; g = p_buffer[1]; b = p_buffer[2]; pixel = CAIRO_RGBA_TO_UINT32 (r, g, b, 0xff); memcpy (p_surface, &pixel, sizeof (guint32)); p_surface += pixel_step; p_buffer += 3 /*srcinfo.output_components*/; } surface_row += line_step; buffer_row += buffer_stride; } } } break; case JCS_YCbCr: { register JSAMPLE *range_limit = srcinfo.sample_range_limit; register int *r_cr_tab; register int *g_cb_tab; register int *g_cr_tab; register int *b_cb_tab; int Y, Cb, Cr; YCbCr_tables_init (); r_cr_tab = YCbCr_R_Cr_Tab; g_cb_tab = YCbCr_G_Cb_Tab; g_cr_tab = YCbCr_G_Cr_Tab; b_cb_tab = YCbCr_B_Cb_Tab; while (srcinfo.output_scanline < output_height) { if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; n_lines = jpeg_read_scanlines (&srcinfo, buffer, srcinfo.rec_outbuf_height); buffer_row = buffer; for (l = 0; l < n_lines; l++) { p_surface = surface_row; p_buffer = buffer_row[l]; if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; for (x = 0; x < output_width; x++) { Y = p_buffer[0]; Cb = p_buffer[1]; Cr = p_buffer[2]; r = range_limit[Y + r_cr_tab[Cr]]; g = range_limit[Y + SCALE_DOWN (g_cb_tab[Cb] + g_cr_tab[Cr])]; b = range_limit[Y + b_cb_tab[Cb]]; pixel = CAIRO_RGBA_TO_UINT32 (r, g, b, 0xff); memcpy (p_surface, &pixel, sizeof (guint32)); p_surface += pixel_step; p_buffer += 3 /*srcinfo.output_components*/; } surface_row += line_step; buffer_row += buffer_stride; } } } break; case JCS_YCCK: { register JSAMPLE *range_limit = srcinfo.sample_range_limit; register int *r_cr_tab; register int *g_cb_tab; register int *g_cr_tab; register int *b_cb_tab; register guchar *cmyk_tab; int Y, Cb, Cr, K, Ki, c, m , y; YCbCr_tables_init (); r_cr_tab = YCbCr_R_Cr_Tab; g_cb_tab = YCbCr_G_Cb_Tab; g_cr_tab = YCbCr_G_Cr_Tab; b_cb_tab = YCbCr_B_Cb_Tab; CMYK_table_init (); cmyk_tab = CMYK_Tab; while (srcinfo.output_scanline < output_height) { if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; n_lines = jpeg_read_scanlines (&srcinfo, buffer, srcinfo.rec_outbuf_height); buffer_row = buffer; for (l = 0; l < n_lines; l++) { p_surface = surface_row; p_buffer = buffer_row[l]; if (g_cancellable_is_cancelled (cancellable)) goto stop_loading; for (x = 0; x < output_width; x++) { Y = p_buffer[0]; Cb = p_buffer[1]; Cr = p_buffer[2]; K = p_buffer[3]; c = range_limit[255 - (Y + r_cr_tab[Cr])]; m = range_limit[255 - (Y + SCALE_DOWN (g_cb_tab[Cb] + g_cr_tab[Cr]))]; y = range_limit[255 - (Y + b_cb_tab[Cb])]; Ki = K << 8; /* ki = K * 256 */ r = cmyk_tab[Ki + c]; g = cmyk_tab[Ki + m]; b = cmyk_tab[Ki + y]; pixel = CAIRO_RGBA_TO_UINT32 (r, g, b, 0xff); memcpy (p_surface, &pixel, sizeof (guint32)); p_surface += pixel_step; p_buffer += 4 /*srcinfo.output_components*/; } surface_row += line_step; buffer_row += buffer_stride; } } } break; case JCS_UNKNOWN: default: g_set_error (error, GDK_PIXBUF_ERROR, GDK_PIXBUF_ERROR_UNKNOWN_TYPE, _("Unknown JPEG color space (%d)"), srcinfo.out_color_space); break; } read_all_scanlines = TRUE; stop_loading: if (surface != NULL) { cairo_surface_mark_dirty (surface); if (! g_cancellable_is_cancelled (cancellable)) { int original_width; int original_height; /* Set the original dimensions */ if ((orientation == GTH_TRANSFORM_ROTATE_90) || (orientation == GTH_TRANSFORM_ROTATE_270) || (orientation == GTH_TRANSFORM_TRANSPOSE) || (orientation == GTH_TRANSFORM_TRANSVERSE)) { original_width = srcinfo.image_height; original_height = srcinfo.image_width; } else { original_width = srcinfo.image_width; original_height = srcinfo.image_height; } _cairo_metadata_set_original_size (metadata, original_width, original_height); if (original_width_p != NULL) *original_width_p = original_width; if (original_height_p != NULL) *original_height_p = original_height; if (loaded_original_p != NULL) *loaded_original_p = ! load_scaled; /*_cairo_image_surface_set_attribute_int (surface, "Image::Rotation", rotation); FIXME*/ /* FIXME _cairo_image_surface_set_attribute (surface, "Jpeg::ColorSpace", jpeg_color_space_name (srcinfo.jpeg_color_space)); */ gth_image_set_cairo_surface (image, surface); } else g_set_error_literal (error, G_IO_ERROR, G_IO_ERROR_CANCELLED, ""); cairo_surface_destroy (surface); surface = NULL; /* ignore other jpeg errors */ } if (! finished) { finished = TRUE; if (read_all_scanlines) jpeg_finish_decompress (&srcinfo); else jpeg_abort_decompress (&srcinfo); jpeg_destroy_decompress (&srcinfo); g_free (in_buffer); } return image; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-787'], 'message': 'jpeg loader: do not scan more than output_height lines'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int sas_get_port_device(struct asd_sas_port *port) { struct asd_sas_phy *phy; struct sas_rphy *rphy; struct domain_device *dev; int rc = -ENODEV; dev = sas_alloc_device(); if (!dev) return -ENOMEM; spin_lock_irq(&port->phy_list_lock); if (list_empty(&port->phy_list)) { spin_unlock_irq(&port->phy_list_lock); sas_put_device(dev); return -ENODEV; } phy = container_of(port->phy_list.next, struct asd_sas_phy, port_phy_el); spin_lock(&phy->frame_rcvd_lock); memcpy(dev->frame_rcvd, phy->frame_rcvd, min(sizeof(dev->frame_rcvd), (size_t)phy->frame_rcvd_size)); spin_unlock(&phy->frame_rcvd_lock); spin_unlock_irq(&port->phy_list_lock); if (dev->frame_rcvd[0] == 0x34 && port->oob_mode == SATA_OOB_MODE) { struct dev_to_host_fis *fis = (struct dev_to_host_fis *) dev->frame_rcvd; if (fis->interrupt_reason == 1 && fis->lbal == 1 && fis->byte_count_low==0x69 && fis->byte_count_high == 0x96 && (fis->device & ~0x10) == 0) dev->dev_type = SAS_SATA_PM; else dev->dev_type = SAS_SATA_DEV; dev->tproto = SAS_PROTOCOL_SATA; } else { struct sas_identify_frame *id = (struct sas_identify_frame *) dev->frame_rcvd; dev->dev_type = id->dev_type; dev->iproto = id->initiator_bits; dev->tproto = id->target_bits; } sas_init_dev(dev); dev->port = port; switch (dev->dev_type) { case SAS_SATA_DEV: rc = sas_ata_init(dev); if (rc) { rphy = NULL; break; } /* fall through */ case SAS_END_DEVICE: rphy = sas_end_device_alloc(port->port); break; case SAS_EDGE_EXPANDER_DEVICE: rphy = sas_expander_alloc(port->port, SAS_EDGE_EXPANDER_DEVICE); break; case SAS_FANOUT_EXPANDER_DEVICE: rphy = sas_expander_alloc(port->port, SAS_FANOUT_EXPANDER_DEVICE); break; default: pr_warn("ERROR: Unidentified device type %d\n", dev->dev_type); rphy = NULL; break; } if (!rphy) { sas_put_device(dev); return rc; } rphy->identify.phy_identifier = phy->phy->identify.phy_identifier; memcpy(dev->sas_addr, port->attached_sas_addr, SAS_ADDR_SIZE); sas_fill_in_rphy(dev, rphy); sas_hash_addr(dev->hashed_sas_addr, dev->sas_addr); port->port_dev = dev; dev->linkrate = port->linkrate; dev->min_linkrate = port->linkrate; dev->max_linkrate = port->linkrate; dev->pathways = port->num_phys; memset(port->disc.fanout_sas_addr, 0, SAS_ADDR_SIZE); memset(port->disc.eeds_a, 0, SAS_ADDR_SIZE); memset(port->disc.eeds_b, 0, SAS_ADDR_SIZE); port->disc.max_level = 0; sas_device_set_phy(dev, port->port); dev->rphy = rphy; get_device(&dev->rphy->dev); if (dev_is_sata(dev) || dev->dev_type == SAS_END_DEVICE) list_add_tail(&dev->disco_list_node, &port->disco_list); else { spin_lock_irq(&port->dev_list_lock); list_add_tail(&dev->dev_list_node, &port->dev_list); spin_unlock_irq(&port->dev_list_lock); } spin_lock_irq(&port->phy_list_lock); list_for_each_entry(phy, &port->phy_list, port_phy_el) sas_phy_set_target(phy, dev); spin_unlock_irq(&port->phy_list_lock); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'scsi: libsas: stop discovering if oob mode is disconnected The discovering of sas port is driven by workqueue in libsas. When libsas is processing port events or phy events in workqueue, new events may rise up and change the state of some structures such as asd_sas_phy. This may cause some problems such as follows: ==>thread 1 ==>thread 2 ==>phy up ==>phy_up_v3_hw() ==>oob_mode = SATA_OOB_MODE; ==>phy down quickly ==>hisi_sas_phy_down() ==>sas_ha->notify_phy_event() ==>sas_phy_disconnected() ==>oob_mode = OOB_NOT_CONNECTED ==>workqueue wakeup ==>sas_form_port() ==>sas_discover_domain() ==>sas_get_port_device() ==>oob_mode is OOB_NOT_CONNECTED and device is wrongly taken as expander This at last lead to the panic when libsas trying to issue a command to discover the device. [183047.614035] Unable to handle kernel NULL pointer dereference at virtual address 0000000000000058 [183047.622896] Mem abort info: [183047.625762] ESR = 0x96000004 [183047.628893] Exception class = DABT (current EL), IL = 32 bits [183047.634888] SET = 0, FnV = 0 [183047.638015] EA = 0, S1PTW = 0 [183047.641232] Data abort info: [183047.644189] ISV = 0, ISS = 0x00000004 [183047.648100] CM = 0, WnR = 0 [183047.651145] user pgtable: 4k pages, 48-bit VAs, pgdp = 00000000b7df67be [183047.657834] [0000000000000058] pgd=0000000000000000 [183047.662789] Internal error: Oops: 96000004 [#1] SMP [183047.667740] Process kworker/u16:2 (pid: 31291, stack limit = 0x00000000417c4974) [183047.675208] CPU: 0 PID: 3291 Comm: kworker/u16:2 Tainted: G W OE 4.19.36-vhulk1907.1.0.h410.eulerosv2r8.aarch64 #1 [183047.687015] Hardware name: N/A N/A/Kunpeng Desktop Board D920S10, BIOS 0.15 10/22/2019 [183047.695007] Workqueue: 0000:74:02.0_disco_q sas_discover_domain [183047.700999] pstate: 20c00009 (nzCv daif +PAN +UAO) [183047.705864] pc : prep_ata_v3_hw+0xf8/0x230 [hisi_sas_v3_hw] [183047.711510] lr : prep_ata_v3_hw+0xb0/0x230 [hisi_sas_v3_hw] [183047.717153] sp : ffff00000f28ba60 [183047.720541] x29: ffff00000f28ba60 x28: ffff8026852d7228 [183047.725925] x27: ffff8027dba3e0a8 x26: ffff8027c05fc200 [183047.731310] x25: 0000000000000000 x24: ffff8026bafa8dc0 [183047.736695] x23: ffff8027c05fc218 x22: ffff8026852d7228 [183047.742079] x21: ffff80007c2f2940 x20: ffff8027c05fc200 [183047.747464] x19: 0000000000f80800 x18: 0000000000000010 [183047.752848] x17: 0000000000000000 x16: 0000000000000000 [183047.758232] x15: ffff000089a5a4ff x14: 0000000000000005 [183047.763617] x13: ffff000009a5a50e x12: ffff8026bafa1e20 [183047.769001] x11: ffff0000087453b8 x10: ffff00000f28b870 [183047.774385] x9 : 0000000000000000 x8 : ffff80007e58f9b0 [183047.779770] x7 : 0000000000000000 x6 : 000000000000003f [183047.785154] x5 : 0000000000000040 x4 : ffffffffffffffe0 [183047.790538] x3 : 00000000000000f8 x2 : 0000000002000007 [183047.795922] x1 : 0000000000000008 x0 : 0000000000000000 [183047.801307] Call trace: [183047.803827] prep_ata_v3_hw+0xf8/0x230 [hisi_sas_v3_hw] [183047.809127] hisi_sas_task_prep+0x750/0x888 [hisi_sas_main] [183047.814773] hisi_sas_task_exec.isra.7+0x88/0x1f0 [hisi_sas_main] [183047.820939] hisi_sas_queue_command+0x28/0x38 [hisi_sas_main] [183047.826757] smp_execute_task_sg+0xec/0x218 [183047.831013] smp_execute_task+0x74/0xa0 [183047.834921] sas_discover_expander.part.7+0x9c/0x5f8 [183047.839959] sas_discover_root_expander+0x90/0x160 [183047.844822] sas_discover_domain+0x1b8/0x1e8 [183047.849164] process_one_work+0x1b4/0x3f8 [183047.853246] worker_thread+0x54/0x470 [183047.856981] kthread+0x134/0x138 [183047.860283] ret_from_fork+0x10/0x18 [183047.863931] Code: f9407a80 528000e2 39409281 72a04002 (b9405800) [183047.870097] kernel fault(0x1) notification starting on CPU 0 [183047.875828] kernel fault(0x1) notification finished on CPU 0 [183047.881559] Modules linked in: unibsp(OE) hns3(OE) hclge(OE) hnae3(OE) mem_drv(OE) hisi_sas_v3_hw(OE) hisi_sas_main(OE) [183047.892418] ---[ end trace 4cc26083fc11b783 ]--- [183047.897107] Kernel panic - not syncing: Fatal exception [183047.902403] kernel fault(0x5) notification starting on CPU 0 [183047.908134] kernel fault(0x5) notification finished on CPU 0 [183047.913865] SMP: stopping secondary CPUs [183047.917861] Kernel Offset: disabled [183047.921422] CPU features: 0x2,a2a00a38 [183047.925243] Memory Limit: none [183047.928372] kernel reboot(0x2) notification starting on CPU 0 [183047.934190] kernel reboot(0x2) notification finished on CPU 0 [183047.940008] ---[ end Kernel panic - not syncing: Fatal exception ]--- Fixes: 2908d778ab3e ("[SCSI] aic94xx: new driver") Link: https://lore.kernel.org/r/20191206011118.46909-1-yanaijie@huawei.com Reported-by: Gao Chuan <gaochuan4@huawei.com> Reviewed-by: John Garry <john.garry@huawei.com> Signed-off-by: Jason Yan <yanaijie@huawei.com> Signed-off-by: Martin K. Petersen <martin.petersen@oracle.com>'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int async_polkit_callback(sd_bus_message *reply, void *userdata, sd_bus_error *error) { _cleanup_(sd_bus_error_free) sd_bus_error error_buffer = SD_BUS_ERROR_NULL; AsyncPolkitQuery *q = userdata; int r; assert(reply); assert(q); q->slot = sd_bus_slot_unref(q->slot); q->reply = sd_bus_message_ref(reply); r = sd_bus_message_rewind(q->request, true); if (r < 0) { r = sd_bus_reply_method_errno(q->request, r, NULL); goto finish; } r = q->callback(q->request, q->userdata, &error_buffer); r = bus_maybe_reply_error(q->request, r, &error_buffer); finish: async_polkit_query_free(q); return r; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'polkit: when authorizing via PK let's re-resolve callback/userdata instead of caching it Previously, when doing an async PK query we'd store the original callback/userdata pair and call it again after the PK request is complete. This is problematic, since PK queries might be slow and in the meantime the userdata might be released and re-acquired. Let's avoid this by always traversing through the message handlers so that we always re-resolve the callback and userdata pair and thus can be sure it's up-to-date and properly valid.'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: _public_ int sd_bus_enqeue_for_read(sd_bus *bus, sd_bus_message *m) { int r; assert_return(bus, -EINVAL); assert_return(bus = bus_resolve(bus), -ENOPKG); assert_return(m, -EINVAL); assert_return(m->sealed, -EINVAL); assert_return(!bus_pid_changed(bus), -ECHILD); if (!BUS_IS_OPEN(bus->state)) return -ENOTCONN; /* Re-enqeue a message for reading. This is primarily useful for PolicyKit-style authentication, * where we want accept a message, then determine we need to interactively authenticate the user, and * when we have that process the message again. */ r = bus_rqueue_make_room(bus); if (r < 0) return r; bus->rqueue[bus->rqueue_size++] = bus_message_ref_queued(m, bus); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-416'], 'message': 'Fix typo in function name'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static void listdir(unsigned int depth, int f, void * const tls_fd, const char *name) { PureFileInfo *dir; char *names; PureFileInfo *s; PureFileInfo *r; int d; if (depth >= max_ls_depth || matches >= max_ls_files) { return; } if ((dir = sreaddir(&names)) == NULL) { addreply(226, MSG_CANT_READ_FILE, name); return; } s = dir; while (s->name_offset != (size_t) -1) { d = 0; if (FI_NAME(s)[0] != '.') { d = listfile(s, NULL); } else if (opt_a) { if (FI_NAME(s)[1] == 0 || (FI_NAME(s)[1] == '.' && FI_NAME(s)[2] == 0)) { listfile(s, NULL); } else { d = listfile(s, NULL); } } if (!d) { s->name_offset = (size_t) -1; } s++; } outputfiles(f, tls_fd); r = dir; while (opt_R && r != s) { if (r->name_offset != (size_t) -1 && !chdir(FI_NAME(r))) { char *alloca_subdir; const size_t sizeof_subdir = PATH_MAX + 1U; if ((alloca_subdir = ALLOCA(sizeof_subdir)) == NULL) { goto toomany; } if (SNCHECK(snprintf(alloca_subdir, sizeof_subdir, "%s/%s", name, FI_NAME(r)), sizeof_subdir)) { goto nolist; } wrstr(f, tls_fd, "\r\n\r\n"); wrstr(f, tls_fd, alloca_subdir); wrstr(f, tls_fd, ":\r\n\r\n"); listdir(depth + 1U, f, tls_fd, alloca_subdir); nolist: ALLOCA_FREE(alloca_subdir); if (matches >= max_ls_files) { goto toomany; } if (chdir("..")) { /* defensive in the extreme... */ if (chdir(wd) || chdir(name)) { /* someone rmdir()'d it? */ die(421, LOG_ERR, "chdir: %s", strerror(errno)); } } } r++; } toomany: free(names); free(dir); names = NULL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-400', 'CWE-703'], 'message': 'listdir(): reuse a single buffer to store every file name to display Allocating a new buffer for each entry is useless. And as these buffers are allocated on the stack, on systems with a small stack size, with many entries, the limit can easily be reached, causing a stack exhaustion and aborting the user session. Reported by Antonio Morales from the GitHub Security Lab team, thanks!'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int i915_gem_context_destroy_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_gem_context_destroy *args = data; struct drm_i915_file_private *file_priv = file->driver_priv; struct i915_gem_context *ctx; int ret; if (args->pad != 0) return -EINVAL; if (args->ctx_id == DEFAULT_CONTEXT_HANDLE) return -ENOENT; ctx = i915_gem_context_lookup(file_priv, args->ctx_id); if (!ctx) return -ENOENT; ret = mutex_lock_interruptible(&dev->struct_mutex); if (ret) goto out; idr_remove(&file_priv->context_idr, ctx->user_handle); context_close(ctx); mutex_unlock(&dev->struct_mutex); out: i915_gem_context_put(ctx); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'drm/i915: Introduce a mutex for file_priv->context_idr Define a mutex for the exclusive use of interacting with the per-file context-idr, that was previously guarded by struct_mutex. This allows us to reduce the coverage of struct_mutex, with a view to removing the last bits coordinating GEM context later. (In the short term, we avoid taking struct_mutex while using the extended constructor functions, preventing some nasty recursion.) v2: s/context_lock/context_idr_lock/ Signed-off-by: Chris Wilson <chris@chris-wilson.co.uk> Cc: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Reviewed-by: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Link: https://patchwork.freedesktop.org/patch/msgid/20190321140711.11190-2-chris@chris-wilson.co.uk'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: int i915_gem_context_create_ioctl(struct drm_device *dev, void *data, struct drm_file *file) { struct drm_i915_private *i915 = to_i915(dev); struct drm_i915_gem_context_create *args = data; struct drm_i915_file_private *file_priv = file->driver_priv; struct i915_gem_context *ctx; int ret; if (!DRIVER_CAPS(i915)->has_logical_contexts) return -ENODEV; if (args->pad != 0) return -EINVAL; ret = i915_terminally_wedged(i915); if (ret) return ret; if (client_is_banned(file_priv)) { DRM_DEBUG("client %s[%d] banned from creating ctx\n", current->comm, pid_nr(get_task_pid(current, PIDTYPE_PID))); return -EIO; } ret = i915_mutex_lock_interruptible(dev); if (ret) return ret; ctx = i915_gem_create_context(i915); if (IS_ERR(ctx)) { ret = PTR_ERR(ctx); goto err_unlock; } ret = gem_context_register(ctx, file_priv); if (ret) goto err_ctx; mutex_unlock(&dev->struct_mutex); args->ctx_id = ctx->user_handle; DRM_DEBUG("HW context %d created\n", args->ctx_id); return 0; err_ctx: context_close(ctx); err_unlock: mutex_unlock(&dev->struct_mutex); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'drm/i915: Introduce a mutex for file_priv->context_idr Define a mutex for the exclusive use of interacting with the per-file context-idr, that was previously guarded by struct_mutex. This allows us to reduce the coverage of struct_mutex, with a view to removing the last bits coordinating GEM context later. (In the short term, we avoid taking struct_mutex while using the extended constructor functions, preventing some nasty recursion.) v2: s/context_lock/context_idr_lock/ Signed-off-by: Chris Wilson <chris@chris-wilson.co.uk> Cc: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Reviewed-by: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Link: https://patchwork.freedesktop.org/patch/msgid/20190321140711.11190-2-chris@chris-wilson.co.uk'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static int context_idr_cleanup(int id, void *p, void *data) { struct i915_gem_context *ctx = p; context_close(ctx); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416'], 'message': 'drm/i915: Introduce a mutex for file_priv->context_idr Define a mutex for the exclusive use of interacting with the per-file context-idr, that was previously guarded by struct_mutex. This allows us to reduce the coverage of struct_mutex, with a view to removing the last bits coordinating GEM context later. (In the short term, we avoid taking struct_mutex while using the extended constructor functions, preventing some nasty recursion.) v2: s/context_lock/context_idr_lock/ Signed-off-by: Chris Wilson <chris@chris-wilson.co.uk> Cc: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Reviewed-by: Tvrtko Ursulin <tvrtko.ursulin@intel.com> Link: https://patchwork.freedesktop.org/patch/msgid/20190321140711.11190-2-chris@chris-wilson.co.uk'</s>
<s>[INST] Given the following code containing errors, provide Common Weakness Enumeration (CWE) identifiers and corresponding messages in JSON format. Each identified weakness should have a unique entry in the JSON array. Code: static inline const u32 *flow_keys_hash_start(const struct flow_keys *flow) { const void *p = flow; BUILD_BUG_ON(FLOW_KEYS_HASH_OFFSET % sizeof(u32)); return (const u32 *)(p + FLOW_KEYS_HASH_OFFSET); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-330'], 'message': 'net/flow_dissector: switch to siphash UDP IPv6 packets auto flowlabels are using a 32bit secret (static u32 hashrnd in net/core/flow_dissector.c) and apply jhash() over fields known by the receivers. Attackers can easily infer the 32bit secret and use this information to identify a device and/or user, since this 32bit secret is only set at boot time. Really, using jhash() to generate cookies sent on the wire is a serious security concern. Trying to change the rol32(hash, 16) in ip6_make_flowlabel() would be a dead end. Trying to periodically change the secret (like in sch_sfq.c) could change paths taken in the network for long lived flows. Let's switch to siphash, as we did in commit df453700e8d8 ("inet: switch IP ID generator to siphash") Using a cryptographically strong pseudo random function will solve this privacy issue and more generally remove other weak points in the stack. Packet schedulers using skb_get_hash_perturb() benefit from this change. Fixes: b56774163f99 ("ipv6: Enable auto flow labels by default") Fixes: 42240901f7c4 ("ipv6: Implement different admin modes for automatic flow labels") Fixes: 67800f9b1f4e ("ipv6: Call skb_get_hash_flowi6 to get skb->hash in ip6_make_flowlabel") Fixes: cb1ce2ef387b ("ipv6: Implement automatic flow label generation on transmit") Signed-off-by: Eric Dumazet <edumazet@google.com> Reported-by: Jonathan Berger <jonathann1@walla.com> Reported-by: Amit Klein <aksecurity@gmail.com> Reported-by: Benny Pinkas <benny@pinkas.net> Cc: Tom Herbert <tom@herbertland.com> Signed-off-by: David S. Miller <davem@davemloft.net>'</s>