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: am_cache_entry_t *am_get_request_session_by_nameid(request_rec *r, char *nameid) { return am_cache_lock(r->server, AM_CACHE_NAMEID, nameid); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-79'], 'message': 'Fix Cross-Site Session Transfer vulnerability mod_auth_mellon did not verify that the site the session was created for was the same site as the site the user accessed. This allows an attacker with access to one web site on a server to use the same session to get access to a different site running on the same server. This patch fixes this vulnerability by storing the cookie parameters used when creating the session in the session, and verifying those parameters when the session is loaded. Thanks to François Kooman for reporting this vulnerability. This vulnerability has been assigned CVE-2017-6807.'</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 main(int argc, char **argv) { MYSQL mysql; option_string *eptr; MY_INIT(argv[0]); my_getopt_use_args_separator= TRUE; if (load_defaults("my",load_default_groups,&argc,&argv)) { my_end(0); exit(1); } my_getopt_use_args_separator= FALSE; defaults_argv=argv; if (get_options(&argc,&argv)) { free_defaults(defaults_argv); my_end(0); exit(1); } /* Seed the random number generator if we will be using it. */ if (auto_generate_sql) srandom((uint)time(NULL)); /* globals? Yes, so we only have to run strlen once */ delimiter_length= strlen(delimiter); if (argc > 2) { fprintf(stderr,"%s: Too many arguments\n",my_progname); free_defaults(defaults_argv); my_end(0); exit(1); } mysql_init(&mysql); if (opt_compress) mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) { mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl); mysql_options(&mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath); } #endif if (opt_protocol) mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); if (!opt_secure_auth && slap_connect(&mysql)) mysql_options(&mysql, MYSQL_SECURE_AUTH,(char*)&opt_secure_auth); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); mysql_options(&mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0); mysql_options4(&mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqlslap"); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*) &opt_enable_cleartext_plugin); if (!opt_only_print) { if (!(mysql_connect_ssl_check(&mysql, host, user, opt_password, NULL, opt_mysql_port, opt_mysql_unix_port, connect_flags, opt_ssl_required))) { fprintf(stderr,"%s: Error when connecting to server: %s\n", my_progname,mysql_error(&mysql)); free_defaults(defaults_argv); my_end(0); exit(1); } } pthread_mutex_init(&counter_mutex, NULL); pthread_cond_init(&count_threshhold, NULL); pthread_mutex_init(&sleeper_mutex, NULL); pthread_cond_init(&sleep_threshhold, NULL); /* Main iterations loop */ eptr= engine_options; do { /* For the final stage we run whatever queries we were asked to run */ uint *current; if (verbose >= 2) printf("Starting Concurrency Test\n"); if (*concurrency) { for (current= concurrency; current && *current; current++) concurrency_loop(&mysql, *current, eptr); } else { uint infinite= 1; do { concurrency_loop(&mysql, infinite, eptr); } while (infinite++); } if (!opt_preserve) drop_schema(&mysql, create_schema_string); } while (eptr ? (eptr= eptr->next) : 0); pthread_mutex_destroy(&counter_mutex); pthread_cond_destroy(&count_threshhold); pthread_mutex_destroy(&sleeper_mutex); pthread_cond_destroy(&sleep_threshhold); if (!opt_only_print) mysql_close(&mysql); /* Close & free connection */ /* now free all the strings we created */ my_free(opt_password); my_free(concurrency); statement_cleanup(create_statements); statement_cleanup(query_statements); statement_cleanup(pre_statements); statement_cleanup(post_statements); option_cleanup(engine_options); #ifdef HAVE_SMEM my_free(shared_memory_base_name); #endif free_defaults(defaults_argv); my_end(my_end_arg); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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 my_bool sql_connect(MYSQL *mysql, uint wait) { my_bool info=0; for (;;) { if (mysql_connect_ssl_check(mysql, host, user, opt_password, NullS, tcp_port, unix_port, CLIENT_REMEMBER_OPTIONS, opt_ssl_required)) { mysql->reconnect= 1; if (info) { fputs("\n",stderr); (void) fflush(stderr); } return 0; } if (!wait) // was or reached 0, fail { if (!option_silent) // print diagnostics { if (!host) host= (char*) LOCAL_HOST; my_printf_error(0,"connect to server at '%s' failed\nerror: '%s'", error_flags, host, mysql_error(mysql)); if (mysql_errno(mysql) == CR_CONNECTION_ERROR) { fprintf(stderr, "Check that mysqld is running and that the socket: '%s' exists!\n", unix_port ? unix_port : mysql_unix_port); } else if (mysql_errno(mysql) == CR_CONN_HOST_ERROR || mysql_errno(mysql) == CR_UNKNOWN_HOST) { fprintf(stderr,"Check that mysqld is running on %s",host); fprintf(stderr," and that the port is %d.\n", tcp_port ? tcp_port: mysql_port); fprintf(stderr,"You can check this by doing 'telnet %s %d'\n", host, tcp_port ? tcp_port: mysql_port); } } return 1; } if (wait != (uint) ~0) wait--; /* count down, one less retry */ if ((mysql_errno(mysql) != CR_CONN_HOST_ERROR) && (mysql_errno(mysql) != CR_CONNECTION_ERROR)) { /* Error is worse than "server doesn't answer (yet?)"; fail even if we still have "wait-coins" unless --force was also given. */ fprintf(stderr,"Got error: %s\n", mysql_error(mysql)); if (!option_force) return 1; } else if (!option_silent) { if (!info) { info=1; fputs("Waiting for MySQL server to answer",stderr); (void) fflush(stderr); } else { putc('.',stderr); (void) fflush(stderr); } } sleep(5); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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 main(int argc, char **argv) { int error; my_bool first_argument_uses_wildcards=0; char *wild; MYSQL mysql; MY_INIT(argv[0]); my_getopt_use_args_separator= TRUE; if (load_defaults("my",load_default_groups,&argc,&argv)) exit(1); my_getopt_use_args_separator= FALSE; get_options(&argc,&argv); wild=0; if (argc) { char *pos= argv[argc-1], *to; for (to= pos ; *pos ; pos++, to++) { switch (*pos) { case '*': *pos= '%'; first_argument_uses_wildcards= 1; break; case '?': *pos= '_'; first_argument_uses_wildcards= 1; break; case '%': case '_': first_argument_uses_wildcards= 1; break; case '\\': pos++; default: break; } *to= *pos; } *to= *pos; /* just to copy a '\0' if '\\' was used */ } if (first_argument_uses_wildcards) wild= argv[--argc]; else if (argc == 3) /* We only want one field */ wild= argv[--argc]; if (argc > 2) { fprintf(stderr,"%s: Too many arguments\n",my_progname); exit(1); } mysql_init(&mysql); if (opt_compress) mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) { mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl); mysql_options(&mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath); } mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); if (opt_bind_addr) mysql_options(&mysql,MYSQL_OPT_BIND,opt_bind_addr); if (!opt_secure_auth) mysql_options(&mysql, MYSQL_SECURE_AUTH,(char*)&opt_secure_auth); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*)&opt_enable_cleartext_plugin); mysql_options(&mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0); mysql_options4(&mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqlshow"); if (!(mysql_connect_ssl_check(&mysql, host, user, opt_password, (first_argument_uses_wildcards) ? "" : argv[0], opt_mysql_port, opt_mysql_unix_port, 0, opt_ssl_required))) { fprintf(stderr,"%s: %s\n",my_progname,mysql_error(&mysql)); exit(1); } mysql.reconnect= 1; switch (argc) { case 0: error=list_dbs(&mysql,wild); break; case 1: if (opt_status) error=list_table_status(&mysql,argv[0],wild); else error=list_tables(&mysql,argv[0],wild); break; default: if (opt_status && ! wild) error=list_table_status(&mysql,argv[0],argv[1]); else error=list_fields(&mysql,argv[0],argv[1],wild); break; } mysql_close(&mysql); /* Close & free connection */ my_free(opt_password); #ifdef HAVE_SMEM my_free(shared_memory_base_name); #endif my_end(my_end_arg); exit(error ? 1 : 0); return 0; /* No compiler warnings */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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: sql_real_connect(char *host,char *database,char *user,char *password, uint silent) { my_bool handle_expired= (opt_connect_expired_password || !status.batch) ? TRUE : FALSE; if (connected) { connected= 0; mysql_close(&mysql); } mysql_init(&mysql); if (opt_init_command) mysql_options(&mysql, MYSQL_INIT_COMMAND, opt_init_command); if (opt_connect_timeout) { uint timeout=opt_connect_timeout; mysql_options(&mysql,MYSQL_OPT_CONNECT_TIMEOUT, (char*) &timeout); } if (opt_bind_addr) mysql_options(&mysql, MYSQL_OPT_BIND, opt_bind_addr); if (opt_compress) mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS); if (!opt_secure_auth) mysql_options(&mysql, MYSQL_SECURE_AUTH, (char *) &opt_secure_auth); if (using_opt_local_infile) mysql_options(&mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_infile); #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) if (opt_use_ssl) { mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql, MYSQL_OPT_SSL_CRL, opt_ssl_crl); mysql_options(&mysql, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath); } mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif if (safe_updates) { char init_command[100]; sprintf(init_command, "SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=%lu,MAX_JOIN_SIZE=%lu", select_limit,max_join_size); mysql_options(&mysql, MYSQL_INIT_COMMAND, init_command); } mysql_set_character_set(&mysql, default_charset); #ifdef __WIN__ uint cnv_errors; String converted_database, converted_user; if (!my_charset_same(&my_charset_utf8mb4_bin, mysql.charset)) { /* Convert user and database from UTF8MB4 to connection character set */ if (user) { converted_user.copy(user, strlen(user) + 1, &my_charset_utf8mb4_bin, mysql.charset, &cnv_errors); user= (char *) converted_user.ptr(); } if (database) { converted_database.copy(database, strlen(database) + 1, &my_charset_utf8mb4_bin, mysql.charset, &cnv_errors); database= (char *) converted_database.ptr(); } } #endif if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); #if !defined(HAVE_YASSL) if (opt_server_public_key && *opt_server_public_key) mysql_options(&mysql, MYSQL_SERVER_PUBLIC_KEY, opt_server_public_key); #endif if (using_opt_enable_cleartext_plugin) mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*) &opt_enable_cleartext_plugin); mysql_options(&mysql, MYSQL_OPT_CONNECT_ATTR_RESET, 0); mysql_options4(&mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysql"); mysql_options(&mysql, MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS, &handle_expired); if (!mysql_connect_ssl_check(&mysql, host, user, password, database, opt_mysql_port, opt_mysql_unix_port, connect_flag | CLIENT_MULTI_STATEMENTS, opt_ssl_required)) { if (!silent || (mysql_errno(&mysql) != CR_CONN_HOST_ERROR && mysql_errno(&mysql) != CR_CONNECTION_ERROR)) { (void) put_error(&mysql); (void) fflush(stdout); return ignore_errors ? -1 : 1; // Abort } return -1; // Retryable } #ifdef __WIN__ /* Convert --execute buffer from UTF8MB4 to connection character set */ if (!execute_buffer_conversion_done++ && status.line_buff && !status.line_buff->file && /* Convert only -e buffer, not real file */ status.line_buff->buffer < status.line_buff->end && /* Non-empty */ !my_charset_same(&my_charset_utf8mb4_bin, mysql.charset)) { String tmp; size_t len= status.line_buff->end - status.line_buff->buffer; uint dummy_errors; /* Don't convert trailing '\n' character - it was appended during last batch_readline_command() call. Oherwise we'll get an extra line, which makes some tests fail. */ if (status.line_buff->buffer[len - 1] == '\n') len--; if (tmp.copy(status.line_buff->buffer, len, &my_charset_utf8mb4_bin, mysql.charset, &dummy_errors)) return 1; /* Free the old line buffer */ batch_readline_end(status.line_buff); /* Re-initialize line buffer from the converted string */ if (!(status.line_buff= batch_readline_command(NULL, (char *) tmp.c_ptr_safe()))) return 1; } #endif /* __WIN__ */ charset_info= mysql.charset; connected=1; #ifndef EMBEDDED_LIBRARY mysql.reconnect= debug_info_flag; // We want to know if this happens #else mysql.reconnect= 1; #endif #ifdef HAVE_READLINE build_completion_hash(opt_rehash, 1); #endif return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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: MYSQL *mysql_connect_ssl_check(MYSQL *mysql_arg, const char *host, const char *user, const char *passwd, const char *db, uint port, const char *unix_socket, ulong client_flag, my_bool ssl_required MY_ATTRIBUTE((unused))) { MYSQL *mysql= mysql_real_connect(mysql_arg, host, user, passwd, db, port, unix_socket, client_flag); #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) if (mysql && /* connection established. */ ssl_required && /* --ssl-mode=REQUIRED. */ !mysql_get_ssl_cipher(mysql)) /* non-SSL connection. */ { NET *net= &mysql->net; net->last_errno= CR_SSL_CONNECTION_ERROR; strmov(net->last_error, "--ssl-mode=REQUIRED option forbids non SSL connections"); strmov(net->sqlstate, "HY000"); return NULL; } #endif return mysql; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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 run_tool(char *tool_path, DYNAMIC_STRING *ds_res, ...) { int ret; const char* arg; va_list args; DYNAMIC_STRING ds_cmdline; DBUG_ENTER("run_tool"); DBUG_PRINT("enter", ("tool_path: %s", tool_path)); if (init_dynamic_string(&ds_cmdline, IF_WIN("\"", ""), FN_REFLEN, FN_REFLEN)) die("Out of memory"); dynstr_append_os_quoted(&ds_cmdline, tool_path, NullS); dynstr_append(&ds_cmdline, " "); va_start(args, ds_res); while ((arg= va_arg(args, char *))) { /* Options should be os quoted */ if (strncmp(arg, "--", 2) == 0) dynstr_append_os_quoted(&ds_cmdline, arg, NullS); else dynstr_append(&ds_cmdline, arg); dynstr_append(&ds_cmdline, " "); } va_end(args); /* If given --ssl-mode=REQUIRED propagate it to the tool. */ if (opt_ssl_required) dynstr_append(&ds_cmdline, "--ssl-mode=REQUIRED"); #ifdef __WIN__ dynstr_append(&ds_cmdline, "\""); #endif DBUG_PRINT("info", ("Running: %s", ds_cmdline.str)); ret= run_command(ds_cmdline.str, ds_res); DBUG_PRINT("exit", ("ret: %d", ret)); dynstr_free(&ds_cmdline); DBUG_RETURN(ret); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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 connect_to_db(char *host, char *user,char *passwd) { char buff[20+FN_REFLEN]; DBUG_ENTER("connect_to_db"); verbose_msg("-- Connecting to %s...\n", host ? host : "localhost"); mysql_init(&mysql_connection); if (opt_compress) mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) { mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRL, opt_ssl_crl); mysql_options(&mysql_connection, MYSQL_OPT_SSL_CRLPATH, opt_ssl_crlpath); } mysql_options(&mysql_connection,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); if (opt_bind_addr) mysql_options(&mysql_connection,MYSQL_OPT_BIND,opt_bind_addr); if (!opt_secure_auth) mysql_options(&mysql_connection,MYSQL_SECURE_AUTH,(char*)&opt_secure_auth); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql_connection, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char *) &opt_enable_cleartext_plugin); mysql_options(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_RESET, 0); mysql_options4(&mysql_connection, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "mysqldump"); if (!(mysql= mysql_connect_ssl_check(&mysql_connection, host, user, passwd, NULL, opt_mysql_port, opt_mysql_unix_port, 0, opt_ssl_required))) { DB_error(&mysql_connection, "when trying to connect"); DBUG_RETURN(1); } if ((mysql_get_server_version(&mysql_connection) < 40100) || (opt_compatible_mode & 3)) { /* Don't dump SET NAMES with a pre-4.1 server (bug#7997). */ opt_set_charset= 0; /* Don't switch charsets for 4.1 and earlier. (bug#34192). */ server_supports_switching_charsets= FALSE; } /* As we're going to set SQL_MODE, it would be lost on reconnect, so we cannot reconnect. */ mysql->reconnect= 0; my_snprintf(buff, sizeof(buff), "/*!40100 SET @@SQL_MODE='%s' */", compatible_mode_normal_str); if (mysql_query_with_error_report(mysql, 0, buff)) DBUG_RETURN(1); /* set time_zone to UTC to allow dumping date types between servers with different time zone settings */ if (opt_tz_utc) { my_snprintf(buff, sizeof(buff), "/*!40103 SET TIME_ZONE='+00:00' */"); if (mysql_query_with_error_report(mysql, 0, buff)) DBUG_RETURN(1); } DBUG_RETURN(0); } /* connect_to_db */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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 STDCALL mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg) { DBUG_ENTER("mysql_option"); DBUG_PRINT("enter",("option: %d",(int) option)); switch (option) { case MYSQL_OPT_CONNECT_TIMEOUT: mysql->options.connect_timeout= *(uint*) arg; break; case MYSQL_OPT_READ_TIMEOUT: mysql->options.read_timeout= *(uint*) arg; break; case MYSQL_OPT_WRITE_TIMEOUT: mysql->options.write_timeout= *(uint*) arg; break; case MYSQL_OPT_COMPRESS: mysql->options.compress= 1; /* Remember for connect */ mysql->options.client_flag|= CLIENT_COMPRESS; break; case MYSQL_OPT_NAMED_PIPE: /* This option is depricated */ mysql->options.protocol=MYSQL_PROTOCOL_PIPE; /* Force named pipe */ break; case MYSQL_OPT_LOCAL_INFILE: /* Allow LOAD DATA LOCAL ?*/ if (!arg || MY_TEST(*(uint*) arg)) mysql->options.client_flag|= CLIENT_LOCAL_FILES; else mysql->options.client_flag&= ~CLIENT_LOCAL_FILES; break; case MYSQL_INIT_COMMAND: add_init_command(&mysql->options,arg); break; case MYSQL_READ_DEFAULT_FILE: my_free(mysql->options.my_cnf_file); mysql->options.my_cnf_file=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_READ_DEFAULT_GROUP: my_free(mysql->options.my_cnf_group); mysql->options.my_cnf_group=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_SET_CHARSET_DIR: my_free(mysql->options.charset_dir); mysql->options.charset_dir=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_SET_CHARSET_NAME: my_free(mysql->options.charset_name); mysql->options.charset_name=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_OPT_PROTOCOL: mysql->options.protocol= *(uint*) arg; break; case MYSQL_SHARED_MEMORY_BASE_NAME: #ifdef HAVE_SMEM if (mysql->options.shared_memory_base_name != def_shared_memory_base_name) my_free(mysql->options.shared_memory_base_name); mysql->options.shared_memory_base_name=my_strdup(arg,MYF(MY_WME)); #endif break; case MYSQL_OPT_USE_REMOTE_CONNECTION: case MYSQL_OPT_USE_EMBEDDED_CONNECTION: case MYSQL_OPT_GUESS_CONNECTION: mysql->options.methods_to_use= option; break; case MYSQL_SET_CLIENT_IP: my_free(mysql->options.ci.client_ip); mysql->options.ci.client_ip= my_strdup(arg, MYF(MY_WME)); break; case MYSQL_SECURE_AUTH: mysql->options.secure_auth= *(my_bool *) arg; break; case MYSQL_REPORT_DATA_TRUNCATION: mysql->options.report_data_truncation= MY_TEST(*(my_bool *) arg); break; case MYSQL_OPT_RECONNECT: mysql->reconnect= *(my_bool *) arg; break; case MYSQL_OPT_BIND: my_free(mysql->options.ci.bind_address); mysql->options.ci.bind_address= my_strdup(arg, MYF(MY_WME)); break; case MYSQL_OPT_SSL_VERIFY_SERVER_CERT: if (*(my_bool*) arg) mysql->options.client_flag|= CLIENT_SSL_VERIFY_SERVER_CERT; else mysql->options.client_flag&= ~CLIENT_SSL_VERIFY_SERVER_CERT; break; case MYSQL_PLUGIN_DIR: EXTENSION_SET_STRING(&mysql->options, plugin_dir, arg); break; case MYSQL_DEFAULT_AUTH: EXTENSION_SET_STRING(&mysql->options, default_auth, arg); break; case MYSQL_OPT_SSL_KEY: if (mysql->options.ssl_key) my_free(mysql->options.ssl_key); mysql->options.ssl_key= set_ssl_option_unpack_path(&mysql->options, arg); break; case MYSQL_OPT_SSL_CERT: if (mysql->options.ssl_cert) my_free(mysql->options.ssl_cert); mysql->options.ssl_cert= set_ssl_option_unpack_path(&mysql->options, arg); break; case MYSQL_OPT_SSL_CA: if (mysql->options.ssl_ca) my_free(mysql->options.ssl_ca); mysql->options.ssl_ca= set_ssl_option_unpack_path(&mysql->options, arg); break; case MYSQL_OPT_SSL_CAPATH: if (mysql->options.ssl_capath) my_free(mysql->options.ssl_capath); mysql->options.ssl_capath= set_ssl_option_unpack_path(&mysql->options, arg); break; case MYSQL_OPT_SSL_CIPHER: SET_SSL_OPTION(ssl_cipher, arg); break; case MYSQL_OPT_SSL_CRL: if (mysql->options.extension) my_free(mysql->options.extension->ssl_crl); else ALLOCATE_EXTENSIONS(&mysql->options); mysql->options.extension->ssl_crl= set_ssl_option_unpack_path(&mysql->options, arg); break; case MYSQL_OPT_SSL_CRLPATH: if (mysql->options.extension) my_free(mysql->options.extension->ssl_crlpath); else ALLOCATE_EXTENSIONS(&mysql->options); mysql->options.extension->ssl_crlpath= set_ssl_option_unpack_path(&mysql->options, arg); break; case MYSQL_SERVER_PUBLIC_KEY: EXTENSION_SET_STRING(&mysql->options, server_public_key_path, arg); break; case MYSQL_OPT_CONNECT_ATTR_RESET: ENSURE_EXTENSIONS_PRESENT(&mysql->options); if (my_hash_inited(&mysql->options.extension->connection_attributes)) { my_hash_free(&mysql->options.extension->connection_attributes); mysql->options.extension->connection_attributes_length= 0; } break; case MYSQL_OPT_CONNECT_ATTR_DELETE: ENSURE_EXTENSIONS_PRESENT(&mysql->options); if (my_hash_inited(&mysql->options.extension->connection_attributes)) { size_t len; uchar *elt; len= arg ? strlen(arg) : 0; if (len) { elt= my_hash_search(&mysql->options.extension->connection_attributes, arg, len); if (elt) { LEX_STRING *attr= (LEX_STRING *) elt; LEX_STRING *key= attr, *value= attr + 1; mysql->options.extension->connection_attributes_length-= get_length_store_length(key->length) + key->length + get_length_store_length(value->length) + value->length; my_hash_delete(&mysql->options.extension->connection_attributes, elt); } } } break; case MYSQL_ENABLE_CLEARTEXT_PLUGIN: ENSURE_EXTENSIONS_PRESENT(&mysql->options); mysql->options.extension->enable_cleartext_plugin= (*(my_bool*) arg) ? TRUE : FALSE; break; case MYSQL_OPT_CAN_HANDLE_EXPIRED_PASSWORDS: if (*(my_bool*) arg) mysql->options.client_flag|= CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS; else mysql->options.client_flag&= ~CLIENT_CAN_HANDLE_EXPIRED_PASSWORDS; break; default: DBUG_RETURN(1); } DBUG_RETURN(0); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit f91b941842d240b8a62645e507f5554e8be76aec)'</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 STDCALL mysql_options(MYSQL *mysql,enum mysql_option option, const void *arg) { DBUG_ENTER("mysql_option"); DBUG_PRINT("enter",("option: %d",(int) option)); switch (option) { case MYSQL_OPT_CONNECT_TIMEOUT: mysql->options.connect_timeout= *(uint*) arg; break; case MYSQL_OPT_READ_TIMEOUT: mysql->options.read_timeout= *(uint*) arg; break; case MYSQL_OPT_WRITE_TIMEOUT: mysql->options.write_timeout= *(uint*) arg; break; case MYSQL_OPT_COMPRESS: mysql->options.compress= 1; /* Remember for connect */ mysql->options.client_flag|= CLIENT_COMPRESS; break; case MYSQL_OPT_NAMED_PIPE: /* This option is depricated */ mysql->options.protocol=MYSQL_PROTOCOL_PIPE; /* Force named pipe */ break; case MYSQL_OPT_LOCAL_INFILE: /* Allow LOAD DATA LOCAL ?*/ if (!arg || test(*(uint*) arg)) mysql->options.client_flag|= CLIENT_LOCAL_FILES; else mysql->options.client_flag&= ~CLIENT_LOCAL_FILES; break; case MYSQL_INIT_COMMAND: add_init_command(&mysql->options,arg); break; case MYSQL_READ_DEFAULT_FILE: my_free(mysql->options.my_cnf_file); mysql->options.my_cnf_file=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_READ_DEFAULT_GROUP: my_free(mysql->options.my_cnf_group); mysql->options.my_cnf_group=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_SET_CHARSET_DIR: my_free(mysql->options.charset_dir); mysql->options.charset_dir=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_SET_CHARSET_NAME: my_free(mysql->options.charset_name); mysql->options.charset_name=my_strdup(arg,MYF(MY_WME)); break; case MYSQL_OPT_PROTOCOL: mysql->options.protocol= *(uint*) arg; break; case MYSQL_SHARED_MEMORY_BASE_NAME: #ifdef HAVE_SMEM if (mysql->options.shared_memory_base_name != def_shared_memory_base_name) my_free(mysql->options.shared_memory_base_name); mysql->options.shared_memory_base_name=my_strdup(arg,MYF(MY_WME)); #endif break; case MYSQL_OPT_USE_REMOTE_CONNECTION: case MYSQL_OPT_USE_EMBEDDED_CONNECTION: case MYSQL_OPT_GUESS_CONNECTION: mysql->options.methods_to_use= option; break; case MYSQL_SET_CLIENT_IP: my_free(mysql->options.client_ip); mysql->options.client_ip= my_strdup(arg, MYF(MY_WME)); break; case MYSQL_SECURE_AUTH: mysql->options.secure_auth= *(my_bool *) arg; break; case MYSQL_REPORT_DATA_TRUNCATION: mysql->options.report_data_truncation= test(*(my_bool *) arg); break; case MYSQL_OPT_RECONNECT: mysql->reconnect= *(my_bool *) arg; break; case MYSQL_OPT_SSL_VERIFY_SERVER_CERT: if (*(my_bool*) arg) mysql->options.client_flag|= CLIENT_SSL_VERIFY_SERVER_CERT; else mysql->options.client_flag&= ~CLIENT_SSL_VERIFY_SERVER_CERT; break; case MYSQL_PLUGIN_DIR: EXTENSION_SET_STRING(&mysql->options, plugin_dir, arg); break; case MYSQL_DEFAULT_AUTH: EXTENSION_SET_STRING(&mysql->options, default_auth, arg); break; case MYSQL_ENABLE_CLEARTEXT_PLUGIN: ENSURE_EXTENSIONS_PRESENT(&mysql->options); mysql->options.extension->enable_cleartext_plugin= (*(my_bool*) arg) ? TRUE : FALSE; break; default: DBUG_RETURN(1); } DBUG_RETURN(0); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 connect_to_db(char *host, char *user,char *passwd) { char buff[20+FN_REFLEN]; DBUG_ENTER("connect_to_db"); verbose_msg("-- Connecting to %s...\n", host ? host : "localhost"); mysql_init(&mysql_connection); if (opt_compress) mysql_options(&mysql_connection,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) mysql_ssl_set(&mysql_connection, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql_connection,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(&mysql_connection,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql_connection,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql_connection, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql_connection, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql_connection, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql_connection, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char *) &opt_enable_cleartext_plugin); if (!(mysql= mysql_connect_ssl_check(&mysql_connection, host, user, passwd, NULL, opt_mysql_port, opt_mysql_unix_port, 0, opt_ssl_required))) { DB_error(&mysql_connection, "when trying to connect"); DBUG_RETURN(1); } if ((mysql_get_server_version(&mysql_connection) < 40100) || (opt_compatible_mode & 3)) { /* Don't dump SET NAMES with a pre-4.1 server (bug#7997). */ opt_set_charset= 0; /* Don't switch charsets for 4.1 and earlier. (bug#34192). */ server_supports_switching_charsets= FALSE; } /* As we're going to set SQL_MODE, it would be lost on reconnect, so we cannot reconnect. */ mysql->reconnect= 0; my_snprintf(buff, sizeof(buff), "/*!40100 SET @@SQL_MODE='%s' */", compatible_mode_normal_str); if (mysql_query_with_error_report(mysql, 0, buff)) DBUG_RETURN(1); /* set time_zone to UTC to allow dumping date types between servers with different time zone settings */ if (opt_tz_utc) { my_snprintf(buff, sizeof(buff), "/*!40103 SET TIME_ZONE='+00:00' */"); if (mysql_query_with_error_report(mysql, 0, buff)) DBUG_RETURN(1); } DBUG_RETURN(0); } /* connect_to_db */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 connect_n_handle_errors(struct st_command *command, MYSQL* con, const char* host, const char* user, const char* pass, const char* db, int port, const char* sock) { DYNAMIC_STRING *ds; int failed_attempts= 0; ds= &ds_res; /* Only log if an error is expected */ if (command->expected_errors.count > 0 && !disable_query_log) { /* Log the connect to result log */ dynstr_append_mem(ds, "connect(", 8); replace_dynstr_append(ds, host); dynstr_append_mem(ds, ",", 1); replace_dynstr_append(ds, user); dynstr_append_mem(ds, ",", 1); replace_dynstr_append(ds, pass); dynstr_append_mem(ds, ",", 1); if (db) replace_dynstr_append(ds, db); dynstr_append_mem(ds, ",", 1); replace_dynstr_append_uint(ds, port); dynstr_append_mem(ds, ",", 1); if (sock) replace_dynstr_append(ds, sock); dynstr_append_mem(ds, ")", 1); dynstr_append_mem(ds, delimiter, delimiter_length); dynstr_append_mem(ds, "\n", 1); } /* Simlified logging if enabled */ if (!disable_connect_log && !disable_query_log) { replace_dynstr_append(ds, command->query); dynstr_append_mem(ds, ";\n", 2); } while (!mysql_connect_ssl_check(con, host, user, pass, db, port, sock ? sock: 0, CLIENT_MULTI_STATEMENTS, opt_ssl_required)) { /* If we have used up all our connections check whether this is expected (by --error). If so, handle the error right away. Otherwise, give it some extra time to rule out race-conditions. If extra-time doesn't help, we have an unexpected error and must abort -- just proceeding to handle_error() when second and third chances are used up will handle that for us. There are various user-limits of which only max_user_connections and max_connections_per_hour apply at connect time. For the the second to create a race in our logic, we'd need a limits test that runs without a FLUSH for longer than an hour, so we'll stay clear of trying to work out which exact user-limit was exceeded. */ if (((mysql_errno(con) == ER_TOO_MANY_USER_CONNECTIONS) || (mysql_errno(con) == ER_USER_LIMIT_REACHED)) && (failed_attempts++ < opt_max_connect_retries)) { int i; i= match_expected_error(command, mysql_errno(con), mysql_sqlstate(con)); if (i >= 0) goto do_handle_error; /* expected error, handle */ my_sleep(connection_retry_sleep); /* unexpected error, wait */ continue; /* and give it 1 more chance */ } do_handle_error: var_set_errno(mysql_errno(con)); handle_error(command, mysql_errno(con), mysql_error(con), mysql_sqlstate(con), ds); return 0; /* Not connected */ } var_set_errno(0); handle_no_error(command); revert_properties(); return 1; /* Connected */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 mysql_read_default_options(struct st_mysql_options *options, const char *filename,const char *group) { int argc; char *argv_buff[1],**argv; const char *groups[3]; DBUG_ENTER("mysql_read_default_options"); DBUG_PRINT("enter",("file: %s group: %s",filename,group ? group :"NULL")); compile_time_assert(OPT_keep_this_one_last == array_elements(default_options)); argc=1; argv=argv_buff; argv_buff[0]= (char*) "client"; groups[0]= (char*) "client"; groups[1]= (char*) group; groups[2]=0; my_load_defaults(filename, groups, &argc, &argv, NULL); if (argc != 1) /* If some default option */ { char **option=argv; while (*++option) { if (my_getopt_is_args_separator(option[0])) /* skip arguments separator */ continue; /* DBUG_PRINT("info",("option: %s",option[0])); */ if (option[0][0] == '-' && option[0][1] == '-') { char *end=strcend(*option,'='); char *opt_arg=0; if (*end) { opt_arg=end+1; *end=0; /* Remove '=' */ } /* Change all '_' in variable name to '-' */ for (end= *option ; *(end= strcend(end,'_')) ; ) *end= '-'; switch (find_type(*option + 2, &option_types, FIND_TYPE_BASIC)) { case OPT_port: if (opt_arg) options->port=atoi(opt_arg); break; case OPT_socket: if (opt_arg) { my_free(options->unix_socket); options->unix_socket=my_strdup(opt_arg,MYF(MY_WME)); } break; case OPT_compress: options->compress=1; options->client_flag|= CLIENT_COMPRESS; break; case OPT_password: if (opt_arg) { my_free(options->password); options->password=my_strdup(opt_arg,MYF(MY_WME)); } break; case OPT_pipe: options->protocol = MYSQL_PROTOCOL_PIPE; case OPT_connect_timeout: case OPT_timeout: if (opt_arg) options->connect_timeout=atoi(opt_arg); break; case OPT_user: if (opt_arg) { my_free(options->user); options->user=my_strdup(opt_arg,MYF(MY_WME)); } break; case OPT_init_command: add_init_command(options,opt_arg); break; case OPT_host: if (opt_arg) { my_free(options->host); options->host=my_strdup(opt_arg,MYF(MY_WME)); } break; case OPT_database: if (opt_arg) { my_free(options->db); options->db=my_strdup(opt_arg,MYF(MY_WME)); } break; case OPT_debug: #ifdef MYSQL_CLIENT mysql_debug(opt_arg ? opt_arg : "d:t:o,/tmp/client.trace"); break; #endif case OPT_return_found_rows: options->client_flag|=CLIENT_FOUND_ROWS; break; #if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) case OPT_ssl_key: my_free(options->ssl_key); options->ssl_key = my_strdup(opt_arg, MYF(MY_WME)); break; case OPT_ssl_cert: my_free(options->ssl_cert); options->ssl_cert = my_strdup(opt_arg, MYF(MY_WME)); break; case OPT_ssl_ca: my_free(options->ssl_ca); options->ssl_ca = my_strdup(opt_arg, MYF(MY_WME)); break; case OPT_ssl_capath: my_free(options->ssl_capath); options->ssl_capath = my_strdup(opt_arg, MYF(MY_WME)); break; case OPT_ssl_cipher: my_free(options->ssl_cipher); options->ssl_cipher= my_strdup(opt_arg, MYF(MY_WME)); break; #else case OPT_ssl_key: case OPT_ssl_cert: case OPT_ssl_ca: case OPT_ssl_capath: case OPT_ssl_cipher: break; #endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */ case OPT_character_sets_dir: my_free(options->charset_dir); options->charset_dir = my_strdup(opt_arg, MYF(MY_WME)); break; case OPT_default_character_set: my_free(options->charset_name); options->charset_name = my_strdup(opt_arg, MYF(MY_WME)); break; case OPT_interactive_timeout: options->client_flag|= CLIENT_INTERACTIVE; break; case OPT_local_infile: if (!opt_arg || atoi(opt_arg) != 0) options->client_flag|= CLIENT_LOCAL_FILES; else options->client_flag&= ~CLIENT_LOCAL_FILES; break; case OPT_disable_local_infile: options->client_flag&= ~CLIENT_LOCAL_FILES; break; case OPT_max_allowed_packet: if (opt_arg) options->max_allowed_packet= atoi(opt_arg); break; case OPT_protocol: if ((options->protocol= find_type(opt_arg, &sql_protocol_typelib, FIND_TYPE_BASIC)) <= 0) { fprintf(stderr, "Unknown option to protocol: %s\n", opt_arg); exit(1); } break; case OPT_shared_memory_base_name: #ifdef HAVE_SMEM if (options->shared_memory_base_name != def_shared_memory_base_name) my_free(options->shared_memory_base_name); options->shared_memory_base_name=my_strdup(opt_arg,MYF(MY_WME)); #endif break; case OPT_multi_results: options->client_flag|= CLIENT_MULTI_RESULTS; break; case OPT_multi_statements: case OPT_multi_queries: options->client_flag|= CLIENT_MULTI_STATEMENTS | CLIENT_MULTI_RESULTS; break; case OPT_secure_auth: options->secure_auth= TRUE; break; case OPT_report_data_truncation: options->report_data_truncation= opt_arg ? test(atoi(opt_arg)) : 1; break; case OPT_plugin_dir: { char buff[FN_REFLEN], buff2[FN_REFLEN]; if (strlen(opt_arg) >= FN_REFLEN) opt_arg[FN_REFLEN]= '\0'; if (my_realpath(buff, opt_arg, 0)) { DBUG_PRINT("warning",("failed to normalize the plugin path: %s", opt_arg)); break; } convert_dirname(buff2, buff, NULL); EXTENSION_SET_STRING(options, plugin_dir, buff2); } break; case OPT_default_auth: EXTENSION_SET_STRING(options, default_auth, opt_arg); break; case OPT_enable_cleartext_plugin: ENSURE_EXTENSIONS_PRESENT(options); options->extension->enable_cleartext_plugin= (!opt_arg || atoi(opt_arg) != 0) ? TRUE : FALSE; break; default: DBUG_PRINT("warning",("unknown option: %s",option[0])); } } } } free_defaults(argv); DBUG_VOID_RETURN; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 MYSQL *db_connect(char *host, char *database, char *user, char *passwd) { MYSQL *mysql; if (verbose) fprintf(stdout, "Connecting to %s\n", host ? host : "localhost"); if (opt_use_threads && !lock_tables) { pthread_mutex_lock(&init_mutex); if (!(mysql= mysql_init(NULL))) { pthread_mutex_unlock(&init_mutex); return 0; } pthread_mutex_unlock(&init_mutex); } else if (!(mysql= mysql_init(NULL))) return 0; if (opt_compress) mysql_options(mysql,MYSQL_OPT_COMPRESS,NullS); if (opt_local_file) mysql_options(mysql,MYSQL_OPT_LOCAL_INFILE, (char*) &opt_local_file); #ifdef HAVE_OPENSSL if (opt_use_ssl) mysql_ssl_set(mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif if (opt_plugin_dir && *opt_plugin_dir) mysql_options(mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*)&opt_enable_cleartext_plugin); mysql_options(mysql, MYSQL_SET_CHARSET_NAME, default_charset); if (!(mysql_connect_ssl_check(mysql, host, user, passwd, database, opt_mysql_port, opt_mysql_unix_port, 0, opt_ssl_required))) { ignore_errors=0; /* NO RETURN FROM db_error */ db_error(mysql); } mysql->reconnect= 0; if (verbose) fprintf(stdout, "Selecting database %s\n", database); if (mysql_select_db(mysql, database)) { ignore_errors=0; db_error(mysql); } return mysql; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 main(int argc, char **argv) { int error; my_bool first_argument_uses_wildcards=0; char *wild; MYSQL mysql; MY_INIT(argv[0]); if (load_defaults("my",load_default_groups,&argc,&argv)) exit(1); get_options(&argc,&argv); wild=0; if (argc) { char *pos= argv[argc-1], *to; for (to= pos ; *pos ; pos++, to++) { switch (*pos) { case '*': *pos= '%'; first_argument_uses_wildcards= 1; break; case '?': *pos= '_'; first_argument_uses_wildcards= 1; break; case '%': case '_': first_argument_uses_wildcards= 1; break; case '\\': pos++; default: break; } *to= *pos; } *to= *pos; /* just to copy a '\0' if '\\' was used */ } if (first_argument_uses_wildcards) wild= argv[--argc]; else if (argc == 3) /* We only want one field */ wild= argv[--argc]; if (argc > 2) { fprintf(stderr,"%s: Too many arguments\n",my_progname); exit(1); } mysql_init(&mysql); if (opt_compress) mysql_options(&mysql,MYSQL_OPT_COMPRESS,NullS); #ifdef HAVE_OPENSSL if (opt_use_ssl) mysql_ssl_set(&mysql, opt_ssl_key, opt_ssl_cert, opt_ssl_ca, opt_ssl_capath, opt_ssl_cipher); mysql_options(&mysql,MYSQL_OPT_SSL_VERIFY_SERVER_CERT, (char*)&opt_ssl_verify_server_cert); #endif if (opt_protocol) mysql_options(&mysql,MYSQL_OPT_PROTOCOL,(char*)&opt_protocol); #ifdef HAVE_SMEM if (shared_memory_base_name) mysql_options(&mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name); #endif mysql_options(&mysql, MYSQL_SET_CHARSET_NAME, default_charset); if (opt_plugin_dir && *opt_plugin_dir) mysql_options(&mysql, MYSQL_PLUGIN_DIR, opt_plugin_dir); if (opt_default_auth && *opt_default_auth) mysql_options(&mysql, MYSQL_DEFAULT_AUTH, opt_default_auth); if (using_opt_enable_cleartext_plugin) mysql_options(&mysql, MYSQL_ENABLE_CLEARTEXT_PLUGIN, (char*)&opt_enable_cleartext_plugin); if (!(mysql_connect_ssl_check(&mysql, host, user, opt_password, (first_argument_uses_wildcards) ? "" : argv[0], opt_mysql_port, opt_mysql_unix_port, 0, opt_ssl_required))) { fprintf(stderr,"%s: %s\n",my_progname,mysql_error(&mysql)); exit(1); } mysql.reconnect= 1; switch (argc) { case 0: error=list_dbs(&mysql,wild); break; case 1: if (opt_status) error=list_table_status(&mysql,argv[0],wild); else error=list_tables(&mysql,argv[0],wild); break; default: if (opt_status && ! wild) error=list_table_status(&mysql,argv[0],argv[1]); else error=list_fields(&mysql,argv[0],argv[1],wild); break; } mysql_close(&mysql); /* Close & free connection */ my_free(opt_password); #ifdef HAVE_SMEM my_free(shared_memory_base_name); #endif my_end(my_end_arg); exit(error ? 1 : 0); return 0; /* No compiler warnings */ } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 mysql_ssl_free(MYSQL *mysql __attribute__((unused))) { struct st_VioSSLFd *ssl_fd= (struct st_VioSSLFd*) mysql->connector_fd; DBUG_ENTER("mysql_ssl_free"); my_free(mysql->options.ssl_key); my_free(mysql->options.ssl_cert); my_free(mysql->options.ssl_ca); my_free(mysql->options.ssl_capath); my_free(mysql->options.ssl_cipher); if (ssl_fd) SSL_CTX_free(ssl_fd->ssl_context); my_free(mysql->connector_fd); mysql->options.ssl_key = 0; mysql->options.ssl_cert = 0; mysql->options.ssl_ca = 0; mysql->options.ssl_capath = 0; mysql->options.ssl_cipher= 0; mysql->options.use_ssl = FALSE; mysql->connector_fd = 0; DBUG_VOID_RETURN; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-319'], 'message': 'BUG#25575605: SETTING --SSL-MODE=REQUIRED SENDS CREDENTIALS BEFORE VERIFYING SSL CONNECTION MYSQL_OPT_SSL_MODE option introduced. It is set in case of --ssl-mode=REQUIRED and permits only SSL connection. (cherry picked from commit 3b2d28578c526f347f5cfe763681eff365731f99)'</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 struct ucounts *get_ucounts(struct user_namespace *ns, kuid_t uid) { struct hlist_head *hashent = ucounts_hashentry(ns, uid); struct ucounts *ucounts, *new; spin_lock_irq(&ucounts_lock); ucounts = find_ucounts(ns, uid, hashent); if (!ucounts) { spin_unlock_irq(&ucounts_lock); new = kzalloc(sizeof(*new), GFP_KERNEL); if (!new) return NULL; new->ns = ns; new->uid = uid; atomic_set(&new->count, 0); spin_lock_irq(&ucounts_lock); ucounts = find_ucounts(ns, uid, hashent); if (ucounts) { kfree(new); } else { hlist_add_head(&new->node, hashent); ucounts = new; } } if (!atomic_add_unless(&ucounts->count, 1, INT_MAX)) ucounts = NULL; spin_unlock_irq(&ucounts_lock); return ucounts; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-362'], 'message': 'ucount: Remove the atomicity from ucount->count Always increment/decrement ucount->count under the ucounts_lock. The increments are there already and moving the decrements there means the locking logic of the code is simpler. This simplification in the locking logic fixes a race between put_ucounts and get_ucounts that could result in a use-after-free because the count could go zero then be found by get_ucounts and then be freed by put_ucounts. A bug presumably this one was found by a combination of syzkaller and KASAN. JongWhan Kim reported the syzkaller failure and Dmitry Vyukov spotted the race in the code. Cc: [email protected] Fixes: f6b2db1a3e8d ("userns: Make the count of user namespaces per user") Reported-by: JongHwan Kim <[email protected]> Reported-by: Dmitry Vyukov <[email protected]> Reviewed-by: Andrei Vagin <[email protected]> Signed-off-by: "Eric W. Biederman" <[email protected]>'</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 CL_Init( void ) { Com_Printf( "----- Client Initialization -----\n" ); Con_Init (); if(!com_fullyInitialized) { CL_ClearState(); clc.state = CA_DISCONNECTED; // no longer CA_UNINITIALIZED cl_oldGameSet = qfalse; } cls.realtime = 0; CL_InitInput (); // // register our variables // cl_noprint = Cvar_Get( "cl_noprint", "0", 0 ); #ifdef UPDATE_SERVER_NAME cl_motd = Cvar_Get ("cl_motd", "1", 0); #endif cl_timeout = Cvar_Get ("cl_timeout", "200", 0); cl_timeNudge = Cvar_Get ("cl_timeNudge", "0", CVAR_TEMP ); cl_shownet = Cvar_Get ("cl_shownet", "0", CVAR_TEMP ); cl_showSend = Cvar_Get ("cl_showSend", "0", CVAR_TEMP ); cl_showTimeDelta = Cvar_Get ("cl_showTimeDelta", "0", CVAR_TEMP ); cl_freezeDemo = Cvar_Get ("cl_freezeDemo", "0", CVAR_TEMP ); rcon_client_password = Cvar_Get ("rconPassword", "", CVAR_TEMP ); cl_activeAction = Cvar_Get( "activeAction", "", CVAR_TEMP ); cl_timedemo = Cvar_Get ("timedemo", "0", 0); cl_timedemoLog = Cvar_Get ("cl_timedemoLog", "", CVAR_ARCHIVE); cl_autoRecordDemo = Cvar_Get ("cl_autoRecordDemo", "0", CVAR_ARCHIVE); cl_aviFrameRate = Cvar_Get ("cl_aviFrameRate", "25", CVAR_ARCHIVE); cl_aviMotionJpeg = Cvar_Get ("cl_aviMotionJpeg", "1", CVAR_ARCHIVE); cl_forceavidemo = Cvar_Get ("cl_forceavidemo", "0", 0); rconAddress = Cvar_Get ("rconAddress", "", 0); cl_yawspeed = Cvar_Get ("cl_yawspeed", "140", CVAR_ARCHIVE); cl_pitchspeed = Cvar_Get ("cl_pitchspeed", "140", CVAR_ARCHIVE); cl_anglespeedkey = Cvar_Get ("cl_anglespeedkey", "1.5", 0); cl_maxpackets = Cvar_Get ("cl_maxpackets", "30", CVAR_ARCHIVE ); cl_packetdup = Cvar_Get ("cl_packetdup", "1", CVAR_ARCHIVE ); cl_run = Cvar_Get ("cl_run", "1", CVAR_ARCHIVE); cl_sensitivity = Cvar_Get ("sensitivity", "5", CVAR_ARCHIVE); cl_mouseAccel = Cvar_Get ("cl_mouseAccel", "0", CVAR_ARCHIVE); cl_freelook = Cvar_Get( "cl_freelook", "1", CVAR_ARCHIVE ); // 0: legacy mouse acceleration // 1: new implementation cl_mouseAccelStyle = Cvar_Get( "cl_mouseAccelStyle", "0", CVAR_ARCHIVE ); // offset for the power function (for style 1, ignored otherwise) // this should be set to the max rate value cl_mouseAccelOffset = Cvar_Get( "cl_mouseAccelOffset", "5", CVAR_ARCHIVE ); Cvar_CheckRange(cl_mouseAccelOffset, 0.001f, 50000.0f, qfalse); cl_showMouseRate = Cvar_Get ("cl_showmouserate", "0", 0); cl_allowDownload = Cvar_Get ("cl_allowDownload", "0", CVAR_ARCHIVE); #ifdef USE_CURL_DLOPEN cl_cURLLib = Cvar_Get("cl_cURLLib", DEFAULT_CURL_LIB, CVAR_ARCHIVE); #endif cl_conXOffset = Cvar_Get ("cl_conXOffset", "0", 0); #ifdef __APPLE__ // In game video is REALLY slow in Mac OS X right now due to driver slowness cl_inGameVideo = Cvar_Get ("r_inGameVideo", "0", CVAR_ARCHIVE); #else cl_inGameVideo = Cvar_Get ("r_inGameVideo", "1", CVAR_ARCHIVE); #endif cl_serverStatusResendTime = Cvar_Get ("cl_serverStatusResendTime", "750", 0); // init autoswitch so the ui will have it correctly even // if the cgame hasn't been started Cvar_Get ("cg_autoswitch", "1", CVAR_ARCHIVE); m_pitch = Cvar_Get ("m_pitch", "0.022", CVAR_ARCHIVE); m_yaw = Cvar_Get ("m_yaw", "0.022", CVAR_ARCHIVE); m_forward = Cvar_Get ("m_forward", "0.25", CVAR_ARCHIVE); m_side = Cvar_Get ("m_side", "0.25", CVAR_ARCHIVE); #ifdef __APPLE__ // Input is jittery on OS X w/o this m_filter = Cvar_Get ("m_filter", "1", CVAR_ARCHIVE); #else m_filter = Cvar_Get ("m_filter", "0", CVAR_ARCHIVE); #endif j_pitch = Cvar_Get ("j_pitch", "0.022", CVAR_ARCHIVE); j_yaw = Cvar_Get ("j_yaw", "-0.022", CVAR_ARCHIVE); j_forward = Cvar_Get ("j_forward", "-0.25", CVAR_ARCHIVE); j_side = Cvar_Get ("j_side", "0.25", CVAR_ARCHIVE); j_up = Cvar_Get ("j_up", "0", CVAR_ARCHIVE); j_pitch_axis = Cvar_Get ("j_pitch_axis", "3", CVAR_ARCHIVE); j_yaw_axis = Cvar_Get ("j_yaw_axis", "2", CVAR_ARCHIVE); j_forward_axis = Cvar_Get ("j_forward_axis", "1", CVAR_ARCHIVE); j_side_axis = Cvar_Get ("j_side_axis", "0", CVAR_ARCHIVE); j_up_axis = Cvar_Get ("j_up_axis", "4", CVAR_ARCHIVE); Cvar_CheckRange(j_pitch_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_yaw_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_forward_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_side_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); Cvar_CheckRange(j_up_axis, 0, MAX_JOYSTICK_AXIS-1, qtrue); cl_motdString = Cvar_Get( "cl_motdString", "", CVAR_ROM ); Cvar_Get( "cl_maxPing", "800", CVAR_ARCHIVE ); cl_lanForcePackets = Cvar_Get ("cl_lanForcePackets", "1", CVAR_ARCHIVE); cl_guidServerUniq = Cvar_Get ("cl_guidServerUniq", "1", CVAR_ARCHIVE); // ~ and `, as keys and characters cl_consoleKeys = Cvar_Get( "cl_consoleKeys", "~ ` 0x7e 0x60", CVAR_ARCHIVE); // userinfo Cvar_Get ("name", "UnnamedPlayer", CVAR_USERINFO | CVAR_ARCHIVE ); cl_rate = Cvar_Get ("rate", "25000", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("snaps", "20", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("model", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("headmodel", "sarge", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_model", "james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("team_headmodel", "*james", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("g_redTeam", "Stroggs", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("g_blueTeam", "Pagans", CVAR_SERVERINFO | CVAR_ARCHIVE); Cvar_Get ("color1", "4", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("color2", "5", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("handicap", "100", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("teamtask", "0", CVAR_USERINFO ); Cvar_Get ("sex", "male", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("cl_anonymous", "0", CVAR_USERINFO | CVAR_ARCHIVE ); Cvar_Get ("password", "", CVAR_USERINFO); Cvar_Get ("cg_predictItems", "1", CVAR_USERINFO | CVAR_ARCHIVE ); #ifdef USE_MUMBLE cl_useMumble = Cvar_Get ("cl_useMumble", "0", CVAR_ARCHIVE | CVAR_LATCH); cl_mumbleScale = Cvar_Get ("cl_mumbleScale", "0.0254", CVAR_ARCHIVE); #endif #ifdef USE_VOIP cl_voipSend = Cvar_Get ("cl_voipSend", "0", 0); cl_voipSendTarget = Cvar_Get ("cl_voipSendTarget", "spatial", 0); cl_voipGainDuringCapture = Cvar_Get ("cl_voipGainDuringCapture", "0.2", CVAR_ARCHIVE); cl_voipCaptureMult = Cvar_Get ("cl_voipCaptureMult", "2.0", CVAR_ARCHIVE); cl_voipUseVAD = Cvar_Get ("cl_voipUseVAD", "0", CVAR_ARCHIVE); cl_voipVADThreshold = Cvar_Get ("cl_voipVADThreshold", "0.25", CVAR_ARCHIVE); cl_voipShowMeter = Cvar_Get ("cl_voipShowMeter", "1", CVAR_ARCHIVE); cl_voip = Cvar_Get ("cl_voip", "1", CVAR_ARCHIVE); Cvar_CheckRange( cl_voip, 0, 1, qtrue ); cl_voipProtocol = Cvar_Get ("cl_voipProtocol", cl_voip->integer ? "opus" : "", CVAR_USERINFO | CVAR_ROM); #endif // cgame might not be initialized before menu is used Cvar_Get ("cg_viewsize", "100", CVAR_ARCHIVE ); // Make sure cg_stereoSeparation is zero as that variable is deprecated and should not be used anymore. Cvar_Get ("cg_stereoSeparation", "0", CVAR_ROM); // // register our commands // Cmd_AddCommand ("cmd", CL_ForwardToServer_f); Cmd_AddCommand ("configstrings", CL_Configstrings_f); Cmd_AddCommand ("clientinfo", CL_Clientinfo_f); Cmd_AddCommand ("snd_restart", CL_Snd_Restart_f); Cmd_AddCommand ("vid_restart", CL_Vid_Restart_f); Cmd_AddCommand ("disconnect", CL_Disconnect_f); Cmd_AddCommand ("record", CL_Record_f); Cmd_AddCommand ("demo", CL_PlayDemo_f); Cmd_SetCommandCompletionFunc( "demo", CL_CompleteDemoName ); Cmd_AddCommand ("cinematic", CL_PlayCinematic_f); Cmd_AddCommand ("stoprecord", CL_StopRecord_f); Cmd_AddCommand ("connect", CL_Connect_f); Cmd_AddCommand ("reconnect", CL_Reconnect_f); Cmd_AddCommand ("localservers", CL_LocalServers_f); Cmd_AddCommand ("globalservers", CL_GlobalServers_f); Cmd_AddCommand ("rcon", CL_Rcon_f); Cmd_SetCommandCompletionFunc( "rcon", CL_CompleteRcon ); Cmd_AddCommand ("ping", CL_Ping_f ); Cmd_AddCommand ("serverstatus", CL_ServerStatus_f ); Cmd_AddCommand ("showip", CL_ShowIP_f ); Cmd_AddCommand ("fs_openedList", CL_OpenedPK3List_f ); Cmd_AddCommand ("fs_referencedList", CL_ReferencedPK3List_f ); Cmd_AddCommand ("model", CL_SetModel_f ); Cmd_AddCommand ("video", CL_Video_f ); Cmd_AddCommand ("stopvideo", CL_StopVideo_f ); if( !com_dedicated->integer ) { Cmd_AddCommand ("sayto", CL_Sayto_f ); Cmd_SetCommandCompletionFunc( "sayto", CL_CompletePlayerName ); } CL_InitRef(); SCR_Init (); // Cbuf_Execute (); Cvar_Set( "cl_running", "1" ); CL_GenerateQKey(); Cvar_Get( "cl_guid", "", CVAR_USERINFO | CVAR_ROM ); CL_UpdateGUID( NULL, 0 ); Com_Printf( "----- Client Initialization Complete -----\n" ); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'Don't load .pk3s as .dlls, and don't load user config files from .pk3s.'</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 *Sys_LoadDll(const char *name, qboolean useSystemLib) { void *dllhandle; if(useSystemLib) Com_Printf("Trying to load \"%s\"...\n", name); if(!useSystemLib || !(dllhandle = Sys_LoadLibrary(name))) { const char *topDir; char libPath[MAX_OSPATH]; topDir = Sys_BinaryPath(); if(!*topDir) topDir = "."; Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, topDir); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", topDir, PATH_SEP, name); if(!(dllhandle = Sys_LoadLibrary(libPath))) { const char *basePath = Cvar_VariableString("fs_basepath"); if(!basePath || !*basePath) basePath = "."; if(FS_FilenameCompare(topDir, basePath)) { Com_Printf("Trying to load \"%s\" from \"%s\"...\n", name, basePath); Com_sprintf(libPath, sizeof(libPath), "%s%c%s", basePath, PATH_SEP, name); dllhandle = Sys_LoadLibrary(libPath); } if(!dllhandle) Com_Printf("Loading \"%s\" failed\n", name); } } return dllhandle; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-269'], 'message': 'Don't load .pk3s as .dlls, and don't load user config files from .pk3s.'</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 plist_t parse_string_node(const char **bnode, uint64_t size) { plist_data_t data = plist_new_plist_data(); data->type = PLIST_STRING; data->strval = (char *) malloc(sizeof(char) * (size + 1)); memcpy(data->strval, *bnode, size); data->strval[size] = '\0'; data->length = strlen(data->strval); return node_create(NULL, data); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'bplist: Make sure to bail out if malloc() fails in parse_string_node() Credit to Wang Junjie <[email protected]> (#93)'</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: MagickExport MagickBooleanType IsOptionMember(const char *option, const char *options) { char **option_list, *string; int number_options; MagickBooleanType member; register ssize_t i; /* Is option a member of the options list? */ if (options == (const char *) NULL) return(MagickFalse); string=ConstantString(options); (void) SubstituteString(&string,","," "); option_list=StringToArgv(string,&number_options); string=DestroyString(string); if (option_list == (char **) NULL) return(MagickFalse); member=MagickFalse; for (i=1; i < (ssize_t) number_options; i++) { if ((*option_list[i] == '!') && (LocaleCompare(option,option_list[i]+1) == 0)) break; if (GlobExpression(option,option_list[i],MagickTrue) != MagickFalse) { member=MagickTrue; break; } option_list[i]=DestroyString(option_list[i]); } for ( ; i < (ssize_t) number_options; i++) option_list[i]=DestroyString(option_list[i]); option_list=(char **) RelinquishMagickMemory(option_list); return(member); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399'], 'message': 'Fixed memory leak in IsOptionMember.'</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 jpc_tsfb_synthesize(jpc_tsfb_t *tsfb, jas_seq2d_t *a) { return (tsfb->numlvls > 0) ? jpc_tsfb_synthesize2(tsfb, jas_seq2d_getref(a, jas_seq2d_xstart(a), jas_seq2d_ystart(a)), jas_seq2d_xstart(a), jas_seq2d_ystart(a), jas_seq2d_width(a), jas_seq2d_height(a), jas_seq2d_rowstep(a), tsfb->numlvls - 1) : 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed an integral type promotion problem by adding a JAS_CAST. Modified the jpc_tsfb_synthesize function so that it will be a noop for an empty sequence (in order to avoid dereferencing a null pointer).'</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 jp2_box_put(jp2_box_t *box, jas_stream_t *out) { jas_stream_t *tmpstream; bool extlen; bool dataflag; tmpstream = 0; dataflag = !(box->info->flags & (JP2_BOX_SUPER | JP2_BOX_NODATA)); if (dataflag) { if (!(tmpstream = jas_stream_memopen(0, 0))) { goto error; } if (box->ops->putdata) { if ((*box->ops->putdata)(box, tmpstream)) { goto error; } } box->len = jas_stream_tell(tmpstream) + JP2_BOX_HDRLEN(false); jas_stream_rewind(tmpstream); } extlen = (box->len >= (((uint_fast64_t)1) << 32)) != 0; if (jp2_putuint32(out, extlen ? 1 : box->len)) { goto error; } if (jp2_putuint32(out, box->type)) { goto error; } if (extlen) { if (jp2_putuint64(out, box->len)) { goto error; } } if (dataflag) { if (jas_stream_copy(out, tmpstream, box->len - JP2_BOX_HDRLEN(false))) { goto error; } jas_stream_close(tmpstream); } return 0; error: if (tmpstream) { jas_stream_close(tmpstream); } return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems.'</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: jp2_box_t *jp2_box_create(int type) { jp2_box_t *box; jp2_boxinfo_t *boxinfo; if (!(box = jas_malloc(sizeof(jp2_box_t)))) { return 0; } memset(box, 0, sizeof(jp2_box_t)); box->type = type; box->len = 0; if (!(boxinfo = jp2_boxinfolookup(type))) { return 0; } box->info = boxinfo; box->ops = &boxinfo->ops; return box; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems.'</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 jp2_cdef_getdata(jp2_box_t *box, jas_stream_t *in) { jp2_cdef_t *cdef = &box->data.cdef; jp2_cdefchan_t *chan; unsigned int channo; if (jp2_getuint16(in, &cdef->numchans)) { return -1; } if (!(cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t)))) { return -1; } for (channo = 0; channo < cdef->numchans; ++channo) { chan = &cdef->ents[channo]; if (jp2_getuint16(in, &chan->channo) || jp2_getuint16(in, &chan->type) || jp2_getuint16(in, &chan->assoc)) { return -1; } } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems.'</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 jp2_pclr_putdata(jp2_box_t *box, jas_stream_t *out) { #if 0 jp2_pclr_t *pclr = &box->data.pclr; #endif /* Eliminate warning about unused variable. */ box = 0; out = 0; return -1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Fixed bugs due to uninitialized data in the JP2 decoder. Also, added some comments marking I/O stream interfaces that probably need to be changed (in the long term) to fix integer overflow problems.'</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 jpc_pi_nextcprl(register jpc_pi_t *pi) { int rlvlno; jpc_pirlvl_t *pirlvl; jpc_pchg_t *pchg; int prchind; int prcvind; int *prclyrno; uint_fast32_t trx0; uint_fast32_t try0; uint_fast32_t r; uint_fast32_t rpx; uint_fast32_t rpy; pchg = pi->pchg; if (!pi->prgvolfirst) { goto skip; } else { pi->prgvolfirst = 0; } for (pi->compno = pchg->compnostart, pi->picomp = &pi->picomps[pi->compno]; pi->compno < JAS_CAST(int, pchg->compnoend) && pi->compno < pi->numcomps; ++pi->compno, ++pi->picomp) { pirlvl = pi->picomp->pirlvls; pi->xstep = pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - 1)); pi->ystep = pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn + pi->picomp->numrlvls - 1)); for (rlvlno = 1, pirlvl = &pi->picomp->pirlvls[1]; rlvlno < pi->picomp->numrlvls; ++rlvlno, ++pirlvl) { pi->xstep = JAS_MIN(pi->xstep, pi->picomp->hsamp * (1 << (pirlvl->prcwidthexpn + pi->picomp->numrlvls - rlvlno - 1))); pi->ystep = JAS_MIN(pi->ystep, pi->picomp->vsamp * (1 << (pirlvl->prcheightexpn + pi->picomp->numrlvls - rlvlno - 1))); } for (pi->y = pi->ystart; pi->y < pi->yend; pi->y += pi->ystep - (pi->y % pi->ystep)) { for (pi->x = pi->xstart; pi->x < pi->xend; pi->x += pi->xstep - (pi->x % pi->xstep)) { for (pi->rlvlno = pchg->rlvlnostart, pi->pirlvl = &pi->picomp->pirlvls[pi->rlvlno]; pi->rlvlno < pi->picomp->numrlvls && pi->rlvlno < pchg->rlvlnoend; ++pi->rlvlno, ++pi->pirlvl) { if (pi->pirlvl->numprcs == 0) { continue; } r = pi->picomp->numrlvls - 1 - pi->rlvlno; trx0 = JPC_CEILDIV(pi->xstart, pi->picomp->hsamp << r); try0 = JPC_CEILDIV(pi->ystart, pi->picomp->vsamp << r); rpx = r + pi->pirlvl->prcwidthexpn; rpy = r + pi->pirlvl->prcheightexpn; if (((pi->x == pi->xstart && ((trx0 << r) % (1 << rpx))) || !(pi->x % (pi->picomp->hsamp << rpx))) && ((pi->y == pi->ystart && ((try0 << r) % (1 << rpy))) || !(pi->y % (pi->picomp->vsamp << rpy)))) { prchind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->x, pi->picomp->hsamp << r), pi->pirlvl->prcwidthexpn) - JPC_FLOORDIVPOW2(trx0, pi->pirlvl->prcwidthexpn); prcvind = JPC_FLOORDIVPOW2(JPC_CEILDIV(pi->y, pi->picomp->vsamp << r), pi->pirlvl->prcheightexpn) - JPC_FLOORDIVPOW2(try0, pi->pirlvl->prcheightexpn); pi->prcno = prcvind * pi->pirlvl->numhprcs + prchind; assert(pi->prcno < pi->pirlvl->numprcs); for (pi->lyrno = 0; pi->lyrno < pi->numlyrs && pi->lyrno < JAS_CAST(int, pchg->lyrnoend); ++pi->lyrno) { prclyrno = &pi->pirlvl->prclyrnos[pi->prcno]; if (pi->lyrno >= *prclyrno) { ++(*prclyrno); return 0; } skip: ; } } } } } } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-190'], 'message': 'Fixed an integer overflow problem in the JPC codec that later resulted in the use of uninitialized data.'</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 xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; int ulen; if (!replay_esn || !rp) return 0; up = nla_data(rp); ulen = xfrm_replay_state_esn_len(up); if (nla_len(rp) < ulen || xfrm_replay_state_esn_len(replay_esn) != ulen) return -EINVAL; if (up->replay_window > up->bmp_len * sizeof(__u32) * 8) return -EINVAL; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284'], 'message': 'xfrm_user: validate XFRM_MSG_NEWAE incoming ESN size harder Kees Cook has pointed out that xfrm_replay_state_esn_len() is subject to wrapping issues. To ensure we are correctly ensuring that the two ESN structures are the same size compare both the overall size as reported by xfrm_replay_state_esn_len() and the internal length are the same. CVE-2017-7184 Signed-off-by: Andy Whitcroft <[email protected]> Acked-by: Steffen Klassert <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</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 read_image_tga( gdIOCtx *ctx, oTga *tga ) { int pixel_block_size = (tga->bits / 8); int image_block_size = (tga->width * tga->height) * pixel_block_size; int* decompression_buffer = NULL; unsigned char* conversion_buffer = NULL; int buffer_caret = 0; int bitmap_caret = 0; int i = 0; int encoded_pixels; int rle_size; if(overflow2(tga->width, tga->height)) { return -1; } if(overflow2(tga->width * tga->height, pixel_block_size)) { return -1; } if(overflow2(image_block_size, sizeof(int))) { return -1; } /*! \todo Add more image type support. */ if (tga->imagetype != TGA_TYPE_RGB && tga->imagetype != TGA_TYPE_RGB_RLE) return -1; /*! \brief Allocate memmory for image block * Allocate a chunk of memory for the image block to be passed into. */ tga->bitmap = (int *) gdMalloc(image_block_size * sizeof(int)); if (tga->bitmap == NULL) return -1; switch (tga->imagetype) { case TGA_TYPE_RGB: /*! \brief Read in uncompressed RGB TGA * Chunk load the pixel data from an uncompressed RGB type TGA. */ conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { return -1; } if (gdGetBuf(conversion_buffer, image_block_size, ctx) != image_block_size) { gd_error("gd-tga: premature end of image data\n"); gdFree(conversion_buffer); return -1; } while (buffer_caret < image_block_size) { tga->bitmap[buffer_caret] = (int) conversion_buffer[buffer_caret]; buffer_caret++; } gdFree(conversion_buffer); break; case TGA_TYPE_RGB_RLE: /*! \brief Read in RLE compressed RGB TGA * Chunk load the pixel data from an RLE compressed RGB type TGA. */ decompression_buffer = (int*) gdMalloc(image_block_size * sizeof(int)); if (decompression_buffer == NULL) { return -1; } conversion_buffer = (unsigned char *) gdMalloc(image_block_size * sizeof(unsigned char)); if (conversion_buffer == NULL) { gd_error("gd-tga: premature end of image data\n"); gdFree( decompression_buffer ); return -1; } rle_size = gdGetBuf(conversion_buffer, image_block_size, ctx); if (rle_size <= 0) { gdFree(conversion_buffer); gdFree(decompression_buffer); return -1; } buffer_caret = 0; while( buffer_caret < rle_size) { decompression_buffer[buffer_caret] = (int)conversion_buffer[buffer_caret]; buffer_caret++; } buffer_caret = 0; while( bitmap_caret < image_block_size ) { if ((decompression_buffer[buffer_caret] & TGA_RLE_FLAG) == TGA_RLE_FLAG) { encoded_pixels = ( ( decompression_buffer[ buffer_caret ] & ~TGA_RLE_FLAG ) + 1 ); buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + pixel_block_size > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } for (i = 0; i < encoded_pixels; i++) { memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, pixel_block_size * sizeof(int)); bitmap_caret += pixel_block_size; } buffer_caret += pixel_block_size; } else { encoded_pixels = decompression_buffer[ buffer_caret ] + 1; buffer_caret++; if ((bitmap_caret + (encoded_pixels * pixel_block_size)) > image_block_size || buffer_caret + (encoded_pixels * pixel_block_size) > rle_size) { gdFree( decompression_buffer ); gdFree( conversion_buffer ); return -1; } memcpy(tga->bitmap + bitmap_caret, decompression_buffer + buffer_caret, encoded_pixels * pixel_block_size * sizeof(int)); bitmap_caret += (encoded_pixels * pixel_block_size); buffer_caret += (encoded_pixels * pixel_block_size); } } gdFree( decompression_buffer ); gdFree( conversion_buffer ); break; } return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'Fix OOB reads of the TGA decompression buffer It is possible to craft TGA files which will overflow the decompression buffer, but not the image's bitmap. Therefore we also have to check for potential decompression buffer overflows. This issue had been reported by Ibrahim El-Sayed to [email protected]; a modified case exposing an off-by-one error of the first patch had been provided by Konrad Beckmann. This commit is an amendment to commit fb0e0cce, so we use CVE-2016-6906 as well.'</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 __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct scm_timestamping tss; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { struct timespec ts; skb_get_timestampns(skb, &ts); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts), &ts); } } memset(&tss, 0, sizeof(tss)); if ((sk->sk_tsflags & SOF_TIMESTAMPING_SOFTWARE) && ktime_to_timespec_cond(skb->tstamp, tss.ts + 0)) empty = 0; if (shhwtstamps && (sk->sk_tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) && ktime_to_timespec_cond(shhwtstamps->hwtstamp, tss.ts + 2)) empty = 0; if (!empty) { put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(tss), &tss); if (skb->len && (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_STATS)) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS, skb->len, skb->data); } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-703', 'CWE-125'], 'message': 'tcp: fix SCM_TIMESTAMPING_OPT_STATS for normal skbs __sock_recv_timestamp can be called for both normal skbs (for receive timestamps) and for skbs on the error queue (for transmit timestamps). Commit 1c885808e456 (tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING) assumes any skb passed to __sock_recv_timestamp are from the error queue, containing OPT_STATS in the content of the skb. This results in accessing invalid memory or generating junk data. To fix this, set skb->pkt_type to PACKET_OUTGOING for packets on the error queue. This is safe because on the receive path on local sockets skb->pkt_type is never set to PACKET_OUTGOING. With that, copy OPT_STATS from a packet, only if its pkt_type is PACKET_OUTGOING. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</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 skb_complete_tx_timestamp(struct sk_buff *skb, struct skb_shared_hwtstamps *hwtstamps) { struct sock *sk = skb->sk; if (!skb_may_tx_timestamp(sk, false)) return; /* Take a reference to prevent skb_orphan() from freeing the socket, * but only if the socket refcount is not zero. */ if (likely(atomic_inc_not_zero(&sk->sk_refcnt))) { *skb_hwtstamps(skb) = *hwtstamps; __skb_complete_tx_timestamp(skb, sk, SCM_TSTAMP_SND); sock_put(sk); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</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 __skb_complete_tx_timestamp(struct sk_buff *skb, struct sock *sk, int tstype) { struct sock_exterr_skb *serr; int err; serr = SKB_EXT_ERR(skb); memset(serr, 0, sizeof(*serr)); serr->ee.ee_errno = ENOMSG; serr->ee.ee_origin = SO_EE_ORIGIN_TIMESTAMPING; serr->ee.ee_info = tstype; if (sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) { serr->ee.ee_data = skb_shinfo(skb)->tskey; if (sk->sk_protocol == IPPROTO_TCP && sk->sk_type == SOCK_STREAM) serr->ee.ee_data -= sk->sk_tskey; } err = sock_queue_err_skb(sk, skb); if (err) kfree_skb(skb); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'tcp: mark skbs with SCM_TIMESTAMPING_OPT_STATS SOF_TIMESTAMPING_OPT_STATS can be enabled and disabled while packets are collected on the error queue. So, checking SOF_TIMESTAMPING_OPT_STATS in sk->sk_tsflags is not enough to safely assume that the skb contains OPT_STATS data. Add a bit in sock_exterr_skb to indicate whether the skb contains opt_stats data. Fixes: 1c885808e456 ("tcp: SOF_TIMESTAMPING_OPT_STATS option for SO_TIMESTAMPING") Reported-by: JongHwan Kim <[email protected]> Signed-off-by: Soheil Hassas Yeganeh <[email protected]> Signed-off-by: Eric Dumazet <[email protected]> Signed-off-by: Willem de Bruijn <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</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 packet_set_ring(struct sock *sk, union tpacket_req_u *req_u, int closing, int tx_ring) { struct pgv *pg_vec = NULL; struct packet_sock *po = pkt_sk(sk); int was_running, order = 0; struct packet_ring_buffer *rb; struct sk_buff_head *rb_queue; __be16 num; int err = -EINVAL; /* Added to avoid minimal code churn */ struct tpacket_req *req = &req_u->req; lock_sock(sk); rb = tx_ring ? &po->tx_ring : &po->rx_ring; rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue; err = -EBUSY; if (!closing) { if (atomic_read(&po->mapped)) goto out; if (packet_read_pending(rb)) goto out; } if (req->tp_block_nr) { /* Sanity tests and some calculations */ err = -EBUSY; if (unlikely(rb->pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V1: po->tp_hdrlen = TPACKET_HDRLEN; break; case TPACKET_V2: po->tp_hdrlen = TPACKET2_HDRLEN; break; case TPACKET_V3: po->tp_hdrlen = TPACKET3_HDRLEN; break; } err = -EINVAL; if (unlikely((int)req->tp_block_size <= 0)) goto out; if (unlikely(!PAGE_ALIGNED(req->tp_block_size))) goto out; if (po->tp_version >= TPACKET_V3 && req->tp_block_size <= BLK_PLUS_PRIV((u64)req_u->req3.tp_sizeof_priv)) goto out; if (unlikely(req->tp_frame_size < po->tp_hdrlen + po->tp_reserve)) goto out; if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1))) goto out; rb->frames_per_block = req->tp_block_size / req->tp_frame_size; if (unlikely(rb->frames_per_block == 0)) goto out; if (unlikely((rb->frames_per_block * req->tp_block_nr) != req->tp_frame_nr)) goto out; err = -ENOMEM; order = get_order(req->tp_block_size); pg_vec = alloc_pg_vec(req, order); if (unlikely(!pg_vec)) goto out; switch (po->tp_version) { case TPACKET_V3: /* Block transmit is not supported yet */ if (!tx_ring) { init_prb_bdqc(po, rb, pg_vec, req_u); } else { struct tpacket_req3 *req3 = &req_u->req3; if (req3->tp_retire_blk_tov || req3->tp_sizeof_priv || req3->tp_feature_req_word) { err = -EINVAL; goto out; } } break; default: break; } } /* Done */ else { err = -EINVAL; if (unlikely(req->tp_frame_nr)) goto out; } /* Detach socket from network */ spin_lock(&po->bind_lock); was_running = po->running; num = po->num; if (was_running) { po->num = 0; __unregister_prot_hook(sk, false); } spin_unlock(&po->bind_lock); synchronize_net(); err = -EBUSY; mutex_lock(&po->pg_vec_lock); if (closing || atomic_read(&po->mapped) == 0) { err = 0; spin_lock_bh(&rb_queue->lock); swap(rb->pg_vec, pg_vec); rb->frame_max = (req->tp_frame_nr - 1); rb->head = 0; rb->frame_size = req->tp_frame_size; spin_unlock_bh(&rb_queue->lock); swap(rb->pg_vec_order, order); swap(rb->pg_vec_len, req->tp_block_nr); rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE; po->prot_hook.func = (po->rx_ring.pg_vec) ? tpacket_rcv : packet_rcv; skb_queue_purge(rb_queue); if (atomic_read(&po->mapped)) pr_err("packet_mmap: vma is busy: %d\n", atomic_read(&po->mapped)); } mutex_unlock(&po->pg_vec_lock); spin_lock(&po->bind_lock); if (was_running) { po->num = num; register_prot_hook(sk); } spin_unlock(&po->bind_lock); if (closing && (po->tp_version > TPACKET_V2)) { /* Because we don't support block-based V3 on tx-ring */ if (!tx_ring) prb_shutdown_retire_blk_timer(po, rb_queue); } if (pg_vec) free_pg_vec(pg_vec, order, req->tp_block_nr); out: release_sock(sk); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'net/packet: fix overflow in check for tp_frame_nr When calculating rb->frames_per_block * req->tp_block_nr the result can overflow. Add a check that tp_block_size * tp_block_nr <= UINT_MAX. Since frames_per_block <= tp_block_size, the expression would never overflow. Signed-off-by: Andrey Konovalov <[email protected]> Acked-by: Eric Dumazet <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</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 vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_gb_surface_create_arg *arg = (union drm_vmw_gb_surface_create_arg *)data; struct drm_vmw_gb_surface_create_req *req = &arg->req; struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; uint32_t size; uint32_t backup_handle; if (req->multisample_count != 0) return -EINVAL; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; size = vmw_user_surface_size + 128; /* Define a surface based on the parameters. */ ret = vmw_surface_gb_priv_define(dev, size, req->svga3d_flags, req->format, req->drm_surface_flags & drm_vmw_surface_flag_scanout, req->mip_levels, req->multisample_count, req->array_size, req->base_size, &srf); if (unlikely(ret != 0)) return ret; user_srf = container_of(srf, struct vmw_user_surface, srf); if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; res = &user_srf->srf.res; if (req->buffer_handle != SVGA3D_INVALID_ID) { ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, &res->backup, &user_srf->backup_base); if (ret == 0 && res->backup->base.num_pages * PAGE_SIZE < res->backup_size) { DRM_ERROR("Surface backup buffer is too small.\n"); vmw_dmabuf_unreference(&res->backup); ret = -EINVAL; goto out_unlock; } } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, req->drm_surface_flags & drm_vmw_surface_flag_shareable, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } tmp = vmw_resource_reference(res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->drm_surface_flags & drm_vmw_surface_flag_shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->handle = user_srf->prime.base.hash.key; rep->backup_size = res->backup_size; if (res->backup) { rep->buffer_map_handle = drm_vma_node_offset_addr(&res->backup->base.vma_node); rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; rep->buffer_handle = backup_handle; } else { rep->buffer_map_handle = 0; rep->buffer_size = 0; rep->buffer_handle = SVGA3D_INVALID_ID; } vmw_resource_unreference(&res); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20'], 'message': 'drm/vmwgfx: limit the number of mip levels in vmw_gb_surface_define_ioctl() The 'req->mip_levels' parameter in vmw_gb_surface_define_ioctl() is a user-controlled 'uint32_t' value which is used as a loop count limit. This can lead to a kernel lockup and DoS. Add check for 'req->mip_levels'. References: https://bugzilla.redhat.com/show_bug.cgi?id=1437431 Cc: <[email protected]> Signed-off-by: Vladis Dronov <[email protected]> Reviewed-by: Sinclair Yeh <[email protected]>'</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 char *parse_ip_address_ex(const char *str, size_t str_len, int *portno, int get_err, zend_string **err) { char *colon; char *host = NULL; #ifdef HAVE_IPV6 char *p; if (*(str) == '[' && str_len > 1) { /* IPV6 notation to specify raw address with port (i.e. [fe80::1]:80) */ p = memchr(str + 1, ']', str_len - 2); if (!p || *(p + 1) != ':') { if (get_err) { *err = strpprintf(0, "Failed to parse IPv6 address \"%s\"", str); } return NULL; } *portno = atoi(p + 2); return estrndup(str + 1, p - str - 1); } #endif if (str_len) { colon = memchr(str, ':', str_len - 1); } else { colon = NULL; } if (colon) { *portno = atoi(colon + 1); host = estrndup(str, colon - str); } else { if (get_err) { *err = strpprintf(0, "Failed to parse address \"%s\"", str); } return NULL; } return host; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-20', 'CWE-918'], 'message': 'Detect invalid port in xp_socket parse ip address For historical reasons, fsockopen() accepts the port and hostname separately: fsockopen('127.0.0.1', 80) However, with the introdcution of stream transports in PHP 4.3, it became possible to include the port in the hostname specifier: fsockopen('127.0.0.1:80') Or more formally: fsockopen('tcp://127.0.0.1:80') Confusing results when these two forms are combined, however. fsockopen('127.0.0.1:80', 443) results in fsockopen() attempting to connect to '127.0.0.1:80:443' which any reasonable stack would consider invalid. Unfortunately, PHP parses the address looking for the first colon (with special handling for IPv6, don't worry) and calls atoi() from there. atoi() in turn, simply stops parsing at the first non-numeric character and returns the value so far. The end result is that the explicitly supplied port is treated as ignored garbage, rather than producing an error. This diff replaces atoi() with strtol() and inspects the stop character. If additional "garbage" of any kind is found, it fails and returns an error.'</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 fscrypt_setup_filename(struct inode *dir, const struct qstr *iname, int lookup, struct fscrypt_name *fname) { int ret = 0, bigname = 0; memset(fname, 0, sizeof(struct fscrypt_name)); fname->usr_fname = iname; if (!dir->i_sb->s_cop->is_encrypted(dir) || fscrypt_is_dot_dotdot(iname)) { fname->disk_name.name = (unsigned char *)iname->name; fname->disk_name.len = iname->len; return 0; } ret = fscrypt_get_crypt_info(dir); if (ret && ret != -EOPNOTSUPP) return ret; if (dir->i_crypt_info) { ret = fscrypt_fname_alloc_buffer(dir, iname->len, &fname->crypto_buf); if (ret) return ret; ret = fname_encrypt(dir, iname, &fname->crypto_buf); if (ret) goto errout; fname->disk_name.name = fname->crypto_buf.name; fname->disk_name.len = fname->crypto_buf.len; return 0; } if (!lookup) return -ENOKEY; /* * We don't have the key and we are doing a lookup; decode the * user-supplied name */ if (iname->name[0] == '_') bigname = 1; if ((bigname && (iname->len != 33)) || (!bigname && (iname->len > 43))) return -ENOENT; fname->crypto_buf.name = kmalloc(32, GFP_KERNEL); if (fname->crypto_buf.name == NULL) return -ENOMEM; ret = digest_decode(iname->name + bigname, iname->len - bigname, fname->crypto_buf.name); if (ret < 0) { ret = -ENOENT; goto errout; } fname->crypto_buf.len = ret; if (bigname) { memcpy(&fname->hash, fname->crypto_buf.name, 4); memcpy(&fname->minor_hash, fname->crypto_buf.name + 4, 4); } else { fname->disk_name.name = fname->crypto_buf.name; fname->disk_name.len = fname->crypto_buf.len; } return 0; errout: fscrypt_fname_free_buffer(&fname->crypto_buf); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-476'], 'message': 'fscrypt: remove broken support for detecting keyring key revocation Filesystem encryption ostensibly supported revoking a keyring key that had been used to "unlock" encrypted files, causing those files to become "locked" again. This was, however, buggy for several reasons, the most severe of which was that when key revocation happened to be detected for an inode, its fscrypt_info was immediately freed, even while other threads could be using it for encryption or decryption concurrently. This could be exploited to crash the kernel or worse. This patch fixes the use-after-free by removing the code which detects the keyring key having been revoked, invalidated, or expired. Instead, an encrypted inode that is "unlocked" now simply remains unlocked until it is evicted from memory. Note that this is no worse than the case for block device-level encryption, e.g. dm-crypt, and it still remains possible for a privileged user to evict unused pages, inodes, and dentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by simply unmounting the filesystem. In fact, one of those actions was already needed anyway for key revocation to work even somewhat sanely. This change is not expected to break any applications. In the future I'd like to implement a real API for fscrypt key revocation that interacts sanely with ongoing filesystem operations --- waiting for existing operations to complete and blocking new operations, and invalidating and sanitizing key material and plaintext from the VFS caches. But this is a hard problem, and for now this bug must be fixed. This bug affected almost all versions of ext4, f2fs, and ubifs encryption, and it was potentially reachable in any kernel configured with encryption support (CONFIG_EXT4_ENCRYPTION=y, CONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or CONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the shared fs/crypto/ code, but due to the potential security implications of this bug, it may still be worthwhile to backport this fix to them. Fixes: b7236e21d55f ("ext4 crypto: reorganize how we store keys in the inode") Cc: [email protected] # v4.2+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Acked-by: Michael Halcrow <[email protected]>'</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 fscrypt_get_encryption_info(struct inode *inode) { struct fscrypt_info *ci = inode->i_crypt_info; if (!ci || (ci->ci_keyring_key && (ci->ci_keyring_key->flags & ((1 << KEY_FLAG_INVALIDATED) | (1 << KEY_FLAG_REVOKED) | (1 << KEY_FLAG_DEAD))))) return fscrypt_get_crypt_info(inode); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-476'], 'message': 'fscrypt: remove broken support for detecting keyring key revocation Filesystem encryption ostensibly supported revoking a keyring key that had been used to "unlock" encrypted files, causing those files to become "locked" again. This was, however, buggy for several reasons, the most severe of which was that when key revocation happened to be detected for an inode, its fscrypt_info was immediately freed, even while other threads could be using it for encryption or decryption concurrently. This could be exploited to crash the kernel or worse. This patch fixes the use-after-free by removing the code which detects the keyring key having been revoked, invalidated, or expired. Instead, an encrypted inode that is "unlocked" now simply remains unlocked until it is evicted from memory. Note that this is no worse than the case for block device-level encryption, e.g. dm-crypt, and it still remains possible for a privileged user to evict unused pages, inodes, and dentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by simply unmounting the filesystem. In fact, one of those actions was already needed anyway for key revocation to work even somewhat sanely. This change is not expected to break any applications. In the future I'd like to implement a real API for fscrypt key revocation that interacts sanely with ongoing filesystem operations --- waiting for existing operations to complete and blocking new operations, and invalidating and sanitizing key material and plaintext from the VFS caches. But this is a hard problem, and for now this bug must be fixed. This bug affected almost all versions of ext4, f2fs, and ubifs encryption, and it was potentially reachable in any kernel configured with encryption support (CONFIG_EXT4_ENCRYPTION=y, CONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or CONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the shared fs/crypto/ code, but due to the potential security implications of this bug, it may still be worthwhile to backport this fix to them. Fixes: b7236e21d55f ("ext4 crypto: reorganize how we store keys in the inode") Cc: [email protected] # v4.2+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Acked-by: Michael Halcrow <[email protected]>'</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 validate_user_key(struct fscrypt_info *crypt_info, struct fscrypt_context *ctx, u8 *raw_key, const char *prefix) { char *description; struct key *keyring_key; struct fscrypt_key *master_key; const struct user_key_payload *ukp; int res; description = kasprintf(GFP_NOFS, "%s%*phN", prefix, FS_KEY_DESCRIPTOR_SIZE, ctx->master_key_descriptor); if (!description) return -ENOMEM; keyring_key = request_key(&key_type_logon, description, NULL); kfree(description); if (IS_ERR(keyring_key)) return PTR_ERR(keyring_key); if (keyring_key->type != &key_type_logon) { printk_once(KERN_WARNING "%s: key type must be logon\n", __func__); res = -ENOKEY; goto out; } down_read(&keyring_key->sem); ukp = user_key_payload(keyring_key); if (ukp->datalen != sizeof(struct fscrypt_key)) { res = -EINVAL; up_read(&keyring_key->sem); goto out; } master_key = (struct fscrypt_key *)ukp->data; BUILD_BUG_ON(FS_AES_128_ECB_KEY_SIZE != FS_KEY_DERIVATION_NONCE_SIZE); if (master_key->size != FS_AES_256_XTS_KEY_SIZE) { printk_once(KERN_WARNING "%s: key size incorrect: %d\n", __func__, master_key->size); res = -ENOKEY; up_read(&keyring_key->sem); goto out; } res = derive_key_aes(ctx->nonce, master_key->raw, raw_key); up_read(&keyring_key->sem); if (res) goto out; crypt_info->ci_keyring_key = keyring_key; return 0; out: key_put(keyring_key); return res; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-416', 'CWE-476'], 'message': 'fscrypt: remove broken support for detecting keyring key revocation Filesystem encryption ostensibly supported revoking a keyring key that had been used to "unlock" encrypted files, causing those files to become "locked" again. This was, however, buggy for several reasons, the most severe of which was that when key revocation happened to be detected for an inode, its fscrypt_info was immediately freed, even while other threads could be using it for encryption or decryption concurrently. This could be exploited to crash the kernel or worse. This patch fixes the use-after-free by removing the code which detects the keyring key having been revoked, invalidated, or expired. Instead, an encrypted inode that is "unlocked" now simply remains unlocked until it is evicted from memory. Note that this is no worse than the case for block device-level encryption, e.g. dm-crypt, and it still remains possible for a privileged user to evict unused pages, inodes, and dentries by running 'sync; echo 3 > /proc/sys/vm/drop_caches', or by simply unmounting the filesystem. In fact, one of those actions was already needed anyway for key revocation to work even somewhat sanely. This change is not expected to break any applications. In the future I'd like to implement a real API for fscrypt key revocation that interacts sanely with ongoing filesystem operations --- waiting for existing operations to complete and blocking new operations, and invalidating and sanitizing key material and plaintext from the VFS caches. But this is a hard problem, and for now this bug must be fixed. This bug affected almost all versions of ext4, f2fs, and ubifs encryption, and it was potentially reachable in any kernel configured with encryption support (CONFIG_EXT4_ENCRYPTION=y, CONFIG_EXT4_FS_ENCRYPTION=y, CONFIG_F2FS_FS_ENCRYPTION=y, or CONFIG_UBIFS_FS_ENCRYPTION=y). Note that older kernels did not use the shared fs/crypto/ code, but due to the potential security implications of this bug, it may still be worthwhile to backport this fix to them. Fixes: b7236e21d55f ("ext4 crypto: reorganize how we store keys in the inode") Cc: [email protected] # v4.2+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: Theodore Ts'o <[email protected]> Acked-by: Michael Halcrow <[email protected]>'</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 struct dentry *ecryptfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *raw_data) { struct super_block *s; struct ecryptfs_sb_info *sbi; struct ecryptfs_dentry_info *root_info; const char *err = "Getting sb failed"; struct inode *inode; struct path path; uid_t check_ruid; int rc; sbi = kmem_cache_zalloc(ecryptfs_sb_info_cache, GFP_KERNEL); if (!sbi) { rc = -ENOMEM; goto out; } rc = ecryptfs_parse_options(sbi, raw_data, &check_ruid); if (rc) { err = "Error parsing options"; goto out; } s = sget(fs_type, NULL, set_anon_super, flags, NULL); if (IS_ERR(s)) { rc = PTR_ERR(s); goto out; } rc = bdi_setup_and_register(&sbi->bdi, "ecryptfs", BDI_CAP_MAP_COPY); if (rc) goto out1; ecryptfs_set_superblock_private(s, sbi); s->s_bdi = &sbi->bdi; /* ->kill_sb() will take care of sbi after that point */ sbi = NULL; s->s_op = &ecryptfs_sops; s->s_d_op = &ecryptfs_dops; err = "Reading sb failed"; rc = kern_path(dev_name, LOOKUP_FOLLOW | LOOKUP_DIRECTORY, &path); if (rc) { ecryptfs_printk(KERN_WARNING, "kern_path() failed\n"); goto out1; } if (path.dentry->d_sb->s_type == &ecryptfs_fs_type) { rc = -EINVAL; printk(KERN_ERR "Mount on filesystem of type " "eCryptfs explicitly disallowed due to " "known incompatibilities\n"); goto out_free; } if (check_ruid && !uid_eq(path.dentry->d_inode->i_uid, current_uid())) { rc = -EPERM; printk(KERN_ERR "Mount of device (uid: %d) not owned by " "requested user (uid: %d)\n", i_uid_read(path.dentry->d_inode), from_kuid(&init_user_ns, current_uid())); goto out_free; } ecryptfs_set_superblock_lower(s, path.dentry->d_sb); /** * Set the POSIX ACL flag based on whether they're enabled in the lower * mount. Force a read-only eCryptfs mount if the lower mount is ro. * Allow a ro eCryptfs mount even when the lower mount is rw. */ s->s_flags = flags & ~MS_POSIXACL; s->s_flags |= path.dentry->d_sb->s_flags & (MS_RDONLY | MS_POSIXACL); s->s_maxbytes = path.dentry->d_sb->s_maxbytes; s->s_blocksize = path.dentry->d_sb->s_blocksize; s->s_magic = ECRYPTFS_SUPER_MAGIC; inode = ecryptfs_get_inode(path.dentry->d_inode, s); rc = PTR_ERR(inode); if (IS_ERR(inode)) goto out_free; s->s_root = d_make_root(inode); if (!s->s_root) { rc = -ENOMEM; goto out_free; } rc = -ENOMEM; root_info = kmem_cache_zalloc(ecryptfs_dentry_info_cache, GFP_KERNEL); if (!root_info) goto out_free; /* ->kill_sb() will take care of root_info */ ecryptfs_set_dentry_private(s->s_root, root_info); root_info->lower_path = path; s->s_flags |= MS_ACTIVE; return dget(s->s_root); out_free: path_put(&path); out1: deactivate_locked_super(s); out: if (sbi) { ecryptfs_destroy_mount_crypt_stat(&sbi->mount_crypt_stat); kmem_cache_free(ecryptfs_sb_info_cache, sbi); } printk(KERN_ERR "%s; rc = [%d]\n", err, rc); return ERR_PTR(rc); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'fs: limit filesystem stacking depth Add a simple read-only counter to super_block that indicates how deep this is in the stack of filesystems. Previously ecryptfs was the only stackable filesystem and it explicitly disallowed multiple layers of itself. Overlayfs, however, can be stacked recursively and also may be stacked on top of ecryptfs or vice versa. To limit the kernel stack usage we must limit the depth of the filesystem stack. Initially the limit is set to 2. Signed-off-by: Miklos Szeredi <[email protected]>'</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 get_default_root(pool *p, int allow_symlinks, char **root) { config_rec *c = NULL; char *dir = NULL; int res; c = find_config(main_server->conf, CONF_PARAM, "DefaultRoot", FALSE); while (c) { pr_signals_handle(); /* Check the groups acl */ if (c->argc < 2) { dir = c->argv[0]; break; } res = pr_expr_eval_group_and(((char **) c->argv)+1); if (res) { dir = c->argv[0]; break; } c = find_config_next(c, c->next, CONF_PARAM, "DefaultRoot", FALSE); } if (dir) { char *new_dir; /* Check for any expandable variables. */ new_dir = path_subst_uservar(p, &dir); if (new_dir != NULL) { dir = new_dir; } if (strncmp(dir, "/", 2) == 0) { dir = NULL; } else { char *realdir; int xerrno = 0; if (allow_symlinks == FALSE) { char *path, target_path[PR_TUNABLE_PATH_MAX + 1]; struct stat st; size_t pathlen; /* First, deal with any possible interpolation. dir_realpath() will * do this for us, but dir_realpath() ALSO automatically follows * symlinks, which is what we do NOT want to do here. */ path = dir; if (*path != '/') { if (*path == '~') { if (pr_fs_interpolate(dir, target_path, sizeof(target_path)-1) < 0) { return -1; } path = target_path; } } /* Note: lstat(2) is sensitive to the presence of a trailing slash on * the path, particularly in the case of a symlink to a directory. * Thus to get the correct test, we need to remove any trailing slash * that might be present. Subtle. */ pathlen = strlen(path); if (pathlen > 1 && path[pathlen-1] == '/') { path[pathlen-1] = '\0'; } pr_fs_clear_cache(); res = pr_fsio_lstat(path, &st); if (res < 0) { xerrno = errno; pr_log_pri(PR_LOG_WARNING, "error: unable to check %s: %s", path, strerror(xerrno)); errno = xerrno; return -1; } if (S_ISLNK(st.st_mode)) { pr_log_pri(PR_LOG_WARNING, "error: DefaultRoot %s is a symlink (denied by AllowChrootSymlinks " "config)", path); errno = EPERM; return -1; } } /* We need to be the final user here so that if the user has their home * directory with a mode the user proftpd is running (i.e. the User * directive) as can not traverse down, we can still have the default * root. */ PRIVS_USER realdir = dir_realpath(p, dir); xerrno = errno; PRIVS_RELINQUISH if (realdir) { dir = realdir; } else { /* Try to provide a more informative message. */ char interp_dir[PR_TUNABLE_PATH_MAX + 1]; memset(interp_dir, '\0', sizeof(interp_dir)); (void) pr_fs_interpolate(dir, interp_dir, sizeof(interp_dir)-1); pr_log_pri(PR_LOG_NOTICE, "notice: unable to use DefaultRoot '%s' [resolved to '%s']: %s", dir, interp_dir, strerror(xerrno)); errno = xerrno; } } } *root = dir; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-59', 'CWE-61'], 'message': 'Backporting recursive handling of DefaultRoot path, when AllowChrootSymlinks is off, to 1.3.5 branch.'</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 udpv6_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct inet_sock *inet = inet_sk(sk); struct sk_buff *skb; unsigned int ulen, copied; int peeked, off = 0; int err; int is_udplite = IS_UDPLITE(sk); int is_udp4; bool slow; if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len, addr_len); if (np->rxpmtu && np->rxopt.bits.rxpmtu) return ipv6_recv_rxpmtu(sk, msg, len, addr_len); try_again: skb = __skb_recv_datagram(sk, flags | (noblock ? MSG_DONTWAIT : 0), &peeked, &off, &err); if (!skb) goto out; ulen = skb->len - sizeof(struct udphdr); copied = len; if (copied > ulen) copied = ulen; else if (copied < ulen) msg->msg_flags |= MSG_TRUNC; is_udp4 = (skb->protocol == htons(ETH_P_IP)); /* * If checksum is needed at all, try to do it while copying the * data. If the data is truncated, or if we only want a partial * coverage checksum (UDP-Lite), do it before the copy. */ if (copied < ulen || UDP_SKB_CB(skb)->partial_cov) { if (udp_lib_checksum_complete(skb)) goto csum_copy_err; } if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_msg(skb, sizeof(struct udphdr), msg, copied); else { err = skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); if (err == -EINVAL) goto csum_copy_err; } if (unlikely(err)) { trace_kfree_skb(skb, udpv6_recvmsg); if (!peeked) { atomic_inc(&sk->sk_drops); if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } goto out_free; } if (!peeked) { if (is_udp4) UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); else UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INDATAGRAMS, is_udplite); } sock_recv_ts_and_drops(msg, sk, skb); /* Copy the address. */ if (msg->msg_name) { DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name); sin6->sin6_family = AF_INET6; sin6->sin6_port = udp_hdr(skb)->source; sin6->sin6_flowinfo = 0; if (is_udp4) { ipv6_addr_set_v4mapped(ip_hdr(skb)->saddr, &sin6->sin6_addr); sin6->sin6_scope_id = 0; } else { sin6->sin6_addr = ipv6_hdr(skb)->saddr; sin6->sin6_scope_id = ipv6_iface_scope_id(&sin6->sin6_addr, inet6_iif(skb)); } *addr_len = sizeof(*sin6); } if (np->rxopt.all) ip6_datagram_recv_common_ctl(sk, msg, skb); if (is_udp4) { if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); } else { if (np->rxopt.all) ip6_datagram_recv_specific_ctl(sk, msg, skb); } err = copied; if (flags & MSG_TRUNC) err = ulen; out_free: skb_free_datagram_locked(sk, skb); out: return err; csum_copy_err: slow = lock_sock_fast(sk); if (!skb_kill_datagram(sk, skb, flags)) { if (is_udp4) { UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } else { UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_CSUMERRORS, is_udplite); UDP6_INC_STATS_USER(sock_net(sk), UDP_MIB_INERRORS, is_udplite); } } unlock_sock_fast(sk, slow); /* starting over for a new packet, but check if we need to yield */ cond_resched(); msg->msg_flags &= ~MSG_TRUNC; goto try_again; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-358'], 'message': 'udp: properly support MSG_PEEK with truncated buffers Backport of this upstream commit into stable kernels : 89c22d8c3b27 ("net: Fix skb csum races when peeking") exposed a bug in udp stack vs MSG_PEEK support, when user provides a buffer smaller than skb payload. In this case, skb_copy_and_csum_datagram_iovec(skb, sizeof(struct udphdr), msg->msg_iov); returns -EFAULT. This bug does not happen in upstream kernels since Al Viro did a great job to replace this into : skb_copy_and_csum_datagram_msg(skb, sizeof(struct udphdr), msg); This variant is safe vs short buffers. For the time being, instead reverting Herbert Xu patch and add back skb->ip_summed invalid changes, simply store the result of udp_lib_checksum_complete() so that we avoid computing the checksum a second time, and avoid the problematic skb_copy_and_csum_datagram_iovec() call. This patch can be applied on recent kernels as it avoids a double checksumming, then backported to stable kernels as a bug fix. Signed-off-by: Eric Dumazet <[email protected]> Acked-by: Herbert Xu <[email protected]> Signed-off-by: David S. Miller <[email protected]>'</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 fscrypt_process_policy(struct inode *inode, const struct fscrypt_policy *policy) { if (policy->version != 0) return -EINVAL; if (!inode_has_encryption_context(inode)) { if (!inode->i_sb->s_cop->empty_dir) return -EOPNOTSUPP; if (!inode->i_sb->s_cop->empty_dir(inode)) return -ENOTEMPTY; return create_encryption_context_from_policy(inode, policy); } if (is_encryption_context_consistent_with_policy(inode, policy)) return 0; printk(KERN_WARNING "%s: Policy inconsistent with encryption context\n", __func__); return -EINVAL; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-284', 'CWE-264'], 'message': 'fscrypto: add authorization check for setting encryption policy On an ext4 or f2fs filesystem with file encryption supported, a user could set an encryption policy on any empty directory(*) to which they had readonly access. This is obviously problematic, since such a directory might be owned by another user and the new encryption policy would prevent that other user from creating files in their own directory (for example). Fix this by requiring inode_owner_or_capable() permission to set an encryption policy. This means that either the caller must own the file, or the caller must have the capability CAP_FOWNER. (*) Or also on any regular file, for f2fs v4.6 and later and ext4 v4.8-rc1 and later; a separate bug fix is coming for that. Signed-off-by: Eric Biggers <[email protected]> Cc: [email protected] # 4.1+; check fs/{ext4,f2fs} Signed-off-by: Theodore Ts'o <[email protected]>'</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 re_yyget_lineno (yyscan_t yyscanner) { struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; if (! YY_CURRENT_BUFFER) return 0; return yylineno; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-703', 'CWE-125'], 'message': 're_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c'</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: while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { yy_cp = yyg->yy_c_buf_p; /* Support of yytext. */ *yy_cp = yyg->yy_hold_char; /* yy_bp points to the position in yy_ch_buf of the start of * the current run. */ yy_bp = yy_cp; yy_current_state = yyg->yy_start; yy_match: do { YY_CHAR yy_c = yy_ec[YY_SC_TO_UI(*yy_cp)] ; if ( yy_accept[yy_current_state] ) { yyg->yy_last_accepting_state = yy_current_state; yyg->yy_last_accepting_cpos = yy_cp; } while ( yy_chk[yy_base[yy_current_state] + yy_c] != yy_current_state ) { yy_current_state = (int) yy_def[yy_current_state]; if ( yy_current_state >= 45 ) yy_c = yy_meta[(unsigned int) yy_c]; } yy_current_state = yy_nxt[yy_base[yy_current_state] + (unsigned int) yy_c]; ++yy_cp; } while ( yy_current_state != 44 ); yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; yy_find_action: yy_act = yy_accept[yy_current_state]; YY_DO_BEFORE_ACTION; if ( yy_act != YY_END_OF_BUFFER && yy_rule_can_match_eol[yy_act] ) { yy_size_t yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; } do_action: /* This label is used only to access EOF actions. */ switch ( yy_act ) { /* beginning of action switch */ case 0: /* must back up */ /* undo the effects of YY_DO_BEFORE_ACTION */ *yy_cp = yyg->yy_hold_char; yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; case 1: YY_RULE_SETUP #line 101 "re_lexer.l" { // Examples: {3,8} {0,5} {,5} {7,} int hi_bound; int lo_bound = atoi(yytext + 1); char* comma = strchr(yytext, ','); if (comma - yytext == strlen(yytext) - 2) // if comma is followed by the closing curly bracket // (example: {2,}) set high bound value to maximum. hi_bound = INT16_MAX; else hi_bound = atoi(comma + 1); if (hi_bound > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } if (hi_bound < lo_bound || hi_bound < 0 || lo_bound < 0) { yyerror(yyscanner, lex_env, "bad repeat interval"); yyterminate(); } yylval->range = (hi_bound << 16) | lo_bound; return _RANGE_; } YY_BREAK case 2: YY_RULE_SETUP #line 135 "re_lexer.l" { // Example: {10} int value = atoi(yytext + 1); if (value > INT16_MAX) { yyerror(yyscanner, lex_env, "repeat interval too large"); yyterminate(); } yylval->range = (value << 16) | value; return _RANGE_; } YY_BREAK case 3: YY_RULE_SETUP #line 153 "re_lexer.l" { // Start of a negated character class. Example: [^abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; } YY_BREAK case 4: YY_RULE_SETUP #line 162 "re_lexer.l" { // Start of character negated class containing a ]. // Example: [^]abc] this must be interpreted as a class // not matching ], a, b, nor c BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = TRUE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 5: YY_RULE_SETUP #line 175 "re_lexer.l" { // Start of character class containing a ]. // Example: []abc] this must be interpreted as a class // matching ], a, b, or c. BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; LEX_ENV->class_vector[']' / 8] |= 1 << ']' % 8; } YY_BREAK case 6: YY_RULE_SETUP #line 188 "re_lexer.l" { // Start of character class. Example: [abcd] BEGIN(char_class); memset(LEX_ENV->class_vector, 0, 32); LEX_ENV->negated_class = FALSE; } YY_BREAK case 7: /* rule 7 can match eol */ YY_RULE_SETUP #line 198 "re_lexer.l" { // Any non-special character is passed as a CHAR token to the scanner. yylval->integer = yytext[0]; return _CHAR_; } YY_BREAK case 8: YY_RULE_SETUP #line 207 "re_lexer.l" { return _WORD_CHAR_; } YY_BREAK case 9: YY_RULE_SETUP #line 212 "re_lexer.l" { return _NON_WORD_CHAR_; } YY_BREAK case 10: YY_RULE_SETUP #line 217 "re_lexer.l" { return _SPACE_; } YY_BREAK case 11: YY_RULE_SETUP #line 222 "re_lexer.l" { return _NON_SPACE_; } YY_BREAK case 12: YY_RULE_SETUP #line 227 "re_lexer.l" { return _DIGIT_; } YY_BREAK case 13: YY_RULE_SETUP #line 232 "re_lexer.l" { return _NON_DIGIT_; } YY_BREAK case 14: YY_RULE_SETUP #line 237 "re_lexer.l" { return _WORD_BOUNDARY_; } YY_BREAK case 15: YY_RULE_SETUP #line 241 "re_lexer.l" { return _NON_WORD_BOUNDARY_; } YY_BREAK case 16: YY_RULE_SETUP #line 246 "re_lexer.l" { yyerror(yyscanner, lex_env, "backreferences are not allowed"); yyterminate(); } YY_BREAK case 17: YY_RULE_SETUP #line 253 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { yylval->integer = c; return _CHAR_; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 18: YY_RULE_SETUP #line 270 "re_lexer.l" { // End of character class. int i; yylval->class_vector = (uint8_t*) yr_malloc(32); memcpy(yylval->class_vector, LEX_ENV->class_vector, 32); if (LEX_ENV->negated_class) { for(i = 0; i < 32; i++) yylval->class_vector[i] = ~yylval->class_vector[i]; } BEGIN(INITIAL); return _CLASS_; } YY_BREAK case 19: /* rule 19 can match eol */ YY_RULE_SETUP #line 291 "re_lexer.l" { // A range inside a character class. // [abc0-9] // ^- matching here uint16_t c; uint8_t start = yytext[0]; uint8_t end = yytext[2]; if (start == '\\') { start = escaped_char_value(yytext); if (yytext[1] == 'x') end = yytext[5]; else end = yytext[3]; } if (end == '\\') { if (!read_escaped_char(yyscanner, &end)) { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } if (end < start) { yyerror(yyscanner, lex_env, "bad character range"); yyterminate(); } for (c = start; c <= end; c++) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } } YY_BREAK case 20: YY_RULE_SETUP #line 333 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= word_chars[i]; } YY_BREAK case 21: YY_RULE_SETUP #line 342 "re_lexer.l" { int i; for (i = 0; i < 32; i++) LEX_ENV->class_vector[i] |= ~word_chars[i]; } YY_BREAK case 22: YY_RULE_SETUP #line 351 "re_lexer.l" { LEX_ENV->class_vector[' ' / 8] |= 1 << ' ' % 8; LEX_ENV->class_vector['\t' / 8] |= 1 << '\t' % 8; } YY_BREAK case 23: YY_RULE_SETUP #line 358 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { if (i == ' ' / 8) LEX_ENV->class_vector[i] |= ~(1 << ' ' % 8); else if (i == '\t' / 8) LEX_ENV->class_vector[i] |= ~(1 << '\t' % 8); else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 24: YY_RULE_SETUP #line 374 "re_lexer.l" { char c; for (c = '0'; c <= '9'; c++) LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } YY_BREAK case 25: YY_RULE_SETUP #line 383 "re_lexer.l" { int i; for (i = 0; i < 32; i++) { // digits 0-7 are in the sixth byte of the vector, let that byte alone if (i == 6) continue; // digits 8 and 9 are the lowest two bits in the seventh byte of the // vector, let those bits alone. if (i == 7) LEX_ENV->class_vector[i] |= 0xFC; else LEX_ENV->class_vector[i] = 0xFF; } } YY_BREAK case 26: YY_RULE_SETUP #line 403 "re_lexer.l" { uint8_t c; if (read_escaped_char(yyscanner, &c)) { LEX_ENV->class_vector[c / 8] |= 1 << c % 8; } else { yyerror(yyscanner, lex_env, "unexpected end of buffer"); yyterminate(); } } YY_BREAK case 27: YY_RULE_SETUP #line 419 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { // A character class (i.e: [0-9a-f]) is represented by a 256-bits vector, // here we set to 1 the vector's bit corresponding to the input character. LEX_ENV->class_vector[yytext[0] / 8] |= 1 << yytext[0] % 8; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(char_class): #line 436 "re_lexer.l" { // End of regexp reached while scanning a character class. yyerror(yyscanner, lex_env, "missing terminating ] for character class"); yyterminate(); } YY_BREAK case 28: YY_RULE_SETUP #line 445 "re_lexer.l" { if (yytext[0] >= 32 && yytext[0] < 127) { return yytext[0]; } else { yyerror(yyscanner, lex_env, "non-ascii character"); yyterminate(); } } YY_BREAK case YY_STATE_EOF(INITIAL): #line 459 "re_lexer.l" { yyterminate(); } YY_BREAK case 29: YY_RULE_SETUP #line 464 "re_lexer.l" ECHO; YY_BREAK #line 1358 "re_lexer.c" case YY_END_OF_BUFFER: { /* Amount of text matched not including the EOB char. */ int yy_amount_of_matched_text = (int) (yy_cp - yyg->yytext_ptr) - 1; /* Undo the effects of YY_DO_BEFORE_ACTION. */ *yy_cp = yyg->yy_hold_char; YY_RESTORE_YY_MORE_OFFSET if ( YY_CURRENT_BUFFER_LVALUE->yy_buffer_status == YY_BUFFER_NEW ) { /* We're scanning a new file or input source. It's * possible that this happened because the user * just pointed yyin at a new source and called * re_yylex(). If so, then we have to assure * consistency between YY_CURRENT_BUFFER and our * globals. Here is the right place to do so, because * this is the first action (other than possibly a * back-up) that will match for the new input source. */ yyg->yy_n_chars = YY_CURRENT_BUFFER_LVALUE->yy_n_chars; YY_CURRENT_BUFFER_LVALUE->yy_input_file = yyin; YY_CURRENT_BUFFER_LVALUE->yy_buffer_status = YY_BUFFER_NORMAL; } /* Note that here we test for yy_c_buf_p "<=" to the position * of the first EOB in the buffer, since yy_c_buf_p will * already have been incremented past the NUL character * (since all states make transitions on EOB to the * end-of-buffer state). Contrast this with the test * in input(). */ if ( yyg->yy_c_buf_p <= &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) { /* This was really a NUL. */ yy_state_type yy_next_state; yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); /* Okay, we're now positioned to make the NUL * transition. We couldn't have * yy_get_previous_state() go ahead and do it * for us because it doesn't know how to deal * with the possibility of jamming (and we don't * want to build jamming into it because then it * will run more slowly). */ yy_next_state = yy_try_NUL_trans( yy_current_state , yyscanner); yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; if ( yy_next_state ) { /* Consume the NUL. */ yy_cp = ++yyg->yy_c_buf_p; yy_current_state = yy_next_state; goto yy_match; } else { yy_cp = yyg->yy_last_accepting_cpos; yy_current_state = yyg->yy_last_accepting_state; goto yy_find_action; } } else switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_END_OF_FILE: { yyg->yy_did_buffer_switch_on_eof = 0; if ( re_yywrap(yyscanner ) ) { /* Note: because we've taken care in * yy_get_next_buffer() to have set up * yytext, we can now set up * yy_c_buf_p so that if some total * hoser (like flex itself) wants to * call the scanner after we return the * YY_NULL, it'll still work - another * YY_NULL will get returned. */ yyg->yy_c_buf_p = yyg->yytext_ptr + YY_MORE_ADJ; yy_act = YY_STATE_EOF(YY_START); goto do_action; } else { if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; } break; } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + yy_amount_of_matched_text; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_match; case EOB_ACT_LAST_MATCH: yyg->yy_c_buf_p = &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars]; yy_current_state = yy_get_previous_state( yyscanner ); yy_cp = yyg->yy_c_buf_p; yy_bp = yyg->yytext_ptr + YY_MORE_ADJ; goto yy_find_action; } break; } default: YY_FATAL_ERROR( "fatal flex scanner internal error--no action found" ); } /* end of action switch */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-703', 'CWE-125'], 'message': 're_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c'</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: #else static int input (yyscan_t yyscanner) #endif { int c; struct yyguts_t * yyg = (struct yyguts_t*)yyscanner; *yyg->yy_c_buf_p = yyg->yy_hold_char; if ( *yyg->yy_c_buf_p == YY_END_OF_BUFFER_CHAR ) { /* yy_c_buf_p now points to the character we want to return. * If this occurs *before* the EOB characters, then it's a * valid NUL; if not, then we've hit the end of the buffer. */ if ( yyg->yy_c_buf_p < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[yyg->yy_n_chars] ) /* This was really a NUL. */ *yyg->yy_c_buf_p = '\0'; else { /* need more input */ yy_size_t offset = yyg->yy_c_buf_p - yyg->yytext_ptr; ++yyg->yy_c_buf_p; switch ( yy_get_next_buffer( yyscanner ) ) { case EOB_ACT_LAST_MATCH: /* This happens because yy_g_n_b() * sees that we've accumulated a * token and flags that we need to * try matching the token before * proceeding. But for input(), * there's no matching to consider. * So convert the EOB_ACT_LAST_MATCH * to EOB_ACT_END_OF_FILE. */ /* Reset buffer status. */ re_yyrestart(yyin ,yyscanner); /*FALLTHROUGH*/ case EOB_ACT_END_OF_FILE: { if ( re_yywrap(yyscanner ) ) return EOF; if ( ! yyg->yy_did_buffer_switch_on_eof ) YY_NEW_FILE; #ifdef __cplusplus return yyinput(yyscanner); #else return input(yyscanner); #endif } case EOB_ACT_CONTINUE_SCAN: yyg->yy_c_buf_p = yyg->yytext_ptr + offset; break; } } } c = *(unsigned char *) yyg->yy_c_buf_p; /* cast for 8-bit char's */ *yyg->yy_c_buf_p = '\0'; /* preserve yytext */ yyg->yy_hold_char = *++yyg->yy_c_buf_p; if ( c == '\n' ) do{ yylineno++; yycolumn=0; }while(0) ; return c; ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-703', 'CWE-125'], 'message': 're_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c'</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 re_yylex_init_extra(YY_EXTRA_TYPE yy_user_defined,yyscan_t* ptr_yy_globals ) { struct yyguts_t dummy_yyguts; re_yyset_extra (yy_user_defined, &dummy_yyguts); if (ptr_yy_globals == NULL){ errno = EINVAL; return 1; } *ptr_yy_globals = (yyscan_t) re_yyalloc ( sizeof( struct yyguts_t ), &dummy_yyguts ); if (*ptr_yy_globals == NULL){ errno = ENOMEM; return 1; } /* By setting to 0xAA, we expose bugs in yy_init_globals. Leave at 0x00 for releases. */ memset(*ptr_yy_globals,0x00,sizeof(struct yyguts_t)); re_yyset_extra (yy_user_defined, *ptr_yy_globals); return yy_init_globals ( *ptr_yy_globals ); ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476', 'CWE-703', 'CWE-125'], 'message': 're_lexer: Make reading escape sequences more robust (#586) * Add test for issue #503 * re_lexer: Make reading escape sequences more robust This commit fixes parsing incomplete escape sequences at the end of a regular expression and parsing things like \xxy (invalid hex digits) which before were silently turned into (char)255. Close #503 * Update re_lexer.c'</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 *yyscanner, YR_COMPILER* compiler) { /* The lookahead symbol. */ int yychar; /* 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); /* 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. 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; 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; #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)) /* 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; yystacksize = YYINITDEPTH; YYDPRINTF ((stderr, "Starting parse\n")); yystate = 0; yyerrstatus = 0; yynerrs = 0; yychar = YYEMPTY; /* Cause a token to be read. */ 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 = yystate; if (yyss + yystacksize - 1 <= yyssp) { /* Get the current used size of the three stacks, in elements. */ YYSIZE_T yysize = 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; /* 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), &yystacksize); yyss = yyss1; yyvs = yyvs1; } #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); # undef YYSTACK_RELOCATE if (yyss1 != yyssa) YYSTACK_FREE (yyss1); } # endif #endif /* no yyoverflow */ yyssp = yyss + yysize - 1; yyvsp = yyvs + yysize - 1; YYDPRINTF ((stderr, "Stack size increased to %lu\n", (unsigned long int) 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, yyscanner, compiler); } 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 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]; YY_REDUCE_PRINT (yyn); switch (yyn) { case 8: #line 230 "grammar.y" /* yacc.c:1646 */ { int result = yr_parser_reduce_import(yyscanner, (yyvsp[0].sized_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF(result != ERROR_SUCCESS); } #line 1661 "grammar.c" /* yacc.c:1646 */ break; case 9: #line 242 "grammar.y" /* yacc.c:1646 */ { YR_RULE* rule = yr_parser_reduce_rule_declaration_phase_1( yyscanner, (int32_t) (yyvsp[-2].integer), (yyvsp[0].c_string)); ERROR_IF(rule == NULL); (yyval.rule) = rule; } #line 1674 "grammar.c" /* yacc.c:1646 */ break; case 10: #line 251 "grammar.y" /* yacc.c:1646 */ { YR_RULE* rule = (yyvsp[-4].rule); // rule created in phase 1 rule->tags = (yyvsp[-3].c_string); rule->metas = (yyvsp[-1].meta); rule->strings = (yyvsp[0].string); } #line 1686 "grammar.c" /* yacc.c:1646 */ break; case 11: #line 259 "grammar.y" /* yacc.c:1646 */ { YR_RULE* rule = (yyvsp[-7].rule); // rule created in phase 1 compiler->last_result = yr_parser_reduce_rule_declaration_phase_2( yyscanner, rule); yr_free((yyvsp[-8].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1701 "grammar.c" /* yacc.c:1646 */ break; case 12: #line 274 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = NULL; } #line 1709 "grammar.c" /* yacc.c:1646 */ break; case 13: #line 278 "grammar.y" /* yacc.c:1646 */ { // Each rule have a list of meta-data info, consisting in a // sequence of YR_META structures. The last YR_META structure does // not represent a real meta-data, it's just a end-of-list marker // identified by a specific type (META_TYPE_NULL). Here we // write the end-of-list marker. YR_META null_meta; memset(&null_meta, 0xFF, sizeof(YR_META)); null_meta.type = META_TYPE_NULL; compiler->last_result = yr_arena_write_data( compiler->metas_arena, &null_meta, sizeof(YR_META), NULL); (yyval.meta) = (yyvsp[0].meta); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 1736 "grammar.c" /* yacc.c:1646 */ break; case 14: #line 305 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = NULL; } #line 1744 "grammar.c" /* yacc.c:1646 */ break; case 15: #line 309 "grammar.y" /* yacc.c:1646 */ { // Each rule have a list of strings, consisting in a sequence // of YR_STRING structures. The last YR_STRING structure does not // represent a real string, it's just a end-of-list marker // identified by a specific flag (STRING_FLAGS_NULL). Here we // write the end-of-list marker. YR_STRING null_string; memset(&null_string, 0xFF, sizeof(YR_STRING)); null_string.g_flags = STRING_GFLAGS_NULL; compiler->last_result = yr_arena_write_data( compiler->strings_arena, &null_string, sizeof(YR_STRING), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.string) = (yyvsp[0].string); } #line 1771 "grammar.c" /* yacc.c:1646 */ break; case 17: #line 340 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = 0; } #line 1777 "grammar.c" /* yacc.c:1646 */ break; case 18: #line 341 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 1783 "grammar.c" /* yacc.c:1646 */ break; case 19: #line 346 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = RULE_GFLAGS_PRIVATE; } #line 1789 "grammar.c" /* yacc.c:1646 */ break; case 20: #line 347 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = RULE_GFLAGS_GLOBAL; } #line 1795 "grammar.c" /* yacc.c:1646 */ break; case 21: #line 353 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = NULL; } #line 1803 "grammar.c" /* yacc.c:1646 */ break; case 22: #line 357 "grammar.y" /* yacc.c:1646 */ { // Tags list is represented in the arena as a sequence // of null-terminated strings, the sequence ends with an // additional null character. Here we write the ending null //character. Example: tag1\0tag2\0tag3\0\0 compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, "", NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[0].c_string); } #line 1821 "grammar.c" /* yacc.c:1646 */ break; case 23: #line 375 "grammar.y" /* yacc.c:1646 */ { char* identifier; compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), &identifier); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = identifier; } #line 1838 "grammar.c" /* yacc.c:1646 */ break; case 24: #line 388 "grammar.y" /* yacc.c:1646 */ { char* tag_name = (yyvsp[-1].c_string); size_t tag_length = tag_name != NULL ? strlen(tag_name) : 0; while (tag_length > 0) { if (strcmp(tag_name, (yyvsp[0].c_string)) == 0) { yr_compiler_set_error_extra_info(compiler, tag_name); compiler->last_result = ERROR_DUPLICATED_TAG_IDENTIFIER; break; } tag_name = (char*) yr_arena_next_address( yyget_extra(yyscanner)->sz_arena, tag_name, tag_length + 1); tag_length = tag_name != NULL ? strlen(tag_name) : 0; } if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( yyget_extra(yyscanner)->sz_arena, (yyvsp[0].c_string), NULL); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-1].c_string); } #line 1874 "grammar.c" /* yacc.c:1646 */ break; case 25: #line 424 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = (yyvsp[0].meta); } #line 1880 "grammar.c" /* yacc.c:1646 */ break; case 26: #line 425 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = (yyvsp[-1].meta); } #line 1886 "grammar.c" /* yacc.c:1646 */ break; case 27: #line 431 "grammar.y" /* yacc.c:1646 */ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_STRING, (yyvsp[-2].c_string), sized_string->c_string, 0); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.meta) == NULL); } #line 1906 "grammar.c" /* yacc.c:1646 */ break; case 28: #line 447 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-2].c_string), NULL, (yyvsp[0].integer)); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1923 "grammar.c" /* yacc.c:1646 */ break; case 29: #line 460 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_INTEGER, (yyvsp[-3].c_string), NULL, -(yyvsp[0].integer)); yr_free((yyvsp[-3].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1940 "grammar.c" /* yacc.c:1646 */ break; case 30: #line 473 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, TRUE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1957 "grammar.c" /* yacc.c:1646 */ break; case 31: #line 486 "grammar.y" /* yacc.c:1646 */ { (yyval.meta) = yr_parser_reduce_meta_declaration( yyscanner, META_TYPE_BOOLEAN, (yyvsp[-2].c_string), NULL, FALSE); yr_free((yyvsp[-2].c_string)); ERROR_IF((yyval.meta) == NULL); } #line 1974 "grammar.c" /* yacc.c:1646 */ break; case 32: #line 502 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = (yyvsp[0].string); } #line 1980 "grammar.c" /* yacc.c:1646 */ break; case 33: #line 503 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = (yyvsp[-1].string); } #line 1986 "grammar.c" /* yacc.c:1646 */ break; case 34: #line 509 "grammar.y" /* yacc.c:1646 */ { compiler->error_line = yyget_lineno(yyscanner); } #line 1994 "grammar.c" /* yacc.c:1646 */ break; case 35: #line 513 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer), (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2009 "grammar.c" /* yacc.c:1646 */ break; case 36: #line 524 "grammar.y" /* yacc.c:1646 */ { compiler->error_line = yyget_lineno(yyscanner); } #line 2017 "grammar.c" /* yacc.c:1646 */ break; case 37: #line 528 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, (int32_t) (yyvsp[0].integer) | STRING_GFLAGS_REGEXP, (yyvsp[-4].c_string), (yyvsp[-1].sized_string)); yr_free((yyvsp[-4].c_string)); yr_free((yyvsp[-1].sized_string)); ERROR_IF((yyval.string) == NULL); compiler->error_line = 0; } #line 2033 "grammar.c" /* yacc.c:1646 */ break; case 38: #line 540 "grammar.y" /* yacc.c:1646 */ { (yyval.string) = yr_parser_reduce_string_declaration( yyscanner, STRING_GFLAGS_HEXADECIMAL, (yyvsp[-2].c_string), (yyvsp[0].sized_string)); yr_free((yyvsp[-2].c_string)); yr_free((yyvsp[0].sized_string)); ERROR_IF((yyval.string) == NULL); } #line 2047 "grammar.c" /* yacc.c:1646 */ break; case 39: #line 553 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = 0; } #line 2053 "grammar.c" /* yacc.c:1646 */ break; case 40: #line 554 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = (yyvsp[-1].integer) | (yyvsp[0].integer); } #line 2059 "grammar.c" /* yacc.c:1646 */ break; case 41: #line 559 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_WIDE; } #line 2065 "grammar.c" /* yacc.c:1646 */ break; case 42: #line 560 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_ASCII; } #line 2071 "grammar.c" /* yacc.c:1646 */ break; case 43: #line 561 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_NO_CASE; } #line 2077 "grammar.c" /* yacc.c:1646 */ break; case 44: #line 562 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = STRING_GFLAGS_FULL_WORD; } #line 2083 "grammar.c" /* yacc.c:1646 */ break; case 45: #line 568 "grammar.y" /* yacc.c:1646 */ { int var_index = yr_parser_lookup_loop_variable(yyscanner, (yyvsp[0].c_string)); if (var_index >= 0) { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, LOOP_LOCAL_VARS * var_index, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = compiler->loop_identifier[var_index]; } else { // Search for identifier within the global namespace, where the // externals variables reside. YR_OBJECT* object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), NULL); if (object == NULL) { // If not found, search within the current namespace. char* ns = compiler->current_namespace->name; object = (YR_OBJECT*) yr_hash_table_lookup( compiler->objects_table, (yyvsp[0].c_string), ns); } if (object != NULL) { char* id; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &id); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_LOAD, id, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = object; (yyval.expression).identifier = object->identifier; } else { YR_RULE* rule = (YR_RULE*) yr_hash_table_lookup( compiler->rules_table, (yyvsp[0].c_string), compiler->current_namespace->name); if (rule != NULL) { compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH_RULE, rule, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; (yyval.expression).identifier = rule->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_UNDEFINED_IDENTIFIER; } } } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2172 "grammar.c" /* yacc.c:1646 */ break; case 46: #line 653 "grammar.y" /* yacc.c:1646 */ { YR_OBJECT* field = NULL; if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-2].expression).value.object->type == OBJECT_TYPE_STRUCTURE) { field = yr_object_lookup_field((yyvsp[-2].expression).value.object, (yyvsp[0].c_string)); if (field != NULL) { char* ident; compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[0].c_string), &ident); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_OBJ_FIELD, ident, NULL, NULL); (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = field; (yyval.expression).identifier = field->identifier; } else { yr_compiler_set_error_extra_info(compiler, (yyvsp[0].c_string)); compiler->last_result = ERROR_INVALID_FIELD_NAME; } } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-2].expression).identifier); compiler->last_result = ERROR_NOT_A_STRUCTURE; } yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2222 "grammar.c" /* yacc.c:1646 */ break; case 47: #line 699 "grammar.y" /* yacc.c:1646 */ { YR_OBJECT_ARRAY* array; YR_OBJECT_DICTIONARY* dict; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_ARRAY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "array indexes must be of integer type"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_INDEX_ARRAY, NULL); array = (YR_OBJECT_ARRAY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = array->prototype_item; (yyval.expression).identifier = array->identifier; } else if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_DICTIONARY) { if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_STRING) { yr_compiler_set_error_extra_info( compiler, "dictionary keys must be of string type"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit( yyscanner, OP_LOOKUP_DICT, NULL); dict = (YR_OBJECT_DICTIONARY*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = dict->prototype_item; (yyval.expression).identifier = dict->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_INDEXABLE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2283 "grammar.c" /* yacc.c:1646 */ break; case 48: #line 757 "grammar.y" /* yacc.c:1646 */ { YR_OBJECT_FUNCTION* function; char* args_fmt; if ((yyvsp[-3].expression).type == EXPRESSION_TYPE_OBJECT && (yyvsp[-3].expression).value.object->type == OBJECT_TYPE_FUNCTION) { compiler->last_result = yr_parser_check_types( compiler, (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object, (yyvsp[-1].c_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_arena_write_string( compiler->sz_arena, (yyvsp[-1].c_string), &args_fmt); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_CALL, args_fmt, NULL, NULL); function = (YR_OBJECT_FUNCTION*) (yyvsp[-3].expression).value.object; (yyval.expression).type = EXPRESSION_TYPE_OBJECT; (yyval.expression).value.object = function->return_obj; (yyval.expression).identifier = function->identifier; } else { yr_compiler_set_error_extra_info( compiler, (yyvsp[-3].expression).identifier); compiler->last_result = ERROR_NOT_A_FUNCTION; } yr_free((yyvsp[-1].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2328 "grammar.c" /* yacc.c:1646 */ break; case 49: #line 801 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = yr_strdup(""); } #line 2334 "grammar.c" /* yacc.c:1646 */ break; case 50: #line 802 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = (yyvsp[0].c_string); } #line 2340 "grammar.c" /* yacc.c:1646 */ break; case 51: #line 807 "grammar.y" /* yacc.c:1646 */ { (yyval.c_string) = (char*) yr_malloc(MAX_FUNCTION_ARGS + 1); switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcpy((yyval.c_string), "i", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcpy((yyval.c_string), "f", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcpy((yyval.c_string), "b", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcpy((yyval.c_string), "s", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcpy((yyval.c_string), "r", MAX_FUNCTION_ARGS); break; } ERROR_IF((yyval.c_string) == NULL); } #line 2369 "grammar.c" /* yacc.c:1646 */ break; case 52: #line 832 "grammar.y" /* yacc.c:1646 */ { if (strlen((yyvsp[-2].c_string)) == MAX_FUNCTION_ARGS) { compiler->last_result = ERROR_TOO_MANY_ARGUMENTS; } else { switch((yyvsp[0].expression).type) { case EXPRESSION_TYPE_INTEGER: strlcat((yyvsp[-2].c_string), "i", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_FLOAT: strlcat((yyvsp[-2].c_string), "f", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_BOOLEAN: strlcat((yyvsp[-2].c_string), "b", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_STRING: strlcat((yyvsp[-2].c_string), "s", MAX_FUNCTION_ARGS); break; case EXPRESSION_TYPE_REGEXP: strlcat((yyvsp[-2].c_string), "r", MAX_FUNCTION_ARGS); break; } } ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.c_string) = (yyvsp[-2].c_string); } #line 2405 "grammar.c" /* yacc.c:1646 */ break; case 53: #line 868 "grammar.y" /* yacc.c:1646 */ { SIZED_STRING* sized_string = (yyvsp[0].sized_string); RE* re; RE_ERROR error; int re_flags = 0; if (sized_string->flags & SIZED_STRING_FLAGS_NO_CASE) re_flags |= RE_FLAGS_NO_CASE; if (sized_string->flags & SIZED_STRING_FLAGS_DOT_ALL) re_flags |= RE_FLAGS_DOT_ALL; compiler->last_result = yr_re_compile( sized_string->c_string, re_flags, compiler->re_code_arena, &re, &error); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_INVALID_REGULAR_EXPRESSION) yr_compiler_set_error_extra_info(compiler, error.message); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, re->root_node->forward_code, NULL, NULL); yr_re_destroy(re); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_REGEXP; } #line 2451 "grammar.c" /* yacc.c:1646 */ break; case 54: #line 914 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_STRING) { if ((yyvsp[0].expression).value.sized_string != NULL) { yywarning(yyscanner, "Using literal string \"%s\" in a boolean operation.", (yyvsp[0].expression).value.sized_string->c_string); } compiler->last_result = yr_parser_emit( yyscanner, OP_STR_TO_BOOL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2474 "grammar.c" /* yacc.c:1646 */ break; case 55: #line 936 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2487 "grammar.c" /* yacc.c:1646 */ break; case 56: #line 945 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 0, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2500 "grammar.c" /* yacc.c:1646 */ break; case 57: #line 954 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "matches"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_REGEXP, "matches"); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit( yyscanner, OP_MATCHES, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2519 "grammar.c" /* yacc.c:1646 */ break; case 58: #line 969 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_STRING, "contains"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_STRING, "contains"); compiler->last_result = yr_parser_emit( yyscanner, OP_CONTAINS, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2535 "grammar.c" /* yacc.c:1646 */ break; case 59: #line 981 "grammar.y" /* yacc.c:1646 */ { int result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_FOUND, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2553 "grammar.c" /* yacc.c:1646 */ break; case 60: #line 995 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "at"); compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_AT, (yyvsp[0].expression).value.integer); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2570 "grammar.c" /* yacc.c:1646 */ break; case 61: #line 1008 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-2].c_string), OP_FOUND_IN, UNDEFINED); yr_free((yyvsp[-2].c_string)); ERROR_IF(compiler->last_result!= ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2585 "grammar.c" /* yacc.c:1646 */ break; case 62: #line 1019 "grammar.y" /* yacc.c:1646 */ { int var_index; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; ERROR_IF(compiler->last_result != ERROR_SUCCESS); var_index = yr_parser_lookup_loop_variable( yyscanner, (yyvsp[-1].c_string)); if (var_index >= 0) { yr_compiler_set_error_extra_info( compiler, (yyvsp[-1].c_string)); compiler->last_result = \ ERROR_DUPLICATED_LOOP_IDENTIFIER; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); // Push end-of-list marker compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 2619 "grammar.c" /* yacc.c:1646 */ break; case 63: #line 1049 "grammar.y" /* yacc.c:1646 */ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; // Clear counter for number of expressions evaluating // to TRUE. yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); // Clear iterations counter yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-1].integer) == INTEGER_SET_ENUMERATION) { // Pop the first integer yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); } else // INTEGER_SET_RANGE { // Pop higher bound of set range yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset + 3, &addr, NULL); // Pop lower bound of set range yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, NULL, NULL); } compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = (yyvsp[-4].c_string); compiler->loop_depth++; } #line 2658 "grammar.c" /* yacc.c:1646 */ break; case 64: #line 1084 "grammar.y" /* yacc.c:1646 */ { int mem_offset; compiler->loop_depth--; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; // The value at the top of the stack is the result of // evaluating the boolean expression, so it could be // 0, 1 or UNDEFINED. Add this value to a counter // keeping the number of expressions evaluating to true. // If the value is UNDEFINED instruction OP_ADD_M // does nothing. yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); // Increment iterations counter yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); if ((yyvsp[-5].integer) == INTEGER_SET_ENUMERATION) { yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); } else // INTEGER_SET_RANGE { // Increment lower bound of integer set yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset, NULL, NULL); // Push lower bound of integer set yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset, NULL, NULL); // Push higher bound of integer set yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 3, NULL, NULL); // Compare higher bound with lower bound, do loop again // if lower bound is still lower or equal than higher bound yr_parser_emit_with_arg_reloc( yyscanner, OP_JLE, compiler->loop_address[compiler->loop_depth], NULL, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); yr_parser_emit(yyscanner, OP_POP, NULL); } // Pop end-of-list marker. yr_parser_emit(yyscanner, OP_POP, NULL); // At this point the loop quantifier (any, all, 1, 2,..) // is at the top of the stack. Check if the quantifier // is undefined (meaning "all") and replace it with the // iterations counter in that case. yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); // Compare the loop quantifier with the number of // expressions evaluating to TRUE. yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); compiler->loop_identifier[compiler->loop_depth] = NULL; yr_free((yyvsp[-8].c_string)); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2741 "grammar.c" /* yacc.c:1646 */ break; case 65: #line 1163 "grammar.y" /* yacc.c:1646 */ { int mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; uint8_t* addr; if (compiler->loop_depth == MAX_LOOP_NESTING) compiler->last_result = \ ERROR_LOOP_NESTING_LIMIT_EXCEEDED; if (compiler->loop_for_of_mem_offset != -1) compiler->last_result = \ ERROR_NESTED_FOR_OF_LOOP; ERROR_IF(compiler->last_result != ERROR_SUCCESS); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 1, NULL, NULL); yr_parser_emit_with_arg( yyscanner, OP_CLEAR_M, mem_offset + 2, NULL, NULL); // Pop the first string. yr_parser_emit_with_arg( yyscanner, OP_POP_M, mem_offset, &addr, NULL); compiler->loop_for_of_mem_offset = mem_offset; compiler->loop_address[compiler->loop_depth] = addr; compiler->loop_identifier[compiler->loop_depth] = NULL; compiler->loop_depth++; } #line 2775 "grammar.c" /* yacc.c:1646 */ break; case 66: #line 1193 "grammar.y" /* yacc.c:1646 */ { int mem_offset; compiler->loop_depth--; compiler->loop_for_of_mem_offset = -1; mem_offset = LOOP_LOCAL_VARS * compiler->loop_depth; // Increment counter by the value returned by the // boolean expression (0 or 1). If the boolean expression // returned UNDEFINED the OP_ADD_M won't do anything. yr_parser_emit_with_arg( yyscanner, OP_ADD_M, mem_offset + 1, NULL, NULL); // Increment iterations counter. yr_parser_emit_with_arg( yyscanner, OP_INCR_M, mem_offset + 2, NULL, NULL); // If next string is not undefined, go back to the // beginning of the loop. yr_parser_emit_with_arg_reloc( yyscanner, OP_JNUNDEF, compiler->loop_address[compiler->loop_depth], NULL, NULL); // Pop end-of-list marker. yr_parser_emit(yyscanner, OP_POP, NULL); // At this point the loop quantifier (any, all, 1, 2,..) // is at top of the stack. Check if the quantifier is // undefined (meaning "all") and replace it with the // iterations counter in that case. yr_parser_emit_with_arg( yyscanner, OP_SWAPUNDEF, mem_offset + 2, NULL, NULL); // Compare the loop quantifier with the number of // expressions evaluating to TRUE. yr_parser_emit_with_arg( yyscanner, OP_PUSH_M, mem_offset + 1, NULL, NULL); yr_parser_emit(yyscanner, OP_INT_LE, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2828 "grammar.c" /* yacc.c:1646 */ break; case 67: #line 1242 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit(yyscanner, OP_OF, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2838 "grammar.c" /* yacc.c:1646 */ break; case 68: #line 1248 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit(yyscanner, OP_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2848 "grammar.c" /* yacc.c:1646 */ break; case 69: #line 1254 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JFALSE, 0, // still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); // create a fixup entry for the jump and push it in the stack fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2878 "grammar.c" /* yacc.c:1646 */ break; case 70: #line 1280 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; uint8_t* and_addr; // Ensure that we have at least two consecutive bytes in the arena's // current page, one for the AND opcode and one for opcode following the // AND. This is necessary because we need to compute the address for the // opcode following the AND, and we don't want the AND in one page and // the following opcode in another page. compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_AND, &and_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); // Now we know the jump destination, which is the address of the // instruction following the AND. Let's fixup the jump address. fixup = compiler->fixup_stack_head; // We know that the AND opcode and the following one are within the same // page, so we can compute the address for the opcode following the AND // by simply adding one to its address. *(void**)(fixup->address) = (void*)(and_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2918 "grammar.c" /* yacc.c:1646 */ break; case 71: #line 1316 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; void* jmp_destination_addr; compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_JTRUE, 0, // still don't know the jump destination NULL, &jmp_destination_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup = (YR_FIXUP*) yr_malloc(sizeof(YR_FIXUP)); if (fixup == NULL) compiler->last_error = ERROR_INSUFFICIENT_MEMORY; ERROR_IF(compiler->last_result != ERROR_SUCCESS); fixup->address = jmp_destination_addr; fixup->next = compiler->fixup_stack_head; compiler->fixup_stack_head = fixup; } #line 2947 "grammar.c" /* yacc.c:1646 */ break; case 72: #line 1341 "grammar.y" /* yacc.c:1646 */ { YR_FIXUP* fixup; uint8_t* or_addr; // Ensure that we have at least two consecutive bytes in the arena's // current page, one for the OR opcode and one for opcode following the // OR. This is necessary because we need to compute the address for the // opcode following the OR, and we don't want the OR in one page and // the following opcode in another page. compiler->last_result = yr_arena_reserve_memory( compiler->code_arena, 2); ERROR_IF(compiler->last_result != ERROR_SUCCESS); compiler->last_result = yr_parser_emit(yyscanner, OP_OR, &or_addr); ERROR_IF(compiler->last_result != ERROR_SUCCESS); // Now we know the jump destination, which is the address of the // instruction following the OP_OR. Let's fixup the jump address. fixup = compiler->fixup_stack_head; // We know that the OR opcode and the following one are within the same // page, so we can compute the address for the opcode following the OR // by simply adding one to its address. *(void**)(fixup->address) = (void*)(or_addr + 1); compiler->fixup_stack_head = fixup->next; yr_free(fixup); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 2987 "grammar.c" /* yacc.c:1646 */ break; case 73: #line 1377 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "<", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3000 "grammar.c" /* yacc.c:1646 */ break; case 74: #line 1386 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, ">", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3013 "grammar.c" /* yacc.c:1646 */ break; case 75: #line 1395 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "<=", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3026 "grammar.c" /* yacc.c:1646 */ break; case 76: #line 1404 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, ">=", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3039 "grammar.c" /* yacc.c:1646 */ break; case 77: #line 1413 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "==", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3052 "grammar.c" /* yacc.c:1646 */ break; case 78: #line 1422 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "!=", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; } #line 3065 "grammar.c" /* yacc.c:1646 */ break; case 79: #line 1431 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[0].expression); } #line 3073 "grammar.c" /* yacc.c:1646 */ break; case 80: #line 1435 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[-1].expression); } #line 3081 "grammar.c" /* yacc.c:1646 */ break; case 81: #line 1442 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = INTEGER_SET_ENUMERATION; } #line 3087 "grammar.c" /* yacc.c:1646 */ break; case 82: #line 1443 "grammar.y" /* yacc.c:1646 */ { (yyval.integer) = INTEGER_SET_RANGE; } #line 3093 "grammar.c" /* yacc.c:1646 */ break; case 83: #line 1449 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[-3].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for range's lower bound"); compiler->last_result = ERROR_WRONG_TYPE; } if ((yyvsp[-1].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for range's upper bound"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3115 "grammar.c" /* yacc.c:1646 */ break; case 84: #line 1471 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for enumeration item"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3131 "grammar.c" /* yacc.c:1646 */ break; case 85: #line 1483 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type != EXPRESSION_TYPE_INTEGER) { yr_compiler_set_error_extra_info( compiler, "wrong type for enumeration item"); compiler->last_result = ERROR_WRONG_TYPE; } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3146 "grammar.c" /* yacc.c:1646 */ break; case 86: #line 1498 "grammar.y" /* yacc.c:1646 */ { // Push end-of-list marker yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3155 "grammar.c" /* yacc.c:1646 */ break; case 88: #line 1504 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); yr_parser_emit_pushes_for_strings(yyscanner, "$*"); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3166 "grammar.c" /* yacc.c:1646 */ break; case 91: #line 1521 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3177 "grammar.c" /* yacc.c:1646 */ break; case 92: #line 1528 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_pushes_for_strings(yyscanner, (yyvsp[0].c_string)); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3188 "grammar.c" /* yacc.c:1646 */ break; case 94: #line 1540 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, UNDEFINED, NULL, NULL); } #line 3196 "grammar.c" /* yacc.c:1646 */ break; case 95: #line 1544 "grammar.y" /* yacc.c:1646 */ { yr_parser_emit_with_arg(yyscanner, OP_PUSH, 1, NULL, NULL); } #line 3204 "grammar.c" /* yacc.c:1646 */ break; case 96: #line 1552 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[-1].expression); } #line 3212 "grammar.c" /* yacc.c:1646 */ break; case 97: #line 1556 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit( yyscanner, OP_FILESIZE, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3226 "grammar.c" /* yacc.c:1646 */ break; case 98: #line 1566 "grammar.y" /* yacc.c:1646 */ { yywarning(yyscanner, "Using deprecated \"entrypoint\" keyword. Use the \"entry_point\" " "function from PE module instead."); compiler->last_result = yr_parser_emit( yyscanner, OP_ENTRYPOINT, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3244 "grammar.c" /* yacc.c:1646 */ break; case 99: #line 1580 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-1].expression), EXPRESSION_TYPE_INTEGER, "intXXXX or uintXXXX"); // _INTEGER_FUNCTION_ could be any of int8, int16, int32, uint8, // uint32, etc. $1 contains an index that added to OP_READ_INT results // in the proper OP_INTXX opcode. compiler->last_result = yr_parser_emit( yyscanner, (uint8_t) (OP_READ_INT + (yyvsp[-3].integer)), NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3264 "grammar.c" /* yacc.c:1646 */ break; case 100: #line 1596 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, (yyvsp[0].integer), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = (yyvsp[0].integer); } #line 3278 "grammar.c" /* yacc.c:1646 */ break; case 101: #line 1606 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg_double( yyscanner, OP_PUSH, (yyvsp[0].double_), NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } #line 3291 "grammar.c" /* yacc.c:1646 */ break; case 102: #line 1615 "grammar.y" /* yacc.c:1646 */ { SIZED_STRING* sized_string; compiler->last_result = yr_arena_write_data( compiler->sz_arena, (yyvsp[0].sized_string), (yyvsp[0].sized_string)->length + sizeof(SIZED_STRING), (void**) &sized_string); yr_free((yyvsp[0].sized_string)); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_emit_with_arg_reloc( yyscanner, OP_PUSH, sized_string, NULL, NULL); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = sized_string; } #line 3320 "grammar.c" /* yacc.c:1646 */ break; case 103: #line 1640 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_COUNT, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3336 "grammar.c" /* yacc.c:1646 */ break; case 104: #line 1652 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3352 "grammar.c" /* yacc.c:1646 */ break; case 105: #line 1664 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_OFFSET, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3372 "grammar.c" /* yacc.c:1646 */ break; case 106: #line 1680 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[-3].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[-3].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3388 "grammar.c" /* yacc.c:1646 */ break; case 107: #line 1692 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_emit_with_arg( yyscanner, OP_PUSH, 1, NULL, NULL); if (compiler->last_result == ERROR_SUCCESS) compiler->last_result = yr_parser_reduce_string_identifier( yyscanner, (yyvsp[0].c_string), OP_LENGTH, UNDEFINED); yr_free((yyvsp[0].c_string)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } #line 3408 "grammar.c" /* yacc.c:1646 */ break; case 108: #line 1708 "grammar.y" /* yacc.c:1646 */ { if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) // loop identifier { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_BOOLEAN) // rule identifier { (yyval.expression).type = EXPRESSION_TYPE_BOOLEAN; (yyval.expression).value.integer = UNDEFINED; } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_OBJECT) { compiler->last_result = yr_parser_emit( yyscanner, OP_OBJ_VALUE, NULL); switch((yyvsp[0].expression).value.object->type) { case OBJECT_TYPE_INTEGER: (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = UNDEFINED; break; case OBJECT_TYPE_FLOAT: (yyval.expression).type = EXPRESSION_TYPE_FLOAT; break; case OBJECT_TYPE_STRING: (yyval.expression).type = EXPRESSION_TYPE_STRING; (yyval.expression).value.sized_string = NULL; break; default: yr_compiler_set_error_extra_info_fmt( compiler, "wrong usage of identifier \"%s\"", (yyvsp[0].expression).identifier); compiler->last_result = ERROR_WRONG_TYPE; } } else { assert(FALSE); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3457 "grammar.c" /* yacc.c:1646 */ break; case 109: #line 1753 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER | EXPRESSION_TYPE_FLOAT, "-"); if ((yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : -((yyvsp[0].expression).value.integer); compiler->last_result = yr_parser_emit(yyscanner, OP_INT_MINUS, NULL); } else if ((yyvsp[0].expression).type == EXPRESSION_TYPE_FLOAT) { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; compiler->last_result = yr_parser_emit(yyscanner, OP_DBL_MINUS, NULL); } ERROR_IF(compiler->last_result != ERROR_SUCCESS); } #line 3480 "grammar.c" /* yacc.c:1646 */ break; case 110: #line 1772 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "+", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(+, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3502 "grammar.c" /* yacc.c:1646 */ break; case 111: #line 1790 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "-", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(-, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3524 "grammar.c" /* yacc.c:1646 */ break; case 112: #line 1808 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "*", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { (yyval.expression).value.integer = OPERATION(*, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3546 "grammar.c" /* yacc.c:1646 */ break; case 113: #line 1826 "grammar.y" /* yacc.c:1646 */ { compiler->last_result = yr_parser_reduce_operation( yyscanner, "\\", (yyvsp[-2].expression), (yyvsp[0].expression)); ERROR_IF(compiler->last_result != ERROR_SUCCESS); if ((yyvsp[-2].expression).type == EXPRESSION_TYPE_INTEGER && (yyvsp[0].expression).type == EXPRESSION_TYPE_INTEGER) { if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(/, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } else { (yyval.expression).type = EXPRESSION_TYPE_FLOAT; } } #line 3576 "grammar.c" /* yacc.c:1646 */ break; case 114: #line 1852 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "%"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "%"); yr_parser_emit(yyscanner, OP_MOD, NULL); if ((yyvsp[0].expression).value.integer != 0) { (yyval.expression).value.integer = OPERATION(%, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; } else { compiler->last_result = ERROR_DIVISION_BY_ZERO; ERROR_IF(compiler->last_result != ERROR_SUCCESS); } } #line 3598 "grammar.c" /* yacc.c:1646 */ break; case 115: #line 1870 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^"); yr_parser_emit(yyscanner, OP_BITWISE_XOR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(^, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3612 "grammar.c" /* yacc.c:1646 */ break; case 116: #line 1880 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "^"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "^"); yr_parser_emit(yyscanner, OP_BITWISE_AND, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(&, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3626 "grammar.c" /* yacc.c:1646 */ break; case 117: #line 1890 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "|"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "|"); yr_parser_emit(yyscanner, OP_BITWISE_OR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(|, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3640 "grammar.c" /* yacc.c:1646 */ break; case 118: #line 1900 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "~"); yr_parser_emit(yyscanner, OP_BITWISE_NOT, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = ((yyvsp[0].expression).value.integer == UNDEFINED) ? UNDEFINED : ~((yyvsp[0].expression).value.integer); } #line 3654 "grammar.c" /* yacc.c:1646 */ break; case 119: #line 1910 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, "<<"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, "<<"); yr_parser_emit(yyscanner, OP_SHL, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(<<, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3668 "grammar.c" /* yacc.c:1646 */ break; case 120: #line 1920 "grammar.y" /* yacc.c:1646 */ { CHECK_TYPE((yyvsp[-2].expression), EXPRESSION_TYPE_INTEGER, ">>"); CHECK_TYPE((yyvsp[0].expression), EXPRESSION_TYPE_INTEGER, ">>"); yr_parser_emit(yyscanner, OP_SHR, NULL); (yyval.expression).type = EXPRESSION_TYPE_INTEGER; (yyval.expression).value.integer = OPERATION(>>, (yyvsp[-2].expression).value.integer, (yyvsp[0].expression).value.integer); } #line 3682 "grammar.c" /* yacc.c:1646 */ break; case 121: #line 1930 "grammar.y" /* yacc.c:1646 */ { (yyval.expression) = (yyvsp[0].expression); } #line 3690 "grammar.c" /* yacc.c:1646 */ break; #line 3694 "grammar.c" /* yacc.c:1646 */ 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; /* 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. */ yyn = yyr1[yyn]; yystate = yypgoto[yyn - YYNTOKENS] + *yyssp; if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp) yystate = yytable[yystate]; else yystate = yydefgoto[yyn - YYNTOKENS]; 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 (yyscanner, compiler, 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 (yyscanner, compiler, yymsgp); if (yysyntax_error_status == 2) goto yyexhaustedlab; } # undef YYSYNTAX_ERROR #endif } 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, yyscanner, compiler); 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; yydestruct ("Error: popping", yystos[yystate], yyvsp, yyscanner, compiler); YYPOPSTACK (1); yystate = *yyssp; YY_STACK_PRINT (yyss, yyssp); } YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN *++yyvsp = yylval; YY_IGNORE_MAYBE_UNINITIALIZED_END /* 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 (yyscanner, compiler, 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, yyscanner, compiler); } /* 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, yyscanner, compiler); 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-416', 'CWE-125'], 'message': 'Fix issue #575'</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: sf_flac_write_callback (const FLAC__StreamDecoder * UNUSED (decoder), const FLAC__Frame *frame, const int32_t * const buffer [], void *client_data) { SF_PRIVATE *psf = (SF_PRIVATE*) client_data ; FLAC_PRIVATE* pflac = (FLAC_PRIVATE*) psf->codec_data ; pflac->frame = frame ; pflac->bufferpos = 0 ; pflac->bufferbackup = SF_FALSE ; pflac->wbuffer = buffer ; flac_buffer_copy (psf) ; return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE ; } /* sf_flac_write_callback */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-369'], 'message': 'src/flac.c: Improve error handling Especially when dealing with corrupt or malicious files.'</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: id3_skip (SF_PRIVATE * psf) { unsigned char buf [10] ; memset (buf, 0, sizeof (buf)) ; psf_binheader_readf (psf, "pb", 0, buf, 10) ; if (buf [0] == 'I' && buf [1] == 'D' && buf [2] == '3') { int offset = buf [6] & 0x7f ; offset = (offset << 7) | (buf [7] & 0x7f) ; offset = (offset << 7) | (buf [8] & 0x7f) ; offset = (offset << 7) | (buf [9] & 0x7f) ; psf_log_printf (psf, "ID3 length : %d\n--------------------\n", offset) ; /* Never want to jump backwards in a file. */ if (offset < 0) return 0 ; /* Calculate new file offset and position ourselves there. */ psf->fileoffset += offset + 10 ; psf_binheader_readf (psf, "p", psf->fileoffset) ; return 1 ; } ; return 0 ; } /* id3_skip */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/id3.c : Improve error handling'</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: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; } ; } /* header_put_le_8byte */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: header_gets (SF_PRIVATE *psf, char *ptr, int bufsize) { int k ; for (k = 0 ; k < bufsize - 1 ; k++) { if (psf->headindex < psf->headend) { ptr [k] = psf->header [psf->headindex] ; psf->headindex ++ ; } else { psf->headend += psf_fread (psf->header + psf->headend, 1, 1, psf) ; ptr [k] = psf->header [psf->headindex] ; psf->headindex = psf->headend ; } ; if (ptr [k] == '\n') break ; } ; ptr [k] = 0 ; return k ; } /* header_gets */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: header_put_le_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 32) ; psf->header [psf->headindex++] = (x >> 40) ; psf->header [psf->headindex++] = (x >> 48) ; psf->header [psf->headindex++] = (x >> 56) ; } ; } /* header_put_le_8byte */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: header_put_le_short (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 2) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; } ; } /* header_put_le_short */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: sf_open_fd (int fd, int mode, SF_INFO *sfinfo, int close_desc) { SF_PRIVATE *psf ; if ((SF_CONTAINER (sfinfo->format)) == SF_FORMAT_SD2) { sf_errno = SFE_SD2_FD_DISALLOWED ; return NULL ; } ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; copy_filename (psf, "") ; psf->file.mode = mode ; psf_set_file (psf, fd) ; psf->is_pipe = psf_is_pipe (psf) ; psf->fileoffset = psf_ftell (psf) ; if (! close_desc) psf->file.do_not_close_descriptor = SF_TRUE ; return psf_open_file (psf, sfinfo) ; } /* sf_open_fd */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: psf_close (SF_PRIVATE *psf) { uint32_t k ; int error = 0 ; if (psf->codec_close) { error = psf->codec_close (psf) ; /* To prevent it being called in psf->container_close(). */ psf->codec_close = NULL ; } ; if (psf->container_close) error = psf->container_close (psf) ; error = psf_fclose (psf) ; psf_close_rsrc (psf) ; /* For an ISO C compliant implementation it is ok to free a NULL pointer. */ free (psf->container_data) ; free (psf->codec_data) ; free (psf->interleave) ; free (psf->dither) ; free (psf->peak_info) ; free (psf->broadcast_16k) ; free (psf->loop_info) ; free (psf->instrument) ; free (psf->cues) ; free (psf->channel_map) ; free (psf->format_desc) ; free (psf->strings.storage) ; if (psf->wchunks.chunks) for (k = 0 ; k < psf->wchunks.used ; k++) free (psf->wchunks.chunks [k].data) ; free (psf->rchunks.chunks) ; free (psf->wchunks.chunks) ; free (psf->iterator) ; free (psf->cart_16k) ; memset (psf, 0, sizeof (SF_PRIVATE)) ; free (psf) ; return error ; } /* psf_close */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: sf_open_virtual (SF_VIRTUAL_IO *sfvirtual, int mode, SF_INFO *sfinfo, void *user_data) { SF_PRIVATE *psf ; /* Make sure we have a valid set ot virtual pointers. */ if (sfvirtual->get_filelen == NULL || sfvirtual->seek == NULL || sfvirtual->tell == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_get_filelen / vio_seek / vio_tell in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_READ || mode == SFM_RDWR) && sfvirtual->read == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_read in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((mode == SFM_WRITE || mode == SFM_RDWR) && sfvirtual->write == NULL) { sf_errno = SFE_BAD_VIRTUAL_IO ; snprintf (sf_parselog, sizeof (sf_parselog), "Bad vio_write in SF_VIRTUAL_IO struct.\n") ; return NULL ; } ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf->virtual_io = SF_TRUE ; psf->vio = *sfvirtual ; psf->vio_user_data = user_data ; psf->file.mode = mode ; return psf_open_file (psf, sfinfo) ; } /* sf_open_virtual */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: header_put_le_3byte (SF_PRIVATE *psf, int x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 3) { psf->header [psf->headindex++] = x ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = (x >> 16) ; } ; } /* header_put_le_3byte */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: header_put_be_8byte (SF_PRIVATE *psf, sf_count_t x) { if (psf->headindex < SIGNED_SIZEOF (psf->header) - 8) { psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = 0 ; psf->header [psf->headindex++] = (x >> 24) ; psf->header [psf->headindex++] = (x >> 16) ; psf->header [psf->headindex++] = (x >> 8) ; psf->header [psf->headindex++] = x ; } ; } /* header_put_be_8byte */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: psf_binheader_writef (SF_PRIVATE *psf, const char *format, ...) { va_list argptr ; sf_count_t countdata ; unsigned long longdata ; unsigned int data ; float floatdata ; double doubledata ; void *bindata ; size_t size ; char c, *strptr ; int count = 0, trunc_8to4 ; trunc_8to4 = SF_FALSE ; va_start (argptr, format) ; while ((c = *format++)) { switch (c) { case ' ' : /* Do nothing. Just used to space out format string. */ break ; case 'e' : /* All conversions are now from LE to host. */ psf->rwf_endian = SF_ENDIAN_LITTLE ; break ; case 'E' : /* All conversions are now from BE to host. */ psf->rwf_endian = SF_ENDIAN_BIG ; break ; case 't' : /* All 8 byte values now get written as 4 bytes. */ trunc_8to4 = SF_TRUE ; break ; case 'T' : /* All 8 byte values now get written as 8 bytes. */ trunc_8to4 = SF_FALSE ; break ; case 'm' : data = va_arg (argptr, unsigned int) ; header_put_marker (psf, data) ; count += 4 ; break ; case '1' : data = va_arg (argptr, unsigned int) ; header_put_byte (psf, data) ; count += 1 ; break ; case '2' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_short (psf, data) ; } else { header_put_le_short (psf, data) ; } ; count += 2 ; break ; case '3' : /* tribyte */ data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_3byte (psf, data) ; } else { header_put_le_3byte (psf, data) ; } ; count += 3 ; break ; case '4' : data = va_arg (argptr, unsigned int) ; if (psf->rwf_endian == SF_ENDIAN_BIG) { header_put_be_int (psf, data) ; } else { header_put_le_int (psf, data) ; } ; count += 4 ; break ; case '8' : countdata = va_arg (argptr, sf_count_t) ; if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_FALSE) { header_put_be_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_FALSE) { header_put_le_8byte (psf, countdata) ; count += 8 ; } else if (psf->rwf_endian == SF_ENDIAN_BIG && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_be_int (psf, longdata) ; count += 4 ; } else if (psf->rwf_endian == SF_ENDIAN_LITTLE && trunc_8to4 == SF_TRUE) { longdata = countdata & 0xFFFFFFFF ; header_put_le_int (psf, longdata) ; count += 4 ; } break ; case 'f' : /* Floats are passed as doubles. Is this always true? */ floatdata = (float) va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) float32_be_write (floatdata, psf->header + psf->headindex) ; else float32_le_write (floatdata, psf->header + psf->headindex) ; psf->headindex += 4 ; count += 4 ; break ; case 'd' : doubledata = va_arg (argptr, double) ; if (psf->rwf_endian == SF_ENDIAN_BIG) double64_be_write (doubledata, psf->header + psf->headindex) ; else double64_le_write (doubledata, psf->header + psf->headindex) ; psf->headindex += 8 ; count += 8 ; break ; case 's' : /* Write a C string (guaranteed to have a zero terminator). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) + 1 ; size += (size & 1) ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; psf->header [psf->headindex - 1] = 0 ; count += 4 + size ; break ; case 'S' : /* ** Write an AIFF style string (no zero terminator but possibly ** an extra pad byte if the string length is odd). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; if (psf->rwf_endian == SF_ENDIAN_BIG) header_put_be_int (psf, size) ; else header_put_le_int (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size + 1) ; size += (size & 1) ; psf->headindex += size ; psf->header [psf->headindex] = 0 ; count += 4 + size ; break ; case 'p' : /* Write a PASCAL string (as used by AIFF files). */ strptr = va_arg (argptr, char *) ; size = strlen (strptr) ; size = (size & 1) ? size : size + 1 ; size = (size > 254) ? 254 : size ; header_put_byte (psf, size) ; memcpy (&(psf->header [psf->headindex]), strptr, size) ; psf->headindex += size ; count += 1 + size ; break ; case 'b' : bindata = va_arg (argptr, void *) ; size = va_arg (argptr, size_t) ; if (psf->headindex + size < sizeof (psf->header)) { memcpy (&(psf->header [psf->headindex]), bindata, size) ; psf->headindex += size ; count += size ; } ; break ; case 'z' : size = va_arg (argptr, size_t) ; count += size ; while (size) { psf->header [psf->headindex] = 0 ; psf->headindex ++ ; size -- ; } ; break ; case 'h' : bindata = va_arg (argptr, void *) ; memcpy (&(psf->header [psf->headindex]), bindata, 16) ; psf->headindex += 16 ; count += 16 ; break ; case 'j' : /* Jump forwards/backwards by specified amount. */ size = va_arg (argptr, size_t) ; psf->headindex += size ; count += size ; break ; case 'o' : /* Jump to specified offset. */ size = va_arg (argptr, size_t) ; if (size < sizeof (psf->header)) { psf->headindex = size ; count = 0 ; } ; break ; default : psf_log_printf (psf, "*** Invalid format specifier `%c'\n", c) ; psf->error = SFE_INTERNAL ; break ; } ; } ; va_end (argptr) ; return count ; } /* psf_binheader_writef */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: sf_open (const char *path, int mode, SF_INFO *sfinfo) { SF_PRIVATE *psf ; /* Ultimate sanity check. */ assert (sizeof (sf_count_t) == 8) ; if ((psf = calloc (1, sizeof (SF_PRIVATE))) == NULL) { sf_errno = SFE_MALLOC_FAILED ; return NULL ; } ; psf_init_files (psf) ; psf_log_printf (psf, "File : %s\n", path) ; if (copy_filename (psf, path) != 0) { sf_errno = psf->error ; return NULL ; } ; psf->file.mode = mode ; if (strcmp (path, "-") == 0) psf->error = psf_set_stdio (psf) ; else psf->error = psf_fopen (psf) ; return psf_open_file (psf, sfinfo) ; } /* sf_open */ ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119', 'CWE-787'], 'message': 'src/ : Move to a variable length header buffer Previously, the `psf->header` buffer was a fixed length specified by `SF_HEADER_LEN` which was set to `12292`. This was problematic for two reasons; this value was un-necessarily large for the majority of files and too small for some others. Now the size of the header buffer starts at 256 bytes and grows as necessary up to a maximum of 100k.'</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: COMPAT_SYSCALL_DEFINE3(set_mempolicy, int, mode, compat_ulong_t __user *, nmask, compat_ulong_t, maxnode) { long err = 0; unsigned long __user *nm = NULL; unsigned long nr_bits, alloc_size; DECLARE_BITMAP(bm, MAX_NUMNODES); nr_bits = min_t(unsigned long, maxnode-1, MAX_NUMNODES); alloc_size = ALIGN(nr_bits, BITS_PER_LONG) / 8; if (nmask) { err = compat_get_bitmap(bm, nmask, nr_bits); nm = compat_alloc_user_space(alloc_size); err |= copy_to_user(nm, bm, alloc_size); } if (err) return -EFAULT; return sys_set_mempolicy(mode, nm, nr_bits+1); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-388'], 'message': 'mm/mempolicy.c: fix error handling in set_mempolicy and mbind. In the case that compat_get_bitmap fails we do not want to copy the bitmap to the user as it will contain uninitialized stack data and leak sensitive data. Signed-off-by: Chris Salls <[email protected]> Signed-off-by: Linus Torvalds <[email protected]>'</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 ahash_op_unaligned(struct ahash_request *req, int (*op)(struct ahash_request *)) { int err; err = ahash_save_req(req, ahash_op_unaligned_done); if (err) return err; err = op(req); ahash_op_unaligned_finish(req, err); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback The ahash API modifies the request's callback function in order to clean up after itself in some corner cases (unaligned final and missing finup). When the request is complete ahash will restore the original callback and everything is fine. However, when the request gets an EBUSY on a full queue, an EINPROGRESS callback is made while the request is still ongoing. In this case the ahash API will incorrectly call its own callback. This patch fixes the problem by creating a temporary request object on the stack which is used to relay EINPROGRESS back to the original completion function. This patch also adds code to preserve the original flags value. Fixes: ab6bf4e5e5e4 ("crypto: hash - Fix the pointer voodoo in...") Cc: <[email protected]> Reported-by: Sabrina Dubroca <[email protected]> Tested-by: Sabrina Dubroca <[email protected]> Signed-off-by: Herbert Xu <[email protected]>'</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 ahash_def_finup_finish1(struct ahash_request *req, int err) { if (err) goto out; req->base.complete = ahash_def_finup_done2; req->base.flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP; err = crypto_ahash_reqtfm(req)->final(req); out: ahash_def_finup_finish2(req, err); return err; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback The ahash API modifies the request's callback function in order to clean up after itself in some corner cases (unaligned final and missing finup). When the request is complete ahash will restore the original callback and everything is fine. However, when the request gets an EBUSY on a full queue, an EINPROGRESS callback is made while the request is still ongoing. In this case the ahash API will incorrectly call its own callback. This patch fixes the problem by creating a temporary request object on the stack which is used to relay EINPROGRESS back to the original completion function. This patch also adds code to preserve the original flags value. Fixes: ab6bf4e5e5e4 ("crypto: hash - Fix the pointer voodoo in...") Cc: <[email protected]> Reported-by: Sabrina Dubroca <[email protected]> Tested-by: Sabrina Dubroca <[email protected]> Signed-off-by: Herbert Xu <[email protected]>'</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 ahash_def_finup_finish2(struct ahash_request *req, int err) { struct ahash_request_priv *priv = req->priv; if (err == -EINPROGRESS) return; if (!err) memcpy(priv->result, req->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(req))); ahash_restore_req(req); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback The ahash API modifies the request's callback function in order to clean up after itself in some corner cases (unaligned final and missing finup). When the request is complete ahash will restore the original callback and everything is fine. However, when the request gets an EBUSY on a full queue, an EINPROGRESS callback is made while the request is still ongoing. In this case the ahash API will incorrectly call its own callback. This patch fixes the problem by creating a temporary request object on the stack which is used to relay EINPROGRESS back to the original completion function. This patch also adds code to preserve the original flags value. Fixes: ab6bf4e5e5e4 ("crypto: hash - Fix the pointer voodoo in...") Cc: <[email protected]> Reported-by: Sabrina Dubroca <[email protected]> Tested-by: Sabrina Dubroca <[email protected]> Signed-off-by: Herbert Xu <[email protected]>'</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 ahash_op_unaligned_finish(struct ahash_request *req, int err) { struct ahash_request_priv *priv = req->priv; if (err == -EINPROGRESS) return; if (!err) memcpy(priv->result, req->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(req))); ahash_restore_req(req); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback The ahash API modifies the request's callback function in order to clean up after itself in some corner cases (unaligned final and missing finup). When the request is complete ahash will restore the original callback and everything is fine. However, when the request gets an EBUSY on a full queue, an EINPROGRESS callback is made while the request is still ongoing. In this case the ahash API will incorrectly call its own callback. This patch fixes the problem by creating a temporary request object on the stack which is used to relay EINPROGRESS back to the original completion function. This patch also adds code to preserve the original flags value. Fixes: ab6bf4e5e5e4 ("crypto: hash - Fix the pointer voodoo in...") Cc: <[email protected]> Reported-by: Sabrina Dubroca <[email protected]> Tested-by: Sabrina Dubroca <[email protected]> Signed-off-by: Herbert Xu <[email protected]>'</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 ahash_def_finup_done2(struct crypto_async_request *req, int err) { struct ahash_request *areq = req->data; ahash_def_finup_finish2(areq, err); areq->base.complete(&areq->base, err); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'crypto: ahash - Fix EINPROGRESS notification callback The ahash API modifies the request's callback function in order to clean up after itself in some corner cases (unaligned final and missing finup). When the request is complete ahash will restore the original callback and everything is fine. However, when the request gets an EBUSY on a full queue, an EINPROGRESS callback is made while the request is still ongoing. In this case the ahash API will incorrectly call its own callback. This patch fixes the problem by creating a temporary request object on the stack which is used to relay EINPROGRESS back to the original completion function. This patch also adds code to preserve the original flags value. Fixes: ab6bf4e5e5e4 ("crypto: hash - Fix the pointer voodoo in...") Cc: <[email protected]> Reported-by: Sabrina Dubroca <[email protected]> Tested-by: Sabrina Dubroca <[email protected]> Signed-off-by: Herbert Xu <[email protected]>'</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 void ModulateLCHuv(const double percent_luma, const double percent_chroma,const double percent_hue,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToLCHuv(*red,*green,*blue,&luma,&chroma,&hue); luma*=0.01*percent_luma; chroma*=0.01*percent_chroma; hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; ConvertLCHuvToRGB(luma,chroma,hue,red,green,blue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'</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 void ModulateHSI(const double percent_hue, const double percent_saturation,const double percent_intensity,double *red, double *green,double *blue) { double intensity, hue, saturation; /* Increase or decrease color intensity, saturation, or hue. */ ConvertRGBToHSI(*red,*green,*blue,&hue,&saturation,&intensity); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; saturation*=0.01*percent_saturation; intensity*=0.01*percent_intensity; ConvertHSIToRGB(hue,saturation,intensity,red,green,blue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'</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 void ModulateHCLp(const double percent_hue, const double percent_chroma,const double percent_luma,double *red, double *green,double *blue) { double hue, luma, chroma; /* Increase or decrease color luma, chroma, or hue. */ ConvertRGBToHCLp(*red,*green,*blue,&hue,&chroma,&luma); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue > 1.0) hue-=1.0; chroma*=0.01*percent_chroma; luma*=0.01*percent_luma; ConvertHCLpToRGB(hue,chroma,luma,red,green,blue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'</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 void ModulateHWB(const double percent_hue, const double percent_whiteness,const double percent_blackness,double *red, double *green,double *blue) { double blackness, hue, whiteness; /* Increase or decrease color blackness, whiteness, or hue. */ ConvertRGBToHWB(*red,*green,*blue,&hue,&whiteness,&blackness); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; blackness*=0.01*percent_blackness; whiteness*=0.01*percent_whiteness; ConvertHWBToRGB(hue,whiteness,blackness,red,green,blue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'</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 void ModulateHSL(const double percent_hue, const double percent_saturation,const double percent_lightness,double *red, double *green,double *blue) { double hue, lightness, saturation; /* Increase or decrease color lightness, saturation, or hue. */ ConvertRGBToHSL(*red,*green,*blue,&hue,&saturation,&lightness); hue+=0.5*(0.01*percent_hue-1.0); while (hue < 0.0) hue+=1.0; while (hue >= 1.0) hue-=1.0; saturation*=0.01*percent_saturation; lightness*=0.01*percent_lightness; ConvertHSLToRGB(hue,saturation,lightness,red,green,blue); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-835'], 'message': 'https://www.imagemagick.org/discourse-server/viewtopic.php?f=3&t=31506'</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: pdf14_pop_transparency_group(gs_gstate *pgs, pdf14_ctx *ctx, const pdf14_nonseparable_blending_procs_t * pblend_procs, int tos_num_color_comp, cmm_profile_t *curr_icc_profile, gx_device *dev) { pdf14_buf *tos = ctx->stack; pdf14_buf *nos = tos->saved; pdf14_mask_t *mask_stack = tos->mask_stack; pdf14_buf *maskbuf; int x0, x1, y0, y1; byte *new_data_buf = NULL; int num_noncolor_planes, new_num_planes; int num_cols, num_rows, nos_num_color_comp; bool icc_match; gsicc_rendering_param_t rendering_params; gsicc_link_t *icc_link; gsicc_bufferdesc_t input_buff_desc; gsicc_bufferdesc_t output_buff_desc; pdf14_device *pdev = (pdf14_device *)dev; bool overprint = pdev->overprint; gx_color_index drawn_comps = pdev->drawn_comps; bool nonicc_conversion = true; nos_num_color_comp = nos->parent_color_info_procs->num_components - nos->num_spots; tos_num_color_comp = tos_num_color_comp - tos->num_spots; #ifdef DEBUG pdf14_debug_mask_stack_state(ctx); #endif if (mask_stack == NULL) { maskbuf = NULL; } else { maskbuf = mask_stack->rc_mask->mask_buf; } if (nos == NULL) return_error(gs_error_rangecheck); /* Sanitise the dirty rectangles, in case some of the drawing routines * have made them overly large. */ rect_intersect(tos->dirty, tos->rect); rect_intersect(nos->dirty, nos->rect); /* dirty = the marked bbox. rect = the entire bounds of the buffer. */ /* Everything marked on tos that fits onto nos needs to be merged down. */ y0 = max(tos->dirty.p.y, nos->rect.p.y); y1 = min(tos->dirty.q.y, nos->rect.q.y); x0 = max(tos->dirty.p.x, nos->rect.p.x); x1 = min(tos->dirty.q.x, nos->rect.q.x); if (ctx->mask_stack) { /* This can occur when we have a situation where we are ending out of a group that has internal to it a soft mask and another group. The soft mask left over from the previous trans group pop is put into ctx->masbuf, since it is still active if another trans group push occurs to use it. If one does not occur, but instead we find ourselves popping from a parent group, then this softmask is no longer needed. We will rc_decrement and set it to NULL. */ rc_decrement(ctx->mask_stack->rc_mask, "pdf14_pop_transparency_group"); if (ctx->mask_stack->rc_mask == NULL ){ gs_free_object(ctx->memory, ctx->mask_stack, "pdf14_pop_transparency_group"); } ctx->mask_stack = NULL; } ctx->mask_stack = mask_stack; /* Restore the mask saved by pdf14_push_transparency_group. */ tos->mask_stack = NULL; /* Clean the pointer sinse the mask ownership is now passed to ctx. */ if (tos->idle) goto exit; if (maskbuf != NULL && maskbuf->data == NULL && maskbuf->alpha == 255) goto exit; #if RAW_DUMP /* Dump the current buffer to see what we have. */ dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y, ctx->stack->rowstride, ctx->stack->n_planes, ctx->stack->planestride, ctx->stack->rowstride, "aaTrans_Group_Pop",ctx->stack->data); #endif /* Note currently if a pattern space has transparency, the ICC profile is not used for blending purposes. Instead we rely upon the gray, rgb, or cmyk parent space. This is partially due to the fact that pdf14_pop_transparency_group and pdf14_push_transparnecy_group have no real ICC interaction and those are the operations called in the tile transparency code. Instead we may want to look at pdf14_begin_transparency_group and pdf14_end_transparency group which is where all the ICC information is handled. We will return to look at that later */ if (nos->parent_color_info_procs->icc_profile != NULL) { icc_match = (nos->parent_color_info_procs->icc_profile->hashcode != curr_icc_profile->hashcode); } else { /* Let the other tests make the decision if we need to transform */ icc_match = false; } /* If the color spaces are different and we actually did do a swap of the procs for color */ if ((nos->parent_color_info_procs->parent_color_mapping_procs != NULL && nos_num_color_comp != tos_num_color_comp) || icc_match) { if (x0 < x1 && y0 < y1) { /* The NOS blending color space is different than that of the TOS. It is necessary to transform the TOS buffer data to the color space of the NOS prior to doing the pdf14_compose_group operation. */ num_noncolor_planes = tos->n_planes - tos_num_color_comp; new_num_planes = num_noncolor_planes + nos_num_color_comp; /* See if we are doing ICC based conversion */ if (nos->parent_color_info_procs->icc_profile != NULL && curr_icc_profile != NULL) { /* Use the ICC color management for buffer color conversion */ /* Define the rendering intents */ rendering_params.black_point_comp = gsBLACKPTCOMP_ON; rendering_params.graphics_type_tag = GS_IMAGE_TAG; rendering_params.override_icc = false; rendering_params.preserve_black = gsBKPRESNOTSPECIFIED; rendering_params.rendering_intent = gsPERCEPTUAL; rendering_params.cmm = gsCMM_DEFAULT; /* Request the ICC link for the transform that we will need to use */ /* Note that if pgs is NULL we assume the same color space. This is due to a call to pop the group from fill_mask when filling with a mask with transparency. In that case, the parent and the child will have the same color space anyway */ icc_link = gsicc_get_link_profile(pgs, dev, curr_icc_profile, nos->parent_color_info_procs->icc_profile, &rendering_params, pgs->memory, false); if (icc_link != NULL) { /* if problem with link we will do non-ICC approach */ nonicc_conversion = false; /* If the link is the identity, then we don't need to do any color conversions */ if ( !(icc_link->is_identity) ) { /* Before we do any allocations check if we can get away with reusing the existing buffer if it is the same size ( if it is smaller go ahead and allocate). We could reuse it in this case too. We need to do a bit of testing to determine what would be best. */ /* FIXME: RJW: Could we get away with just color converting * the area that's actually active (i.e. dirty, not rect)? */ if(nos_num_color_comp != tos_num_color_comp) { /* Different size. We will need to allocate */ new_data_buf = gs_alloc_bytes(ctx->memory, tos->planestride * new_num_planes, "pdf14_pop_transparency_group"); if (new_data_buf == NULL) return_error(gs_error_VMerror); /* Copy over the noncolor planes. */ memcpy(new_data_buf + tos->planestride * nos_num_color_comp, tos->data + tos->planestride * tos_num_color_comp, tos->planestride * num_noncolor_planes); } else { /* In place color conversion! */ new_data_buf = tos->data; } /* Set up the buffer descriptors. Note that pdf14 always has the alpha channels at the back end (last planes). We will just handle that here and let the CMM know nothing about it */ num_rows = tos->rect.q.y - tos->rect.p.y; num_cols = tos->rect.q.x - tos->rect.p.x; gsicc_init_buffer(&input_buff_desc, tos_num_color_comp, 1, false, false, true, tos->planestride, tos->rowstride, num_rows, num_cols); gsicc_init_buffer(&output_buff_desc, nos_num_color_comp, 1, false, false, true, tos->planestride, tos->rowstride, num_rows, num_cols); /* Transform the data. Since the pdf14 device should be using RGB, CMYK or Gray buffers, this transform does not need to worry about the cmap procs of the target device. Those are handled when we do the pdf14 put image operation */ (icc_link->procs.map_buffer)(dev, icc_link, &input_buff_desc, &output_buff_desc, tos->data, new_data_buf); } /* Release the link */ gsicc_release_link(icc_link); /* free the old object if the color spaces were different sizes */ if(!(icc_link->is_identity) && nos_num_color_comp != tos_num_color_comp) { gs_free_object(ctx->memory, tos->data, "pdf14_pop_transparency_group"); tos->data = new_data_buf; } } } if (nonicc_conversion) { /* Non ICC based transform */ new_data_buf = gs_alloc_bytes(ctx->memory, tos->planestride * new_num_planes, "pdf14_pop_transparency_group"); if (new_data_buf == NULL) return_error(gs_error_VMerror); gs_transform_color_buffer_generic(tos->data, tos->rowstride, tos->planestride, tos_num_color_comp, tos->rect, new_data_buf, nos_num_color_comp, num_noncolor_planes); /* Free the old object */ gs_free_object(ctx->memory, tos->data, "pdf14_pop_transparency_group"); tos->data = new_data_buf; } /* Adjust the plane and channel size now */ tos->n_chan = nos->n_chan; tos->n_planes = nos->n_planes; #if RAW_DUMP /* Dump the current buffer to see what we have. */ dump_raw_buffer(ctx->stack->rect.q.y-ctx->stack->rect.p.y, ctx->stack->rowstride, ctx->stack->n_chan, ctx->stack->planestride, ctx->stack->rowstride, "aCMTrans_Group_ColorConv",ctx->stack->data); #endif /* compose. never do overprint in this case */ pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan, nos->parent_color_info_procs->isadditive, nos->parent_color_info_procs->parent_blending_procs, false, drawn_comps, ctx->memory, dev); } } else { /* Group color spaces are the same. No color conversions needed */ if (x0 < x1 && y0 < y1) pdf14_compose_group(tos, nos, maskbuf, x0, x1, y0, y1, nos->n_chan, ctx->additive, pblend_procs, overprint, drawn_comps, ctx->memory, dev); } exit: ctx->stack = nos; /* We want to detect the cases where we have luminosity soft masks embedded within one another. The "alpha" channel really needs to be merged into the luminosity channel in this case. This will occur during the mask pop */ if (ctx->smask_depth > 0 && maskbuf != NULL) { /* Set the trigger so that we will blend if not alpha. Since we have softmasks embedded in softmasks */ ctx->smask_blend = true; } if_debug1m('v', ctx->memory, "[v]pop buf, idle=%d\n", tos->idle); pdf14_buf_free(tos, ctx->memory); return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-476'], 'message': 'Bug 697444 Unmatched transparency group pop This issue can only occur if there is an unmatched group pop. If the interpreter is doing that, then the interpreter is broken. With this bug the user is intentionally doing it. We now throw and error when it occurs.'</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: gxht_thresh_planes(gx_image_enum *penum, fixed xrun, int dest_width, int dest_height, byte *thresh_align, gx_device * dev, int offset_contone[], int contone_stride) { int thresh_width, thresh_height, dx; int left_rem_end, left_width, vdi; int num_full_tiles, right_tile_width; int k, jj, dy, j; byte *thresh_tile; int position; bool replicate_tile; image_posture posture = penum->posture; const int y_pos = penum->yci; int width = 0; /* Init to silence compiler warnings */ byte *ptr_out, *row_ptr, *ptr_out_temp; byte *threshold; int init_tile, in_row_offset, ii, num_tiles, tile_remainder; int offset_bits = penum->ht_offset_bits; byte *halftone; int dithered_stride = penum->ht_stride; bool is_planar_dev = dev->is_planar; gx_color_index dev_white = gx_device_white(dev); gx_color_index dev_black = gx_device_black(dev); int spp_out = dev->color_info.num_components; byte *contone_align = NULL; /* Init to silence compiler warnings */ /* Go ahead and fill the threshold line buffer with tiled threshold values. First just grab the row or column that we are going to tile with and then do memcpy into the buffer */ /* Figure out the tile steps. Left offset, Number of tiles, Right offset. */ switch (posture) { case image_portrait: vdi = penum->hci; /* Iterate over the vdi and fill up our threshold buffer. We also need to loop across the planes of data */ for (j = 0; j < spp_out; j++) { bool threshold_inverted = penum->pgs->dev_ht->components[j].corder.threshold_inverted; thresh_width = penum->pgs->dev_ht->components[j].corder.width; thresh_height = penum->pgs->dev_ht->components[j].corder.full_height; halftone = penum->ht_buffer + j * vdi * dithered_stride; /* Compute the tiling positions with dest_width */ dx = (fixed2int_var_rounded(xrun) + penum->pgs->screen_phase[0].x) % thresh_width; /* Left remainder part */ left_rem_end = min(dx + dest_width, thresh_width); /* The left width of our tile part */ left_width = left_rem_end - dx; /* Now the middle part */ num_full_tiles = (int)fastfloor((dest_width - left_width)/ (float) thresh_width); /* Now the right part */ right_tile_width = dest_width - num_full_tiles * thresh_width - left_width; /* Get the proper threshold for the colorant count */ threshold = penum->pgs->dev_ht->components[j].corder.threshold; /* Point to the proper contone data */ contone_align = penum->line + contone_stride * j + offset_contone[j]; for (k = 0; k < vdi; k++) { /* Get a pointer to our tile row */ dy = (penum->yci + k + penum->dev->band_offset_y) % thresh_height; if (dy < 0) dy += thresh_height; thresh_tile = threshold + thresh_width * dy; /* Fill the buffer, can be multiple rows. Make sure to update with stride */ position = contone_stride * k; /* Tile into the 128 bit aligned threshold strip */ fill_threshhold_buffer(&(thresh_align[position]), thresh_tile, thresh_width, dx, left_width, num_full_tiles, right_tile_width); } /* Apply the threshold operation */ if (offset_bits > dest_width) offset_bits = dest_width; if (threshold_inverted || (dev->color_info.polarity == GX_CINFO_POLARITY_SUBTRACTIVE && is_planar_dev)) { gx_ht_threshold_row_bit_sub(contone_align, thresh_align, contone_stride, halftone, dithered_stride, dest_width, vdi, offset_bits); } else { gx_ht_threshold_row_bit(contone_align, thresh_align, contone_stride, halftone, dithered_stride, dest_width, vdi, offset_bits); } } /* FIXME: An improvement here would be to generate the initial * offset_bits at the correct offset within the byte so that they * align with the remainder of the line. This would mean not * always packing them into the first offset_bits (in MSB order) * of our 16 bit word, but rather into the last offset_bits * (in MSB order) (except when the entire run is small!). * * This would enable us to do just one aligned copy_mono call for * the entire scanline. */ /* Now do the copy mono or copy plane operation */ /* First the left remainder bits */ if (offset_bits > 0) { int x_pos = fixed2int_var_rounded(xrun); if (!is_planar_dev) { (*dev_proc(dev, copy_mono)) (dev, penum->ht_buffer, 0, dithered_stride, gx_no_bitmap_id, x_pos, y_pos, offset_bits, vdi, dev_white, dev_black); } else { (*dev_proc(dev, copy_planes)) (dev, penum->ht_buffer, 0, dithered_stride, gx_no_bitmap_id, x_pos, y_pos, offset_bits, vdi, vdi); } } if ((dest_width - offset_bits) > 0 ) { /* Now the primary aligned bytes */ int curr_width = dest_width - offset_bits; int x_pos = fixed2int_var_rounded(xrun) + offset_bits; /* FIXME: This assumes the allowed offset_bits will always be <= 16 */ int xoffs = offset_bits > 0 ? 16 : 0; if (!is_planar_dev) { (*dev_proc(dev, copy_mono)) (dev, penum->ht_buffer, xoffs, dithered_stride, gx_no_bitmap_id, x_pos, y_pos, curr_width, vdi, dev_white, dev_black); } else { (*dev_proc(dev, copy_planes)) (dev, penum->ht_buffer, xoffs, dithered_stride, gx_no_bitmap_id, x_pos, y_pos, curr_width, vdi, vdi); } } break; case image_landscape: /* Go ahead and paint the chunk if we have LAND_BITS values or a * partial to get us in sync with the 1 bit devices 16 bit * positions. */ vdi = penum->wci; /* Now do the haftoning into our buffer. We basically check first if we have enough data or are all done */ while ( (penum->ht_landscape.count >= LAND_BITS || ((penum->ht_landscape.count >= offset_bits) && penum->ht_landscape.offset_set))) { /* Go ahead and 2D tile in the threshold buffer at this time */ /* Always work the tiling from the upper left corner of our LAND_BITS columns */ for (j = 0; j < spp_out; j++) { halftone = penum->ht_buffer + j * penum->ht_plane_height * (LAND_BITS>>3); thresh_width = penum->pgs->dev_ht->components[j].corder.width; thresh_height = penum->pgs->dev_ht->components[j].corder.full_height; /* Get the proper threshold for the colorant count */ threshold = penum->pgs->dev_ht->components[j].corder.threshold; /* Point to the proper contone data */ contone_align = penum->line + offset_contone[j] + LAND_BITS * j * contone_stride; if (penum->ht_landscape.offset_set) { width = offset_bits; } else { width = LAND_BITS; } if (penum->y_extent.x < 0) { dx = penum->ht_landscape.xstart - width + 1; } else { dx = penum->ht_landscape.xstart; } dx = (dx + penum->pgs->screen_phase[0].x) % thresh_width; dy = (penum->ht_landscape.y_pos + penum->dev->band_offset_y) % thresh_height; if (dy < 0) dy += thresh_height; /* Left remainder part */ left_rem_end = min(dx + LAND_BITS, thresh_width); left_width = left_rem_end - dx; /* Now the middle part */ num_full_tiles = (LAND_BITS - left_width) / thresh_width; /* Now the right part */ right_tile_width = LAND_BITS - num_full_tiles * thresh_width - left_width; /* Now loop over the y stuff */ ptr_out = thresh_align; /* Do this in three parts. We do a top part, followed by larger mem copies followed by a bottom partial. After a slower initial fill we are able to do larger faster expansions */ if (dest_height <= 2 * thresh_height) { init_tile = dest_height; replicate_tile = false; } else { init_tile = thresh_height; replicate_tile = true; } for (jj = 0; jj < init_tile; jj++) { in_row_offset = (jj + dy) % thresh_height; row_ptr = threshold + in_row_offset * thresh_width; ptr_out_temp = ptr_out; /* Left part */ memcpy(ptr_out_temp, row_ptr + dx, left_width); ptr_out_temp += left_width; /* Now the full tiles */ for (ii = 0; ii < num_full_tiles; ii++) { memcpy(ptr_out_temp, row_ptr, thresh_width); ptr_out_temp += thresh_width; } /* Now the remainder */ memcpy(ptr_out_temp, row_ptr, right_tile_width); ptr_out += LAND_BITS; } if (replicate_tile) { /* Find out how many we need to copy */ num_tiles = (int)fastfloor((float) (dest_height - thresh_height)/ (float) thresh_height); tile_remainder = dest_height - (num_tiles + 1) * thresh_height; for (jj = 0; jj < num_tiles; jj ++) { memcpy(ptr_out, thresh_align, LAND_BITS * thresh_height); ptr_out += LAND_BITS * thresh_height; } /* Now fill in the remainder */ memcpy(ptr_out, thresh_align, LAND_BITS * tile_remainder); } /* Apply the threshold operation */ if (dev->color_info.polarity == GX_CINFO_POLARITY_SUBTRACTIVE && is_planar_dev) { gx_ht_threshold_landscape_sub(contone_align, thresh_align, &(penum->ht_landscape), halftone, dest_height); } else { gx_ht_threshold_landscape(contone_align, thresh_align, &(penum->ht_landscape), halftone, dest_height); } /* We may have a line left over that has to be maintained due to line replication in the resolution conversion. */ if (width != penum->ht_landscape.count) { /* move the line do not reset the stuff */ move_landscape_buffer(&(penum->ht_landscape), contone_align, dest_height); } } /* Perform the copy mono */ if (penum->ht_landscape.index < 0) { if (!is_planar_dev) { (*dev_proc(dev, copy_mono)) (dev, penum->ht_buffer, 0, LAND_BITS>>3, gx_no_bitmap_id, penum->ht_landscape.xstart - width + 1, penum->ht_landscape.y_pos, width, dest_height, dev_white, dev_black); } else { (*dev_proc(dev, copy_planes)) (dev, penum->ht_buffer, 0, LAND_BITS>>3, gx_no_bitmap_id, penum->ht_landscape.xstart - width + 1, penum->ht_landscape.y_pos, width, dest_height, penum->ht_plane_height); } } else { if (!is_planar_dev) { (*dev_proc(dev, copy_mono)) (dev, penum->ht_buffer, 0, LAND_BITS>>3, gx_no_bitmap_id, penum->ht_landscape.xstart, penum->ht_landscape.y_pos, width, dest_height, dev_white, dev_black); } else { (*dev_proc(dev, copy_planes)) (dev, penum->ht_buffer, 0, LAND_BITS>>3, gx_no_bitmap_id, penum->ht_landscape.xstart, penum->ht_landscape.y_pos, width, dest_height, penum->ht_plane_height); } } penum->ht_landscape.offset_set = false; if (width != penum->ht_landscape.count) { reset_landscape_buffer(&(penum->ht_landscape), contone_align, dest_height, width); } else { /* Reset the whole buffer */ penum->ht_landscape.count = 0; if (penum->ht_landscape.index < 0) { /* Going right to left */ penum->ht_landscape.curr_pos = LAND_BITS-1; } else { /* Going left to right */ penum->ht_landscape.curr_pos = 0; } penum->ht_landscape.num_contones = 0; memset(&(penum->ht_landscape.widths[0]), 0, sizeof(int)*LAND_BITS); } } break; default: return gs_rethrow(-1, "Invalid orientation for thresholding"); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug 697459 Buffer overflow in fill_threshold_buffer There was an overflow check for ht_buffer size, but none for the larger threshold_buffer. Note that this file didn't fail on Windows because the combination of the ht_buffer and the size of the (miscalculated due to overflow) threshold_buffer would have exceeded the 2Gb limit.'</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: gx_image_enum_begin(gx_device * dev, const gs_gstate * pgs, const gs_matrix *pmat, const gs_image_common_t * pic, const gx_drawing_color * pdcolor, const gx_clip_path * pcpath, gs_memory_t * mem, gx_image_enum *penum) { const gs_pixel_image_t *pim = (const gs_pixel_image_t *)pic; gs_image_format_t format = pim->format; const int width = pim->Width; const int height = pim->Height; const int bps = pim->BitsPerComponent; bool masked = penum->masked; const float *decode = pim->Decode; gs_matrix_double mat; int index_bps; const gs_color_space *pcs = pim->ColorSpace; gs_logical_operation_t lop = (pgs ? pgs->log_op : lop_default); int code; int log2_xbytes = (bps <= 8 ? 0 : arch_log2_sizeof_frac); int spp, nplanes, spread; uint bsize; byte *buffer; fixed mtx, mty; gs_fixed_point row_extent, col_extent, x_extent, y_extent; bool device_color = true; gs_fixed_rect obox, cbox; bool gridfitimages = 0; bool in_pattern_accumulator = 0; int orthogonal; int force_interpolation = 0; penum->clues = NULL; penum->icc_setup.has_transfer = false; penum->icc_setup.is_lab = false; penum->icc_setup.must_halftone = false; penum->icc_setup.need_decode = false; penum->Width = width; penum->Height = height; if ((code = gx_image_compute_mat(pgs, pmat, &(pim->ImageMatrix), &mat)) < 0) { return code; } /* Grid fit: A common construction in postscript/PDF files is for images * to be constructed as a series of 'stacked' 1 pixel high images. * Furthermore, many of these are implemented as an imagemask plotted on * top of thin rectangles. The different fill rules for images and line * art produces problems; line art fills a pixel if any part of it is * touched - images only fill a pixel if the centre of the pixel is * covered. Bug 692666 is such a problem. * * As a workaround for this problem, the code below was introduced. The * concept is that orthogonal images can be 'grid fitted' (or 'stretch') * to entirely cover pixels that they touch. Initially I had this working * for all images regardless of type, but as testing has proceeded, this * showed more and more regressions, so I've cut the cases back in which * this code is used until it now only triggers on imagemasks that are * either 1 pixel high, or wide, and then not if we are rendering a * glyph (such as from a type3 font). */ /* Ask the device if we are in a pattern accumulator */ in_pattern_accumulator = (dev_proc(dev, dev_spec_op)(dev, gxdso_in_pattern_accumulator, NULL, 0)); if (in_pattern_accumulator < 0) in_pattern_accumulator = 0; /* Figure out if we are orthogonal */ if (mat.xy == 0 && mat.yx == 0) orthogonal = 1; else if (mat.xx == 0 && mat.yy == 0) orthogonal = 2; else orthogonal = 0; /* If we are in a pattern accumulator, we choose to always grid fit * orthogonal images. We do this by asking the device whether we * should grid fit. This allows us to avoid nasty blank lines around * the edges of cells. */ gridfitimages = in_pattern_accumulator && orthogonal; if (pgs != NULL && pgs->show_gstate != NULL) { /* If we're a graphics state, and we're in a text object, then we * must be in a type3 font. Don't fiddle with it. */ } else if (!gridfitimages && (!penum->masked || penum->image_parent_type != 0)) { /* Other than for images we are specifically looking to grid fit (such as * ones in a pattern device), we only grid fit imagemasks */ } else if (gridfitimages && (penum->masked && penum->image_parent_type == 0)) { /* We don't gridfit imagemasks in a pattern accumulator */ } else if (pgs != NULL && pgs->fill_adjust.x == 0 && pgs->fill_adjust.y == 0) { /* If fill adjust is disabled, so is grid fitting */ } else if (orthogonal == 1) { if (width == 1 || gridfitimages) { if (mat.xx > 0) { fixed ix0 = int2fixed(fixed2int(float2fixed(mat.tx))); double x1 = mat.tx + mat.xx * width; fixed ix1 = int2fixed(fixed2int_ceiling(float2fixed(x1))); mat.tx = (double)fixed2float(ix0); mat.xx = (double)(fixed2float(ix1 - ix0)/width); } else if (mat.xx < 0) { fixed ix0 = int2fixed(fixed2int_ceiling(float2fixed(mat.tx))); double x1 = mat.tx + mat.xx * width; fixed ix1 = int2fixed(fixed2int(float2fixed(x1))); mat.tx = (double)fixed2float(ix0); mat.xx = (double)(fixed2float(ix1 - ix0)/width); } } if (height == 1 || gridfitimages) { if (mat.yy > 0) { fixed iy0 = int2fixed(fixed2int(float2fixed(mat.ty))); double y1 = mat.ty + mat.yy * height; fixed iy1 = int2fixed(fixed2int_ceiling(float2fixed(y1))); mat.ty = (double)fixed2float(iy0); mat.yy = (double)(fixed2float(iy1 - iy0)/height); } else if (mat.yy < 0) { fixed iy0 = int2fixed(fixed2int_ceiling(float2fixed(mat.ty))); double y1 = mat.ty + mat.yy * height; fixed iy1 = int2fixed(fixed2int(float2fixed(y1))); mat.ty = (double)fixed2float(iy0); mat.yy = ((double)fixed2float(iy1 - iy0)/height); } } } else if (orthogonal == 2) { if (height == 1 || gridfitimages) { if (mat.yx > 0) { fixed ix0 = int2fixed(fixed2int(float2fixed(mat.tx))); double x1 = mat.tx + mat.yx * height; fixed ix1 = int2fixed(fixed2int_ceiling(float2fixed(x1))); mat.tx = (double)fixed2float(ix0); mat.yx = (double)(fixed2float(ix1 - ix0)/height); } else if (mat.yx < 0) { fixed ix0 = int2fixed(fixed2int_ceiling(float2fixed(mat.tx))); double x1 = mat.tx + mat.yx * height; fixed ix1 = int2fixed(fixed2int(float2fixed(x1))); mat.tx = (double)fixed2float(ix0); mat.yx = (double)(fixed2float(ix1 - ix0)/height); } } if (width == 1 || gridfitimages) { if (mat.xy > 0) { fixed iy0 = int2fixed(fixed2int(float2fixed(mat.ty))); double y1 = mat.ty + mat.xy * width; fixed iy1 = int2fixed(fixed2int_ceiling(float2fixed(y1))); mat.ty = (double)fixed2float(iy0); mat.xy = (double)(fixed2float(iy1 - iy0)/width); } else if (mat.xy < 0) { fixed iy0 = int2fixed(fixed2int_ceiling(float2fixed(mat.ty))); double y1 = mat.ty + mat.xy * width; fixed iy1 = int2fixed(fixed2int(float2fixed(y1))); mat.ty = (double)fixed2float(iy0); mat.xy = ((double)fixed2float(iy1 - iy0)/width); } } } /* When rendering to a pattern accumulator, if we are downscaling * then enable interpolation, as otherwise dropouts can cause * serious problems. */ if (in_pattern_accumulator) { double ome = ((double)(fixed_1 - fixed_epsilon)) / (double)fixed_1; /* One Minus Epsilon */ if (orthogonal == 1) { if ((mat.xx > -ome && mat.xx < ome) || (mat.yy > -ome && mat.yy < ome)) { force_interpolation = true; } } else if (orthogonal == 2) { if ((mat.xy > -ome && mat.xy < ome) || (mat.yx > -ome && mat.yx < ome)) { force_interpolation = true; } } } /* Can we restrict the amount of image we need? */ while (pcpath) /* So we can break out of it */ { gs_rect rect, rect_out; gs_matrix mi; const gs_matrix *m = pgs != NULL ? &ctm_only(pgs) : NULL; gs_fixed_rect obox; gs_int_rect irect; if (m == NULL || (code = gs_matrix_invert(m, &mi)) < 0 || (code = gs_matrix_multiply(&mi, &pic->ImageMatrix, &mi)) < 0) { /* Give up trying to shrink the render box, but continue processing */ break; } gx_cpath_outer_box(pcpath, &obox); rect.p.x = fixed2float(obox.p.x); rect.p.y = fixed2float(obox.p.y); rect.q.x = fixed2float(obox.q.x); rect.q.y = fixed2float(obox.q.y); code = gs_bbox_transform(&rect, &mi, &rect_out); if (code < 0) { /* Give up trying to shrink the render box, but continue processing */ break; } irect.p.x = (int)(rect_out.p.x-1.0); irect.p.y = (int)(rect_out.p.y-1.0); irect.q.x = (int)(rect_out.q.x+1.0); irect.q.y = (int)(rect_out.q.y+1.0); /* Need to expand the region to allow for the fact that the mitchell * scaler reads multiple pixels in. This calculation can probably be * improved. */ /* If mi.{xx,yy} > 1 then we are downscaling. During downscaling, * the support increases to ensure that we don't lose pixels contributions * entirely. */ /* I do not understand the need for the +/- 1 fudge factors, * but they seem to be required. Increasing the render rectangle can * never be bad at least... RJW */ { float support = any_abs(mi.xx); int isupport; if (any_abs(mi.yy) > support) support = any_abs(mi.yy); if (any_abs(mi.xy) > support) support = any_abs(mi.xy); if (any_abs(mi.yx) > support) support = any_abs(mi.yx); isupport = (int)(MAX_ISCALE_SUPPORT * (support+1)) + 1; irect.p.x -= isupport; irect.p.y -= isupport; irect.q.x += isupport; irect.q.y += isupport; } if (penum->rrect.x < irect.p.x) { penum->rrect.w -= irect.p.x - penum->rrect.x; if (penum->rrect.w < 0) penum->rrect.w = 0; penum->rrect.x = irect.p.x; } if (penum->rrect.x + penum->rrect.w > irect.q.x) { penum->rrect.w = irect.q.x - penum->rrect.x; if (penum->rrect.w < 0) penum->rrect.w = 0; } if (penum->rrect.y < irect.p.y) { penum->rrect.h -= irect.p.y - penum->rrect.y; if (penum->rrect.h < 0) penum->rrect.h = 0; penum->rrect.y = irect.p.y; } if (penum->rrect.y + penum->rrect.h > irect.q.y) { penum->rrect.h = irect.q.y - penum->rrect.y; if (penum->rrect.h < 0) penum->rrect.h = 0; } break; /* Out of the while */ } /* Check for the intersection being null */ if (penum->rrect.x + penum->rrect.w <= penum->rect.x || penum->rect.x + penum->rect.w <= penum->rrect.x || penum->rrect.y + penum->rrect.h <= penum->rect.y || penum->rect.y + penum->rect.h <= penum->rrect.y) { /* Something may have gone wrong with the floating point above. * set the region to something sane. */ penum->rrect.x = penum->rect.x; penum->rrect.y = penum->rect.y; penum->rrect.w = 0; penum->rrect.h = 0; } /*penum->matrix = mat;*/ penum->matrix.xx = mat.xx; penum->matrix.xy = mat.xy; penum->matrix.yx = mat.yx; penum->matrix.yy = mat.yy; penum->matrix.tx = mat.tx; penum->matrix.ty = mat.ty; if_debug6m('b', mem, " [%g %g %g %g %g %g]\n", mat.xx, mat.xy, mat.yx, mat.yy, mat.tx, mat.ty); /* following works for 1, 2, 4, 8, 12, 16 */ index_bps = (bps < 8 ? bps >> 1 : (bps >> 2) + 1); /* * Compute extents with distance transformation. */ if (mat.tx > 0) mtx = float2fixed(mat.tx); else { /* Use positive values to ensure round down. */ int f = (int)-mat.tx + 1; mtx = float2fixed(mat.tx + f) - int2fixed(f); } if (mat.ty > 0) mty = float2fixed(mat.ty); else { /* Use positive values to ensure round down. */ int f = (int)-mat.ty + 1; mty = float2fixed(mat.ty + f) - int2fixed(f); } row_extent.x = float2fixed_rounded_boxed(width * mat.xx); row_extent.y = (is_fzero(mat.xy) ? fixed_0 : float2fixed_rounded_boxed(width * mat.xy)); col_extent.x = (is_fzero(mat.yx) ? fixed_0 : float2fixed_rounded_boxed(height * mat.yx)); col_extent.y = float2fixed_rounded_boxed(height * mat.yy); gx_image_enum_common_init((gx_image_enum_common_t *)penum, (const gs_data_image_t *)pim, &image1_enum_procs, dev, (masked ? 1 : (penum->alpha ? cs_num_components(pcs)+1 : cs_num_components(pcs))), format); if (penum->rect.w == width && penum->rect.h == height) { x_extent = row_extent; y_extent = col_extent; } else { int rw = penum->rect.w, rh = penum->rect.h; x_extent.x = float2fixed_rounded_boxed(rw * mat.xx); x_extent.y = (is_fzero(mat.xy) ? fixed_0 : float2fixed_rounded_boxed(rw * mat.xy)); y_extent.x = (is_fzero(mat.yx) ? fixed_0 : float2fixed_rounded_boxed(rh * mat.yx)); y_extent.y = float2fixed_rounded_boxed(rh * mat.yy); } /* Set icolor0 and icolor1 to point to image clues locations if we have 1spp or an imagemask, otherwise image clues is not used and we have these values point to other member variables */ if (masked || cs_num_components(pcs) == 1) { /* Go ahead and allocate now if not already done. For a mask we really should only do 2 values. For now, the goal is to eliminate the 256 bytes for the >8bpp image enumerator */ penum->clues = (gx_image_clue*) gs_alloc_bytes(mem, sizeof(gx_image_clue)*256, "gx_image_enum_begin"); if (penum->clues == NULL) return_error(gs_error_VMerror); penum->icolor0 = &(penum->clues[0].dev_color); penum->icolor1 = &(penum->clues[255].dev_color); } else { penum->icolor0 = &(penum->icolor0_val); penum->icolor1 = &(penum->icolor1_val); } if (masked) { /* This is imagemask. */ if (bps != 1 || pcs != NULL || penum->alpha || decode[0] == decode[1]) { return_error(gs_error_rangecheck); } /* Initialize color entries 0 and 255. */ set_nonclient_dev_color(penum->icolor0, gx_no_color_index); set_nonclient_dev_color(penum->icolor1, gx_no_color_index); *(penum->icolor1) = *pdcolor; memcpy(&penum->map[0].table.lookup4x1to32[0], (decode[0] < decode[1] ? lookup4x1to32_inverted : lookup4x1to32_identity), 16 * 4); penum->map[0].decoding = sd_none; spp = 1; lop = rop3_know_S_0(lop); } else { /* This is image, not imagemask. */ const gs_color_space_type *pcst = pcs->type; int b_w_color; spp = cs_num_components(pcs); if (spp < 0) { /* Pattern not allowed */ return_error(gs_error_rangecheck); } if (penum->alpha) ++spp; /* Use a less expensive format if possible. */ switch (format) { case gs_image_format_bit_planar: if (bps > 1) break; format = gs_image_format_component_planar; case gs_image_format_component_planar: if (spp == 1) format = gs_image_format_chunky; default: /* chunky */ break; } if (pcs->cmm_icc_profile_data != NULL) { device_color = false; } else { device_color = (*pcst->concrete_space) (pcs, pgs) == pcs; } code = image_init_colors(penum, bps, spp, format, decode, pgs, dev, pcs, &device_color); if (code < 0) return gs_throw(code, "Image colors initialization failed"); /* If we have a CIE based color space and the icc equivalent profile is not yet set, go ahead and handle that now. It may already be done due to the above init_colors which may go through remap. */ if (gs_color_space_is_PSCIE(pcs) && pcs->icc_equivalent == NULL) { code = gs_colorspace_set_icc_equivalent((gs_color_space *)pcs, &(penum->icc_setup.is_lab), pgs->memory); if (code < 0) return code; if (penum->icc_setup.is_lab) { /* Free what ever profile was created and use the icc manager's cielab profile */ gs_color_space *curr_pcs = (gs_color_space *)pcs; rc_decrement(curr_pcs->icc_equivalent,"gx_image_enum_begin"); rc_decrement(curr_pcs->cmm_icc_profile_data,"gx_image_enum_begin"); curr_pcs->cmm_icc_profile_data = pgs->icc_manager->lab_profile; rc_increment(curr_pcs->cmm_icc_profile_data); } } /* Try to transform non-default RasterOps to something */ /* that we implement less expensively. */ if (!pim->CombineWithColor) lop = rop3_know_T_0(lop) & ~lop_T_transparent; else if ((rop3_uses_T(lop) && color_draws_b_w(dev, pdcolor) == 0)) lop = rop3_know_T_0(lop); if (lop != rop3_S && /* if best case, no more work needed */ !rop3_uses_T(lop) && bps == 1 && spp == 1 && (b_w_color = color_draws_b_w(dev, penum->icolor0)) >= 0 && color_draws_b_w(dev, penum->icolor1) == (b_w_color ^ 1) ) { if (b_w_color) { /* Swap the colors and invert the RasterOp source. */ gx_device_color dcolor; dcolor = *(penum->icolor0); *(penum->icolor0) = *(penum->icolor1); *(penum->icolor1) = dcolor; lop = rop3_invert_S(lop); } /* * At this point, we know that the source pixels * correspond directly to the S input for the raster op, * i.e., icolor0 is black and icolor1 is white. */ switch (lop) { case rop3_D & rop3_S: /* Implement this as an inverted mask writing 0s. */ *(penum->icolor1) = *(penum->icolor0); /* (falls through) */ case rop3_D | rop3_not(rop3_S): /* Implement this as an inverted mask writing 1s. */ memcpy(&penum->map[0].table.lookup4x1to32[0], lookup4x1to32_inverted, 16 * 4); rmask: /* Fill in the remaining parameters for a mask. */ penum->masked = masked = true; set_nonclient_dev_color(penum->icolor0, gx_no_color_index); penum->map[0].decoding = sd_none; lop = rop3_T; break; case rop3_D & rop3_not(rop3_S): /* Implement this as a mask writing 0s. */ *(penum->icolor1) = *(penum->icolor0); /* (falls through) */ case rop3_D | rop3_S: /* Implement this as a mask writing 1s. */ memcpy(&penum->map[0].table.lookup4x1to32[0], lookup4x1to32_identity, 16 * 4); goto rmask; default: ; } } } penum->device_color = device_color; /* * Adjust width upward for unpacking up to 7 trailing bits in * the row, plus 1 byte for end-of-run, plus up to 7 leading * bits for data_x offset within a packed byte. */ bsize = ((bps > 8 ? width * 2 : width) + 15) * spp; buffer = gs_alloc_bytes(mem, bsize, "image buffer"); if (buffer == 0) { return_error(gs_error_VMerror); } penum->bps = bps; penum->unpack_bps = bps; penum->log2_xbytes = log2_xbytes; penum->spp = spp; switch (format) { case gs_image_format_chunky: nplanes = 1; spread = 1 << log2_xbytes; break; case gs_image_format_component_planar: nplanes = spp; spread = spp << log2_xbytes; break; case gs_image_format_bit_planar: nplanes = spp * bps; spread = spp << log2_xbytes; break; default: /* No other cases are possible (checked by gx_image_enum_alloc). */ return_error(gs_error_Fatal); } penum->num_planes = nplanes; penum->spread = spread; /* * If we're asked to interpolate in a partial image, we have to * assume that the client either really only is interested in * the given sub-image, or else is constructing output out of * overlapping pieces. */ penum->interpolate = force_interpolation ? interp_force : pim->Interpolate ? interp_on : interp_off; penum->x_extent = x_extent; penum->y_extent = y_extent; penum->posture = ((x_extent.y | y_extent.x) == 0 ? image_portrait : (x_extent.x | y_extent.y) == 0 ? image_landscape : image_skewed); penum->pgs = pgs; penum->pcs = pcs; penum->memory = mem; penum->buffer = buffer; penum->buffer_size = bsize; penum->line = 0; penum->icc_link = NULL; penum->color_cache = NULL; penum->ht_buffer = NULL; penum->thresh_buffer = NULL; penum->use_cie_range = false; penum->line_size = 0; penum->use_rop = lop != (masked ? rop3_T : rop3_S); #ifdef DEBUG if (gs_debug_c('*')) { if (penum->use_rop) dmprintf1(mem, "[%03x]", lop); dmprintf5(mem, "%c%d%c%dx%d ", (masked ? (color_is_pure(pdcolor) ? 'm' : 'h') : 'i'), bps, (penum->posture == image_portrait ? ' ' : penum->posture == image_landscape ? 'L' : 'T'), width, height); } #endif penum->slow_loop = 0; if (pcpath == 0) { (*dev_proc(dev, get_clipping_box)) (dev, &obox); cbox = obox; penum->clip_image = 0; } else penum->clip_image = (gx_cpath_outer_box(pcpath, &obox) | /* not || */ gx_cpath_inner_box(pcpath, &cbox) ? 0 : image_clip_region); penum->clip_outer = obox; penum->clip_inner = cbox; penum->log_op = rop3_T; /* rop device takes care of this */ penum->clip_dev = 0; /* in case we bail out */ penum->rop_dev = 0; /* ditto */ penum->scaler = 0; /* ditto */ /* * If all four extrema of the image fall within the clipping * rectangle, clipping is never required. When making this check, * we must carefully take into account the fact that we only care * about pixel centers. */ { fixed epx = min(row_extent.x, 0) + min(col_extent.x, 0), eqx = max(row_extent.x, 0) + max(col_extent.x, 0), epy = min(row_extent.y, 0) + min(col_extent.y, 0), eqy = max(row_extent.y, 0) + max(col_extent.y, 0); { int hwx, hwy; switch (penum->posture) { case image_portrait: hwx = width, hwy = height; break; case image_landscape: hwx = height, hwy = width; break; default: hwx = hwy = 0; } /* * If the image is only 1 sample wide or high, * and is less than 1 device pixel wide or high, * move it slightly so that it covers pixel centers. * This is a hack to work around a bug in some old * versions of TeX/dvips, which use 1-bit-high images * to draw horizontal and vertical lines without * positioning them properly. */ if (hwx == 1 && eqx - epx < fixed_1) { fixed diff = arith_rshift_1(row_extent.x + col_extent.x); mtx = (((mtx + diff) | fixed_half) & -fixed_half) - diff; } if (hwy == 1 && eqy - epy < fixed_1) { fixed diff = arith_rshift_1(row_extent.y + col_extent.y); mty = (((mty + diff) | fixed_half) & -fixed_half) - diff; } } if_debug5m('b', mem, "[b]Image: %sspp=%d, bps=%d, mt=(%g,%g)\n", (masked? "masked, " : ""), spp, bps, fixed2float(mtx), fixed2float(mty)); if_debug9m('b', mem, "[b] cbox=(%g,%g),(%g,%g), obox=(%g,%g),(%g,%g), clip_image=0x%x\n", fixed2float(cbox.p.x), fixed2float(cbox.p.y), fixed2float(cbox.q.x), fixed2float(cbox.q.y), fixed2float(obox.p.x), fixed2float(obox.p.y), fixed2float(obox.q.x), fixed2float(obox.q.y), penum->clip_image); /* These DDAs enumerate the starting position of each source pixel * row in device space. */ dda_init(penum->dda.row.x, mtx, col_extent.x, height); dda_init(penum->dda.row.y, mty, col_extent.y, height); if (penum->posture == image_portrait) { penum->dst_width = row_extent.x; penum->dst_height = col_extent.y; } else { penum->dst_width = col_extent.x; penum->dst_height = row_extent.y; } /* For gs_image_class_0_interpolate. */ penum->yi0 = fixed2int_pixround_perfect(dda_current(penum->dda.row.y)); /* For gs_image_class_0_interpolate. */ if (penum->rect.y) { int y = penum->rect.y; while (y--) { dda_next(penum->dda.row.x); dda_next(penum->dda.row.y); } } penum->cur.x = penum->prev.x = dda_current(penum->dda.row.x); penum->cur.y = penum->prev.y = dda_current(penum->dda.row.y); /* These DDAs enumerate the starting positions of each row of our * source pixel data, in the subrectangle ('strip') that we are * actually rendering. */ dda_init(penum->dda.strip.x, penum->cur.x, row_extent.x, width); dda_init(penum->dda.strip.y, penum->cur.y, row_extent.y, width); if (penum->rect.x) { dda_advance(penum->dda.strip.x, penum->rect.x); dda_advance(penum->dda.strip.y, penum->rect.x); } { fixed ox = dda_current(penum->dda.strip.x); fixed oy = dda_current(penum->dda.strip.y); if (!penum->clip_image) /* i.e., not clip region */ penum->clip_image = (fixed_pixround(ox + epx) < fixed_pixround(cbox.p.x) ? image_clip_xmin : 0) + (fixed_pixround(ox + eqx) >= fixed_pixround(cbox.q.x) ? image_clip_xmax : 0) + (fixed_pixround(oy + epy) < fixed_pixround(cbox.p.y) ? image_clip_ymin : 0) + (fixed_pixround(oy + eqy) >= fixed_pixround(cbox.q.y) ? image_clip_ymax : 0); } } penum->y = 0; penum->used.x = 0; penum->used.y = 0; { static sample_unpack_proc_t procs[2][6] = { { sample_unpack_1, sample_unpack_2, sample_unpack_4, sample_unpack_8, sample_unpack_12, sample_unpack_16 }, { sample_unpack_1_interleaved, sample_unpack_2_interleaved, sample_unpack_4_interleaved, sample_unpack_8_interleaved, sample_unpack_12, sample_unpack_16 }}; int num_planes = penum->num_planes; bool interleaved = (num_planes == 1 && penum->plane_depths[0] != penum->bps); int i; if (interleaved) { int num_components = penum->plane_depths[0] / penum->bps; for (i = 1; i < num_components; i++) { if (decode[0] != decode[i * 2 + 0] || decode[1] != decode[i * 2 + 1]) break; } if (i == num_components) interleaved = false; /* Use single table. */ } penum->unpack = procs[interleaved][index_bps]; if_debug1m('b', mem, "[b]unpack=%d\n", bps); /* Set up pixel0 for image class procedures. */ penum->dda.pixel0 = penum->dda.strip; for (i = 0; i < gx_image_class_table_count; ++i) if ((penum->render = gx_image_class_table[i](penum)) != 0) break; if (i == gx_image_class_table_count) { /* No available class can handle this image. */ gx_default_end_image(dev, (gx_image_enum_common_t *) penum, false); return_error(gs_error_rangecheck); } } if (penum->clip_image && pcpath) { /* Set up the clipping device. */ gx_device_clip *cdev = gs_alloc_struct(mem, gx_device_clip, &st_device_clip, "image clipper"); if (cdev == 0) { gx_default_end_image(dev, (gx_image_enum_common_t *) penum, false); return_error(gs_error_VMerror); } gx_make_clip_device_in_heap(cdev, pcpath, dev, mem); penum->clip_dev = cdev; } if (penum->use_rop) { /* Set up the RasterOp source device. */ gx_device_rop_texture *rtdev; code = gx_alloc_rop_texture_device(&rtdev, mem, "image RasterOp"); if (code < 0) { gx_default_end_image(dev, (gx_image_enum_common_t *) penum, false); return code; } /* The 'target' must not be NULL for gx_make_rop_texture_device */ if (!penum->clip_dev && !dev) return_error(gs_error_undefined); gx_make_rop_texture_device(rtdev, (penum->clip_dev != 0 ? (gx_device *) penum->clip_dev : dev), lop, pdcolor); gx_device_retain((gx_device *)rtdev, true); penum->rop_dev = rtdev; } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'Fix bug 697459 Buffer overflow in fill_threshold_buffer There was an overflow check for ht_buffer size, but none for the larger threshold_buffer. Note that this file didn't fail on Windows because the combination of the ht_buffer and the size of the (miscalculated due to overflow) threshold_buffer would have exceeded the 2Gb limit.'</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 WritePNMImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { char buffer[MagickPathExtent], format, magick[MagickPathExtent]; const char *value; MagickBooleanType status; MagickOffsetType scene; Quantum index; QuantumAny pixel; QuantumInfo *quantum_info; QuantumType quantum_type; register unsigned char *pixels, *q; size_t extent, packet_size; ssize_t count, y; /* 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); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); scene=0; do { QuantumAny max_value; /* Write PNM file header. */ packet_size=3; quantum_type=RGBQuantum; (void) CopyMagickString(magick,image_info->magick,MagickPathExtent); max_value=GetQuantumRange(image->depth); switch (magick[1]) { case 'A': case 'a': { format='7'; break; } case 'B': case 'b': { format='4'; if (image_info->compression == NoCompression) format='1'; break; } case 'F': case 'f': { format='F'; if (SetImageGray(image,exception) != MagickFalse) format='f'; break; } case 'G': case 'g': { format='5'; if (image_info->compression == NoCompression) format='2'; break; } case 'N': case 'n': { if ((image_info->type != TrueColorType) && (SetImageGray(image,exception) != MagickFalse)) { format='5'; if (image_info->compression == NoCompression) format='2'; if (SetImageMonochrome(image,exception) != MagickFalse) { format='4'; if (image_info->compression == NoCompression) format='1'; } break; } } default: { format='6'; if (image_info->compression == NoCompression) format='3'; break; } } (void) FormatLocaleString(buffer,MagickPathExtent,"P%c\n",format); (void) WriteBlobString(image,buffer); value=GetImageProperty(image,"comment",exception); if (value != (const char *) NULL) { register const char *p; /* Write comments to file. */ (void) WriteBlobByte(image,'#'); for (p=value; *p != '\0'; p++) { (void) WriteBlobByte(image,(unsigned char) *p); if ((*p == '\n') || (*p == '\r')) (void) WriteBlobByte(image,'#'); } (void) WriteBlobByte(image,'\n'); } if (format != '7') { (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g %.20g\n", (double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); } else { char type[MagickPathExtent]; /* PAM header. */ (void) FormatLocaleString(buffer,MagickPathExtent, "WIDTH %.20g\nHEIGHT %.20g\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); quantum_type=GetQuantumType(image,exception); switch (quantum_type) { case CMYKQuantum: case CMYKAQuantum: { packet_size=4; (void) CopyMagickString(type,"CMYK",MagickPathExtent); break; } case GrayQuantum: case GrayAlphaQuantum: { packet_size=1; (void) CopyMagickString(type,"GRAYSCALE",MagickPathExtent); if (IsImageMonochrome(image) != MagickFalse) (void) CopyMagickString(type,"BLACKANDWHITE",MagickPathExtent); break; } default: { quantum_type=RGBQuantum; if (image->alpha_trait != UndefinedPixelTrait) quantum_type=RGBAQuantum; packet_size=3; (void) CopyMagickString(type,"RGB",MagickPathExtent); break; } } if (image->alpha_trait != UndefinedPixelTrait) { packet_size++; (void) ConcatenateMagickString(type,"_ALPHA",MagickPathExtent); } if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent, "DEPTH %.20g\nMAXVAL %.20g\n",(double) packet_size,(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MagickPathExtent, "TUPLTYPE %s\nENDHDR\n",type); (void) WriteBlobString(image,buffer); } /* Convert runextent encoded to PNM raster pixels. */ switch (format) { case '1': { unsigned char pixels[2048]; /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(unsigned char) (GetPixelLuma(image,p) >= (QuantumRange/2.0) ? '0' : '1'); *q++=' '; if ((q-pixels+1) >= (ssize_t) sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '2': { unsigned char pixels[2048]; /* Convert image to a PGM image. */ if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=ClampToQuantum(GetPixelLuma(image,p)); if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent,"%u ", ScaleQuantumToChar(index)); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToShort(index)); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u ",ScaleQuantumToLong(index)); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '3': { unsigned char pixels[2048]; /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth <= 8) (void) WriteBlobString(image,"255\n"); else if (image->depth <= 16) (void) WriteBlobString(image,"65535\n"); else (void) WriteBlobString(image,"4294967295\n"); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if (image->depth <= 8) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToChar(GetPixelRed(image,p)), ScaleQuantumToChar(GetPixelGreen(image,p)), ScaleQuantumToChar(GetPixelBlue(image,p))); else if (image->depth <= 16) count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToShort(GetPixelRed(image,p)), ScaleQuantumToShort(GetPixelGreen(image,p)), ScaleQuantumToShort(GetPixelBlue(image,p))); else count=(ssize_t) FormatLocaleString(buffer,MagickPathExtent, "%u %u %u ",ScaleQuantumToLong(GetPixelRed(image,p)), ScaleQuantumToLong(GetPixelGreen(image,p)), ScaleQuantumToLong(GetPixelBlue(image,p))); extent=(size_t) count; (void) strncpy((char *) q,buffer,extent); q+=extent; if ((q-pixels+extent+1) >= sizeof(pixels)) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p+=GetPixelChannels(image); } *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case '4': { /* Convert image to a PBM image. */ (void) SetImageType(image,BilevelType,exception); image->depth=1; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '5': { /* Convert image to a PGM image. */ if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); quantum_info->min_is_white=MagickTrue; pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,GrayQuantum); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, GrayQuantum,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); else { if (image->depth == 8) pixel=ScaleQuantumToChar(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); else { if (image->depth == 16) pixel=ScaleQuantumToShort(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p), max_value); } q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { if (IsPixelGray(image,p) == MagickFalse) pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image,p)), max_value); else { if (image->depth == 16) pixel=ScaleQuantumToLong(GetPixelRed(image,p)); else pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); } q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '6': { /* Convert image to a PNM image. */ (void) TransformImageColorspace(image,sRGBColorspace,exception); if (image->depth > 32) image->depth=32; (void) FormatLocaleString(buffer,MagickPathExtent,"%.20g\n",(double) ((MagickOffsetType) GetQuantumRange(image->depth))); (void) WriteBlobString(image,buffer); quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); extent=GetQuantumExtent(image,quantum_info,quantum_type); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); p+=GetPixelChannels(image); } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case '7': { /* Convert image to a PAM. */ if (image->depth > 32) image->depth=32; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); (void) SetQuantumEndian(image,quantum_info,MSBEndian); pixels=GetQuantumPixels(quantum_info); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; q=pixels; switch (image->depth) { case 8: case 16: case 32: { extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); break; } default: { switch (quantum_type) { case GrayQuantum: case GrayAlphaQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma( image,p)),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(ClampToQuantum(GetPixelLuma(image, p)),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=(unsigned char) ScaleQuantumToAny( GetPixelAlpha(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } case CMYKQuantum: case CMYKAQuantum: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlack(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } default: { if (image->depth <= 8) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopCharPixel((unsigned char) pixel,q); } p+=GetPixelChannels(image); } break; } if (image->depth <= 16) { for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopShortPixel(MSBEndian,(unsigned short) pixel,q); } p+=GetPixelChannels(image); } break; } for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToAny(GetPixelRed(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelGreen(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); pixel=ScaleQuantumToAny(GetPixelBlue(image,p),max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); if (image->alpha_trait != UndefinedPixelTrait) { pixel=ScaleQuantumToAny(GetPixelAlpha(image,p), max_value); q=PopLongPixel(MSBEndian,(unsigned int) pixel,q); } p+=GetPixelChannels(image); } break; } } extent=(size_t) (q-pixels); break; } } count=WriteBlob(image,extent,pixels); if (count != (ssize_t) extent) break; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } case 'F': case 'f': { (void) WriteBlobString(image,image->endian == LSBEndian ? "-1.0\n" : "1.0\n"); image->depth=32; quantum_type=format == 'f' ? GrayQuantum : RGBQuantum; quantum_info=AcquireQuantumInfo(image_info,image); if (quantum_info == (QuantumInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); status=SetQuantumFormat(image,quantum_info,FloatingPointQuantumFormat); if (status == MagickFalse) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); pixels=GetQuantumPixels(quantum_info); for (y=(ssize_t) image->rows-1; y >= 0; y--) { register const Quantum *magick_restrict p; p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; extent=ExportQuantumPixels(image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); (void) WriteBlob(image,extent,pixels); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } quantum_info=DestroyQuantumInfo(quantum_info); break; } } if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); 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-20'], 'message': 'https://github.com/ImageMagick/ImageMagick/issues/415'</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 install_thread_keyring_to_cred(struct cred *new) { struct key *keyring; keyring = keyring_alloc("_tid", new->uid, new->gid, new, KEY_POS_ALL | KEY_USR_VIEW, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); new->thread_keyring = keyring; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-404'], 'message': 'KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings This fixes CVE-2017-7472. Running the following program as an unprivileged user exhausts kernel memory by leaking thread keyrings: #include <keyutils.h> int main() { for (;;) keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING); } Fix it by only creating a new thread keyring if there wasn't one before. To make things more consistent, make install_thread_keyring_to_cred() and install_process_keyring_to_cred() both return 0 if the corresponding keyring is already present. Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials") Cc: [email protected] # 2.6.29+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]>'</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 install_process_keyring_to_cred(struct cred *new) { struct key *keyring; if (new->process_keyring) return -EEXIST; keyring = keyring_alloc("_pid", new->uid, new->gid, new, KEY_POS_ALL | KEY_USR_VIEW, KEY_ALLOC_QUOTA_OVERRUN, NULL, NULL); if (IS_ERR(keyring)) return PTR_ERR(keyring); new->process_keyring = keyring; return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-404'], 'message': 'KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings This fixes CVE-2017-7472. Running the following program as an unprivileged user exhausts kernel memory by leaking thread keyrings: #include <keyutils.h> int main() { for (;;) keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING); } Fix it by only creating a new thread keyring if there wasn't one before. To make things more consistent, make install_thread_keyring_to_cred() and install_process_keyring_to_cred() both return 0 if the corresponding keyring is already present. Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials") Cc: [email protected] # 2.6.29+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]>'</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 keyctl_set_reqkey_keyring(int reqkey_defl) { struct cred *new; int ret, old_setting; old_setting = current_cred_xxx(jit_keyring); if (reqkey_defl == KEY_REQKEY_DEFL_NO_CHANGE) return old_setting; new = prepare_creds(); if (!new) return -ENOMEM; switch (reqkey_defl) { case KEY_REQKEY_DEFL_THREAD_KEYRING: ret = install_thread_keyring_to_cred(new); if (ret < 0) goto error; goto set; case KEY_REQKEY_DEFL_PROCESS_KEYRING: ret = install_process_keyring_to_cred(new); if (ret < 0) { if (ret != -EEXIST) goto error; ret = 0; } goto set; case KEY_REQKEY_DEFL_DEFAULT: case KEY_REQKEY_DEFL_SESSION_KEYRING: case KEY_REQKEY_DEFL_USER_KEYRING: case KEY_REQKEY_DEFL_USER_SESSION_KEYRING: case KEY_REQKEY_DEFL_REQUESTOR_KEYRING: goto set; case KEY_REQKEY_DEFL_NO_CHANGE: case KEY_REQKEY_DEFL_GROUP_KEYRING: default: ret = -EINVAL; goto error; } set: new->jit_keyring = reqkey_defl; commit_creds(new); return old_setting; error: abort_creds(new); return ret; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-399', 'CWE-404'], 'message': 'KEYS: fix keyctl_set_reqkey_keyring() to not leak thread keyrings This fixes CVE-2017-7472. Running the following program as an unprivileged user exhausts kernel memory by leaking thread keyrings: #include <keyutils.h> int main() { for (;;) keyctl_set_reqkey_keyring(KEY_REQKEY_DEFL_THREAD_KEYRING); } Fix it by only creating a new thread keyring if there wasn't one before. To make things more consistent, make install_thread_keyring_to_cred() and install_process_keyring_to_cred() both return 0 if the corresponding keyring is already present. Fixes: d84f4f992cbd ("CRED: Inaugurate COW credentials") Cc: [email protected] # 2.6.29+ Signed-off-by: Eric Biggers <[email protected]> Signed-off-by: David Howells <[email protected]>'</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 local_name_to_path(FsContext *ctx, V9fsPath *dir_path, const char *name, V9fsPath *target) { if (dir_path) { v9fs_path_sprintf(target, "%s/%s", dir_path->data, name); } else { v9fs_path_sprintf(target, "%s", name); } return 0; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-732'], 'message': '9pfs: local: set the path of the export root to "." The local backend was recently converted to using "at*()" syscalls in order to ensure all accesses happen below the shared directory. This requires that we only pass relative paths, otherwise the dirfd argument to the "at*()" syscalls is ignored and the path is treated as an absolute path in the host. This is actually the case for paths in all fids, with the notable exception of the root fid, whose path is "/". This causes the following backend ops to act on the "/" directory of the host instead of the virtfs shared directory when the export root is involved: - lstat - chmod - chown - utimensat ie, chmod /9p_mount_point in the guest will be converted to chmod / in the host for example. This could cause security issues with a privileged QEMU. All "*at()" syscalls are being passed an open file descriptor. In the case of the export root, this file descriptor points to the path in the host that was passed to -fsdev. The fix is thus as simple as changing the path of the export root fid to be "." instead of "/". This is CVE-2017-7471. Cc: [email protected] Reported-by: Léo Gaspard <[email protected]> Signed-off-by: Greg Kurz <[email protected]> Reviewed-by: Eric Blake <[email protected]> Signed-off-by: Peter Maydell <[email protected]>'</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: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_8)(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { int x,y; uint8_t p; dstpitch -= bltwidth; srcpitch -= bltwidth; for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x++) { p = *dst; ROP_OP(&p, *src); if (p != s->vga.gr[0x34]) *dst = p; dst++; src++; } dst += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-125'], 'message': 'fix :cirrus_vga fix OOB read case qemu Segmentation fault check the validity of parameters in cirrus_bitblt_rop_fwd_transp_xxx and cirrus_bitblt_rop_fwd_xxx to avoid the OOB read which causes qemu Segmentation fault. After the fix, we will touch the assert in cirrus_invalidate_region: assert(off_cur_end >= off_cur); Signed-off-by: fangying <[email protected]> Signed-off-by: hangaohuai <[email protected]> Message-id: [email protected] Signed-off-by: Gerd Hoffmann <[email protected]>'</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 *enl_ipc_get(const char *msg_data) { static char *message = NULL; static unsigned short len = 0; char buff[13], *ret_msg = NULL; register unsigned char i; unsigned char blen; if (msg_data == IPC_TIMEOUT) { return(IPC_TIMEOUT); } for (i = 0; i < 12; i++) { buff[i] = msg_data[i]; } buff[12] = 0; blen = strlen(buff); if (message != NULL) { len += blen; message = (char *) erealloc(message, len + 1); strcat(message, buff); } else { len = blen; message = (char *) emalloc(len + 1); strcpy(message, buff); } if (blen < 12) { ret_msg = message; message = NULL; D(("Received complete reply: \"%s\"\n", ret_msg)); } return(ret_msg); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-61', 'CWE-787'], 'message': 'Fix double-free/OOB-write while receiving IPC data If a malicious client pretends to be the E17 window manager, it is possible to trigger an out of boundary heap write while receiving an IPC message. The length of the already received message is stored in an unsigned short, which overflows after receiving 64 KB of data. It's comparably small amount of data and therefore achievable for an attacker. When len overflows, realloc() will either be called with a small value and therefore chars will be appended out of bounds, or len + 1 will be exactly 0, in which case realloc() behaves like free(). This could be abused for a later double-free attack as it's even possible to overwrite the free information -- but this depends on the malloc implementation. Signed-off-by: Tobias Stoeckmann <[email protected]>'</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 cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop) { cirrus_fill_t rop_func; if (blit_is_unsafe(s, true)) { return 0; } rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1]; rop_func(s, s->vga.vram_ptr + s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_bitblt_reset(s); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_8)(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { int x,y; uint8_t p; dstpitch -= bltwidth; srcpitch -= bltwidth; if (bltheight > 1 && (dstpitch < 0 || srcpitch < 0)) { return; } for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x++) { p = *dst; ROP_OP(&p, *src); if (p != s->vga.gr[0x34]) *dst = p; dst++; src++; } dst += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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 void glue(rop_32_,ROP_NAME)(uint32_t *dst, uint32_t src) { *dst = ROP_FN(*dst, src); } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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 cirrus_bitblt_common_patterncopy(CirrusVGAState *s, bool videosrc) { uint32_t patternsize; uint8_t *dst; uint8_t *src; dst = s->vga.vram_ptr + s->cirrus_blt_dstaddr; if (videosrc) { switch (s->vga.get_bpp(&s->vga)) { case 8: patternsize = 64; break; case 15: case 16: patternsize = 128; break; case 24: case 32: default: patternsize = 256; break; } s->cirrus_blt_srcaddr &= ~(patternsize - 1); if (s->cirrus_blt_srcaddr + patternsize > s->vga.vram_size) { return 0; } src = s->vga.vram_ptr + s->cirrus_blt_srcaddr; } else { src = s->cirrus_bltbuf; } if (blit_is_unsafe(s, true)) { return 0; } (*s->cirrus_rop) (s, dst, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: (CirrusVGAState * s, uint8_t * dst, const uint8_t * src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { uint8_t *d; int x, y; unsigned bits, bits_xor; unsigned int col; unsigned bitmask; unsigned index; #if DEPTH == 24 int dstskipleft = s->vga.gr[0x2f] & 0x1f; int srcskipleft = dstskipleft / 3; #else int srcskipleft = s->vga.gr[0x2f] & 0x07; int dstskipleft = srcskipleft * (DEPTH / 8); #endif if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_COLOREXPINV) { bits_xor = 0xff; col = s->cirrus_blt_bgcol; } else { bits_xor = 0x00; col = s->cirrus_blt_fgcol; } for(y = 0; y < bltheight; y++) { bitmask = 0x80 >> srcskipleft; bits = *src++ ^ bits_xor; d = dst + dstskipleft; for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) { if ((bitmask & 0xff) == 0) { bitmask = 0x80; bits = *src++ ^ bits_xor; } index = (bits & bitmask); if (index) { PUTPIXEL(); } d += (DEPTH / 8); bitmask >>= 1; } dst += dstpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: glue(glue(cirrus_bitblt_rop_bkwd_transp_, ROP_NAME),_16)(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { int x,y; uint8_t p1, p2; dstpitch += bltwidth; srcpitch += bltwidth; for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x+=2) { p1 = *(dst-1); p2 = *dst; ROP_OP(&p1, *(src - 1)); ROP_OP(&p2, *src); if ((p1 != s->vga.gr[0x34]) || (p2 != s->vga.gr[0x35])) { *(dst-1) = p1; *dst = p2; } dst-=2; src-=2; } dst += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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 cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h) { int sx = 0, sy = 0; int dx = 0, dy = 0; int depth = 0; int notify = 0; /* make sure to only copy if it's a plain copy ROP */ if (*s->cirrus_rop == cirrus_bitblt_rop_fwd_src || *s->cirrus_rop == cirrus_bitblt_rop_bkwd_src) { int width, height; depth = s->vga.get_bpp(&s->vga) / 8; if (!depth) { return 0; } s->vga.get_resolution(&s->vga, &width, &height); /* extra x, y */ sx = (src % ABS(s->cirrus_blt_srcpitch)) / depth; sy = (src / ABS(s->cirrus_blt_srcpitch)); dx = (dst % ABS(s->cirrus_blt_dstpitch)) / depth; dy = (dst / ABS(s->cirrus_blt_dstpitch)); /* normalize width */ w /= depth; /* if we're doing a backward copy, we have to adjust our x/y to be the upper left corner (instead of the lower right corner) */ if (s->cirrus_blt_dstpitch < 0) { sx -= (s->cirrus_blt_width / depth) - 1; dx -= (s->cirrus_blt_width / depth) - 1; sy -= s->cirrus_blt_height - 1; dy -= s->cirrus_blt_height - 1; } /* are we in the visible portion of memory? */ if (sx >= 0 && sy >= 0 && dx >= 0 && dy >= 0 && (sx + w) <= width && (sy + h) <= height && (dx + w) <= width && (dy + h) <= height) { notify = 1; } } (*s->cirrus_rop) (s, s->vga.vram_ptr + s->cirrus_blt_dstaddr, s->vga.vram_ptr + s->cirrus_blt_srcaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch, s->cirrus_blt_width, s->cirrus_blt_height); if (notify) { dpy_gfx_update(s->vga.con, dx, dy, s->cirrus_blt_width / depth, s->cirrus_blt_height); } /* we don't have to notify the display that this portion has changed since qemu_console_copy implies this */ cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: glue(cirrus_bitblt_rop_bkwd_, ROP_NAME)(CirrusVGAState *s, uint8_t *dst,const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { int x,y; dstpitch += bltwidth; srcpitch += bltwidth; for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x++) { ROP_OP(dst, *src); dst--; src--; } dst += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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 cirrus_bitblt_fill_nop(CirrusVGAState *s, uint8_t *dst, int dstpitch, int bltwidth,int bltheight) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: (CirrusVGAState * s, uint8_t * dst, const uint8_t * src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { uint8_t *d; int x, y, bitpos, pattern_y; unsigned int bits, bits_xor; unsigned int col; #if DEPTH == 24 int dstskipleft = s->vga.gr[0x2f] & 0x1f; int srcskipleft = dstskipleft / 3; #else int srcskipleft = s->vga.gr[0x2f] & 0x07; int dstskipleft = srcskipleft * (DEPTH / 8); #endif if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_COLOREXPINV) { bits_xor = 0xff; col = s->cirrus_blt_bgcol; } else { bits_xor = 0x00; col = s->cirrus_blt_fgcol; } pattern_y = s->cirrus_blt_srcaddr & 7; for(y = 0; y < bltheight; y++) { bits = src[pattern_y] ^ bits_xor; bitpos = 7 - srcskipleft; d = dst + dstskipleft; for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) { if ((bits >> bitpos) & 1) { PUTPIXEL(); } d += (DEPTH / 8); bitpos = (bitpos - 1) & 7; } pattern_y = (pattern_y + 1) & 7; dst += dstpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: (CirrusVGAState * s, uint8_t * dst, const uint8_t * src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { uint32_t colors[2]; uint8_t *d; int x, y; unsigned bits; unsigned int col; unsigned bitmask; int srcskipleft = s->vga.gr[0x2f] & 0x07; int dstskipleft = srcskipleft * (DEPTH / 8); colors[0] = s->cirrus_blt_bgcol; colors[1] = s->cirrus_blt_fgcol; for(y = 0; y < bltheight; y++) { bitmask = 0x80 >> srcskipleft; bits = *src++; d = dst + dstskipleft; for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) { if ((bitmask & 0xff) == 0) { bitmask = 0x80; bits = *src++; } col = colors[!!(bits & bitmask)]; PUTPIXEL(); d += (DEPTH / 8); bitmask >>= 1; } dst += dstpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around dst pointers in the blitter Instead pass around the address (aka offset into vga memory). Calculate the pointer in the rop_* functions, after applying the mask to the address, to make sure the address stays within the valid range. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: glue(glue(cirrus_bitblt_rop_bkwd_transp_, ROP_NAME),_8)(CirrusVGAState *s, uint32_t dstaddr, const uint8_t *src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { int x,y; uint8_t transp = s->vga.gr[0x34]; dstpitch += bltwidth; srcpitch += bltwidth; for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x++) { ROP_OP_TR(s, dstaddr, *src, transp); dstaddr--; src--; } dstaddr += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: glue(glue(cirrus_bitblt_rop_fwd_transp_, ROP_NAME),_8)(CirrusVGAState *s, uint32_t dstaddr, const uint8_t *src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { int x,y; uint8_t transp = s->vga.gr[0x34]; dstpitch -= bltwidth; srcpitch -= bltwidth; if (bltheight > 1 && (dstpitch < 0 || srcpitch < 0)) { return; } for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x++) { ROP_OP_TR(s, dstaddr, *src, transp); dstaddr++; src++; } dstaddr += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: glue(glue(cirrus_bitblt_rop_bkwd_transp_, ROP_NAME),_16)(CirrusVGAState *s, uint32_t dstaddr, const uint8_t *src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { int x,y; uint16_t transp = s->vga.gr[0x34] | (uint16_t)s->vga.gr[0x35] << 8; dstpitch += bltwidth; srcpitch += bltwidth; for (y = 0; y < bltheight; y++) { for (x = 0; x < bltwidth; x+=2) { ROP_OP_TR_16(s, dstaddr, *(uint16_t *)src, transp); dstaddr -= 2; src -= 2; } dstaddr += dstpitch; src += srcpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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 cirrus_bitblt_common_patterncopy(CirrusVGAState *s, bool videosrc) { uint32_t patternsize; uint8_t *src; if (videosrc) { switch (s->vga.get_bpp(&s->vga)) { case 8: patternsize = 64; break; case 15: case 16: patternsize = 128; break; case 24: case 32: default: patternsize = 256; break; } s->cirrus_blt_srcaddr &= ~(patternsize - 1); if (s->cirrus_blt_srcaddr + patternsize > s->vga.vram_size) { return 0; } src = s->vga.vram_ptr + s->cirrus_blt_srcaddr; } else { src = s->cirrus_bltbuf; } if (blit_is_unsafe(s, true)) { return 0; } (*s->cirrus_rop) (s, s->cirrus_blt_dstaddr, src, s->cirrus_blt_dstpitch, 0, s->cirrus_blt_width, s->cirrus_blt_height); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, s->cirrus_blt_dstpitch, s->cirrus_blt_width, s->cirrus_blt_height); return 1; } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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 cirrus_bitblt_cputovideo_next(CirrusVGAState * s) { int copy_count; uint8_t *end_ptr; if (s->cirrus_srccounter > 0) { if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) { cirrus_bitblt_common_patterncopy(s, false); the_end: s->cirrus_srccounter = 0; cirrus_bitblt_reset(s); } else { /* at least one scan line */ do { (*s->cirrus_rop)(s, s->cirrus_blt_dstaddr, s->cirrus_bltbuf, 0, 0, s->cirrus_blt_width, 1); cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, 0, s->cirrus_blt_width, 1); s->cirrus_blt_dstaddr += s->cirrus_blt_dstpitch; s->cirrus_srccounter -= s->cirrus_blt_srcpitch; if (s->cirrus_srccounter <= 0) goto the_end; /* more bytes than needed can be transferred because of word alignment, so we keep them for the next line */ /* XXX: keep alignment to speed up transfer */ end_ptr = s->cirrus_bltbuf + s->cirrus_blt_srcpitch; copy_count = s->cirrus_srcptr_end - end_ptr; memmove(s->cirrus_bltbuf, end_ptr, copy_count); s->cirrus_srcptr = s->cirrus_bltbuf + copy_count; s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch; } while (s->cirrus_srcptr >= s->cirrus_srcptr_end); } } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: (CirrusVGAState *s, uint32_t dstaddr, const uint8_t *src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { uint32_t addr; int x, y; unsigned bits, bits_xor; unsigned int col; unsigned bitmask; unsigned index; #if DEPTH == 24 int dstskipleft = s->vga.gr[0x2f] & 0x1f; int srcskipleft = dstskipleft / 3; #else int srcskipleft = s->vga.gr[0x2f] & 0x07; int dstskipleft = srcskipleft * (DEPTH / 8); #endif if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_COLOREXPINV) { bits_xor = 0xff; col = s->cirrus_blt_bgcol; } else { bits_xor = 0x00; col = s->cirrus_blt_fgcol; } for(y = 0; y < bltheight; y++) { bitmask = 0x80 >> srcskipleft; bits = *src++ ^ bits_xor; addr = dstaddr + dstskipleft; for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) { if ((bitmask & 0xff) == 0) { bitmask = 0x80; bits = *src++ ^ bits_xor; } index = (bits & bitmask); if (index) { PUTPIXEL(s, addr, col); } addr += (DEPTH / 8); bitmask >>= 1; } dstaddr += dstpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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: (CirrusVGAState *s, uint32_t dstaddr, const uint8_t *src, int dstpitch, int srcpitch, int bltwidth, int bltheight) { uint32_t colors[2]; uint32_t addr; int x, y; unsigned bits; unsigned int col; unsigned bitmask; int srcskipleft = s->vga.gr[0x2f] & 0x07; int dstskipleft = srcskipleft * (DEPTH / 8); colors[0] = s->cirrus_blt_bgcol; colors[1] = s->cirrus_blt_fgcol; for(y = 0; y < bltheight; y++) { bitmask = 0x80 >> srcskipleft; bits = *src++; addr = dstaddr + dstskipleft; for (x = dstskipleft; x < bltwidth; x += (DEPTH / 8)) { if ((bitmask & 0xff) == 0) { bitmask = 0x80; bits = *src++; } col = colors[!!(bits & bitmask)]; PUTPIXEL(s, addr, col); addr += (DEPTH / 8); bitmask >>= 1; } dstaddr += dstpitch; } } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</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 cirrus_bitblt_rop_nop(CirrusVGAState *s, uint32_t dstaddr, const uint8_t *src, int dstpitch,int srcpitch, int bltwidth,int bltheight) { } ; Sample JSON Format Confermily Expected output: "examples" => "cwe": "xxx"; "message": "xxx" [/INST] 'cwe': ['CWE-119'], 'message': 'cirrus: stop passing around src pointers in the blitter Does basically the same as "cirrus: stop passing around dst pointers in the blitter", just for the src pointer instead of the dst pointer. For the src we have to care about cputovideo blits though and fetch the data from s->cirrus_bltbuf instead of vga memory. The cirrus_src*() helper functions handle that. Signed-off-by: Gerd Hoffmann <[email protected]> Message-id: [email protected]'</s>