From 002e94bff657a195da0f2637bcbb7091e4770dcc Mon Sep 17 00:00:00 2001 From: Chris Smowton Date: Fri, 10 Feb 2017 13:41:12 +0000 Subject: [PATCH 01/67] Factor out fresh symbol generation This code was duplicated in quite a few places. --- src/goto-instrument/code_contracts.cpp | 22 +++--- src/goto-programs/goto_clean_expr.cpp | 28 ++++---- src/goto-programs/goto_convert.cpp | 24 +++---- src/goto-programs/goto_convert_class.h | 2 +- .../remove_function_pointers.cpp | 45 +++--------- src/goto-programs/remove_instanceof.cpp | 22 +++--- src/java_bytecode/java_object_factory.cpp | 72 +++++++++++-------- src/java_bytecode/java_object_factory.h | 2 + src/util/Makefile | 1 + src/util/fresh_symbol.cpp | 62 ++++++++++++++++ src/util/fresh_symbol.h | 27 +++++++ 11 files changed, 187 insertions(+), 120 deletions(-) create mode 100644 src/util/fresh_symbol.cpp create mode 100644 src/util/fresh_symbol.h diff --git a/src/goto-instrument/code_contracts.cpp b/src/goto-instrument/code_contracts.cpp index b82ecc35bd9..46914d78fb0 100644 --- a/src/goto-instrument/code_contracts.cpp +++ b/src/goto-instrument/code_contracts.cpp @@ -9,6 +9,7 @@ Date: February 2016 \*******************************************************************/ #include +#include #include #include @@ -291,20 +292,13 @@ const symbolt &code_contractst::new_tmp_symbol( const typet &type, const source_locationt &source_location) { - auxiliary_symbolt new_symbol; - new_symbol.type=type; - new_symbol.location=source_location; - - symbolt *symbol_ptr; - - do - { - new_symbol.base_name="tmp_cc$"+std::to_string(++temporary_counter); - new_symbol.name=new_symbol.base_name; - } - while(symbol_table.move(new_symbol, symbol_ptr)); - - return *symbol_ptr; + return get_fresh_aux_symbol( + type, + "", + "tmp_cc", + source_location, + irep_idt(), + symbol_table); } /*******************************************************************\ diff --git a/src/goto-programs/goto_clean_expr.cpp b/src/goto-programs/goto_clean_expr.cpp index 9b5b44a44d9..c7fa8637194 100644 --- a/src/goto-programs/goto_clean_expr.cpp +++ b/src/goto-programs/goto_clean_expr.cpp @@ -6,6 +6,7 @@ Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ +#include #include #include #include @@ -33,24 +34,21 @@ symbol_exprt goto_convertt::make_compound_literal( { const source_locationt source_location=expr.find_source_location(); - auxiliary_symbolt new_symbol; - symbolt *symbol_ptr; - - do - { - new_symbol.base_name="literal$"+std::to_string(++temporary_counter); - new_symbol.name=tmp_symbol_prefix+id2string(new_symbol.base_name); - new_symbol.is_static_lifetime=source_location.get_function().empty(); - new_symbol.value=expr; - new_symbol.type=expr.type(); - new_symbol.location=source_location; - } - while(symbol_table.move(new_symbol, symbol_ptr)); + symbolt &new_symbol= + get_fresh_aux_symbol( + expr.type(), + tmp_symbol_prefix, + "literal", + source_location, + irep_idt(), + symbol_table); + new_symbol.is_static_lifetime=source_location.get_function().empty(); + new_symbol.value=expr; // The value might depend on a variable, thus // generate code for this. - symbol_exprt result=symbol_ptr->symbol_expr(); + symbol_exprt result=new_symbol.symbol_expr(); result.add_source_location()=source_location; // The lifetime of compound literals is really that of @@ -62,7 +60,7 @@ symbol_exprt goto_convertt::make_compound_literal( convert(code_assign, dest); // now create a 'dead' instruction - if(!symbol_ptr->is_static_lifetime) + if(!new_symbol.is_static_lifetime) { code_deadt code_dead(result); targets.destructor_stack.push_back(code_dead); diff --git a/src/goto-programs/goto_convert.cpp b/src/goto-programs/goto_convert.cpp index a3124f3b898..293e2ca8571 100644 --- a/src/goto-programs/goto_convert.cpp +++ b/src/goto-programs/goto_convert.cpp @@ -10,6 +10,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include +#include #include #include #include @@ -2674,24 +2675,21 @@ symbolt &goto_convertt::new_tmp_symbol( goto_programt &dest, const source_locationt &source_location) { - auxiliary_symbolt new_symbol; - symbolt *symbol_ptr; - - do - { - new_symbol.base_name="tmp_"+suffix+"$"+std::to_string(++temporary_counter); - new_symbol.name=tmp_symbol_prefix+id2string(new_symbol.base_name); - new_symbol.type=type; - new_symbol.location=source_location; - } - while(symbol_table.move(new_symbol, symbol_ptr)); + symbolt &new_symbol= + get_fresh_aux_symbol( + type, + tmp_symbol_prefix, + "tmp_"+suffix, + source_location, + irep_idt(), + symbol_table); code_declt decl; - decl.symbol()=symbol_ptr->symbol_expr(); + decl.symbol()=new_symbol.symbol_expr(); decl.add_source_location()=source_location; convert_decl(decl, dest); - return *symbol_ptr; + return new_symbol; } /*******************************************************************\ diff --git a/src/goto-programs/goto_convert_class.h b/src/goto-programs/goto_convert_class.h index feab8197046..997ca676f63 100644 --- a/src/goto-programs/goto_convert_class.h +++ b/src/goto-programs/goto_convert_class.h @@ -32,7 +32,7 @@ class goto_convertt:public messaget symbol_table(_symbol_table), ns(_symbol_table), temporary_counter(0), - tmp_symbol_prefix("goto_convertt::") + tmp_symbol_prefix("goto_convertt") { } diff --git a/src/goto-programs/remove_function_pointers.cpp b/src/goto-programs/remove_function_pointers.cpp index b5dac445fda..3893729a1e1 100644 --- a/src/goto-programs/remove_function_pointers.cpp +++ b/src/goto-programs/remove_function_pointers.cpp @@ -8,6 +8,7 @@ Author: Daniel Kroening, kroening@kroening.com #include +#include #include #include #include @@ -68,8 +69,6 @@ class remove_function_pointerst code_function_callt &function_call, goto_programt &dest); - symbolt &new_tmp_symbol(); - void compute_address_taken_in_symbols( std::set &address_taken) { @@ -110,37 +109,6 @@ remove_function_pointerst::remove_function_pointerst( /*******************************************************************\ -Function: remove_function_pointerst::new_tmp_symbol - - Inputs: - - Outputs: - - Purpose: - -\*******************************************************************/ - -symbolt &remove_function_pointerst::new_tmp_symbol() -{ - static int temporary_counter; - - auxiliary_symbolt new_symbol; - symbolt *symbol_ptr; - - do - { - new_symbol.base_name= - "tmp_return_val$"+std::to_string(++temporary_counter); - new_symbol.name= - "remove_function_pointers::"+id2string(new_symbol.base_name); - } - while(symbol_table.move(new_symbol, symbol_ptr)); - - return *symbol_ptr; -} - -/*******************************************************************\ - Function: remove_function_pointerst::arg_is_type_compatible Inputs: @@ -311,9 +279,14 @@ void remove_function_pointerst::fix_return_type( code_type.return_type(), ns)) return; - symbolt &tmp_symbol=new_tmp_symbol(); - tmp_symbol.type=code_type.return_type(); - tmp_symbol.location=function_call.source_location(); + symbolt &tmp_symbol= + get_fresh_aux_symbol( + code_type.return_type(), + "remove_function_pointers", + "tmp_return_val", + function_call.source_location(), + irep_idt(), + symbol_table); symbol_exprt tmp_symbol_expr; tmp_symbol_expr.type()=tmp_symbol.type; diff --git a/src/goto-programs/remove_instanceof.cpp b/src/goto-programs/remove_instanceof.cpp index ee7f5979332..3fc2699ef47 100644 --- a/src/goto-programs/remove_instanceof.cpp +++ b/src/goto-programs/remove_instanceof.cpp @@ -9,6 +9,7 @@ Author: Chris Smowton, chris.smowton@diffblue.com #include "class_hierarchy.h" #include "class_identifier.h" #include "remove_instanceof.h" +#include #include @@ -20,8 +21,7 @@ class remove_instanceoft goto_functionst &_goto_functions): symbol_table(_symbol_table), ns(_symbol_table), - goto_functions(_goto_functions), - lowered_count(0) + goto_functions(_goto_functions) { class_hierarchy(_symbol_table); } @@ -34,7 +34,6 @@ class remove_instanceoft namespacet ns; class_hierarchyt class_hierarchy; goto_functionst &goto_functions; - int lowered_count; bool lower_instanceof(goto_programt &); @@ -128,15 +127,14 @@ void remove_instanceoft::lower_instanceof( symbol_typet jlo("java::java.lang.Object"); exprt object_clsid=get_class_identifier_field(check_ptr, jlo, ns); - std::ostringstream symname; - symname << "instanceof_tmp::instanceof_tmp" << (++lowered_count); - auxiliary_symbolt newsym; - newsym.name=symname.str(); - newsym.type=object_clsid.type(); - newsym.base_name=newsym.name; - newsym.mode=ID_java; - newsym.is_type=false; - assert(!symbol_table.add(newsym)); + symbolt &newsym= + get_fresh_aux_symbol( + object_clsid.type(), + "instanceof_tmp", + "instanceof_tmp", + source_locationt(), + ID_java, + symbol_table); auto newinst=goto_program.insert_after(this_inst); newinst->make_assignment(); diff --git a/src/java_bytecode/java_object_factory.cpp b/src/java_bytecode/java_object_factory.cpp index b23e419d216..088a25f7038 100644 --- a/src/java_bytecode/java_object_factory.cpp +++ b/src/java_bytecode/java_object_factory.cpp @@ -10,6 +10,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include +#include #include #include #include @@ -107,8 +108,7 @@ exprt java_object_factoryt::allocate_object( bool cast_needed=allocate_type_resolved!=target_type; if(!create_dynamic_objects) { - symbolt &aux_symbol=new_tmp_symbol(symbol_table); - aux_symbol.type=allocate_type; + symbolt &aux_symbol=new_tmp_symbol(symbol_table, loc, allocate_type); aux_symbol.is_static_lifetime=true; exprt object=aux_symbol.symbol_expr(); @@ -136,8 +136,11 @@ exprt java_object_factoryt::allocate_object( // Create a symbol for the malloc expression so we can initialize // without having to do it potentially through a double-deref, which // breaks the to-SSA phase. - symbolt &malloc_sym=new_tmp_symbol(symbol_table, "malloc_site"); - malloc_sym.type=pointer_typet(allocate_type); + symbolt &malloc_sym=new_tmp_symbol( + symbol_table, + loc, + pointer_typet(allocate_type), + "malloc_site"); code_assignt assign=code_assignt(malloc_sym.symbol_expr(), malloc_expr); code_assignt &malloc_assign=assign; malloc_assign.add_source_location()=loc; @@ -211,8 +214,11 @@ void java_object_factoryt::gen_nondet_init( if(!assume_non_null) { auto returns_null_sym= - new_tmp_symbol(symbol_table, "opaque_returns_null"); - returns_null_sym.type=c_bool_typet(1); + new_tmp_symbol( + symbol_table, + loc, + c_bool_typet(1), + "opaque_returns_null"); auto returns_null=returns_null_sym.symbol_expr(); auto assign_returns_null= code_assignt(returns_null, get_nondet_bool(returns_null_sym.type)); @@ -365,8 +371,11 @@ void java_object_factoryt::gen_nondet_array_init( auto max_length_expr=from_integer(max_nondet_array_length, java_int_type()); typet allocate_type; - symbolt &length_sym=new_tmp_symbol(symbol_table, "nondet_array_length"); - length_sym.type=java_int_type(); + symbolt &length_sym=new_tmp_symbol( + symbol_table, + loc, + java_int_type(), + "nondet_array_length"); const auto &length_sym_expr=length_sym.symbol_expr(); // Initialize array with some undetermined length: @@ -400,8 +409,11 @@ void java_object_factoryt::gen_nondet_array_init( // Interpose a new symbol, as the goto-symex stage can't handle array indexing // via a cast. - symbolt &array_init_symbol=new_tmp_symbol(symbol_table, "array_data_init"); - array_init_symbol.type=init_array_expr.type(); + symbolt &array_init_symbol=new_tmp_symbol( + symbol_table, + loc, + init_array_expr.type(), + "array_data_init"); const auto &array_init_symexpr=array_init_symbol.symbol_expr(); codet data_assign=code_assignt(array_init_symexpr, init_array_expr); data_assign.add_source_location()=loc; @@ -409,8 +421,11 @@ void java_object_factoryt::gen_nondet_array_init( // Emit init loop for(array_init_iter=0; array_init_iter!=array.length; // ++array_init_iter) init(array[array_init_iter]); - symbolt &counter=new_tmp_symbol(symbol_table, "array_init_iter"); - counter.type=length_sym_expr.type(); + symbolt &counter=new_tmp_symbol( + symbol_table, + loc, + length_sym_expr.type(), + "array_init_iter"); exprt counter_expr=counter.symbol_expr(); exprt java_zero=from_integer(0, java_int_type()); @@ -512,22 +527,19 @@ Function: new_tmp_symbol \*******************************************************************/ -symbolt &new_tmp_symbol(symbol_tablet &symbol_table, const std::string &prefix) +symbolt &new_tmp_symbol( + symbol_tablet &symbol_table, + const source_locationt &loc, + const typet &type, + const std::string &prefix) { - static size_t temporary_counter=0; // TODO encapsulate as class variable - - auxiliary_symbolt new_symbol; - symbolt *symbol_ptr; - - do - { - new_symbol.name="tmp_object_factory$"+std::to_string(++temporary_counter); - new_symbol.base_name=new_symbol.name; - new_symbol.mode=ID_java; - } - while(symbol_table.move(new_symbol, symbol_ptr)); - - return *symbol_ptr; + return get_fresh_aux_symbol( + type, + "", + prefix, + loc, + ID_java, + symbol_table); } /*******************************************************************\ @@ -572,8 +584,10 @@ exprt object_factory( { if(type.id()==ID_pointer) { - symbolt &aux_symbol=new_tmp_symbol(symbol_table); - aux_symbol.type=type; + symbolt &aux_symbol=new_tmp_symbol( + symbol_table, + loc, + type); aux_symbol.is_static_lifetime=true; exprt object=aux_symbol.symbol_expr(); diff --git a/src/java_bytecode/java_object_factory.h b/src/java_bytecode/java_object_factory.h index d111948e365..6122d3e2780 100644 --- a/src/java_bytecode/java_object_factory.h +++ b/src/java_bytecode/java_object_factory.h @@ -38,6 +38,8 @@ exprt get_nondet_bool(const typet &); symbolt &new_tmp_symbol( symbol_tablet &symbol_table, + const source_locationt &, + const typet &, const std::string &prefix="tmp_object_factory"); #endif // CPROVER_JAVA_BYTECODE_JAVA_OBJECT_FACTORY_H diff --git a/src/util/Makefile b/src/util/Makefile index 6cc42a18fb8..fefabaed3af 100644 --- a/src/util/Makefile +++ b/src/util/Makefile @@ -22,6 +22,7 @@ SRC = arith_tools.cpp base_type.cpp cmdline.cpp config.cpp symbol_table.cpp \ irep_ids.cpp byte_operators.cpp string2int.cpp file_util.cpp \ memory_info.cpp pipe_stream.cpp irep_hash.cpp endianness_map.cpp \ ssa_expr.cpp json_irep.cpp json_expr.cpp \ + fresh_symbol.cpp \ string_utils.cpp INCLUDES= -I .. diff --git a/src/util/fresh_symbol.cpp b/src/util/fresh_symbol.cpp new file mode 100644 index 00000000000..fbe6f09b871 --- /dev/null +++ b/src/util/fresh_symbol.cpp @@ -0,0 +1,62 @@ +/*******************************************************************\ + +Module: Fresh auxiliary symbol creation + +Author: Chris Smowton, chris.smowton@diffblue.com + +\*******************************************************************/ + +#include "fresh_symbol.h" + +/*******************************************************************\ + +Function: get_fresh_aux_symbol + + Inputs: `type`: type of new symbol + `name_prefix`, `basename_prefix`: + new symbol will be named name_prefix::basename_prefix$num + unless name_prefix is empty, in which case the :: prefix + is omitted. + `source_location`: new symbol source loc + `symbol_mode`: new symbol mode + `symbol_table`: table to add the new symbol to + + Outputs: + + Purpose: Installs a fresh-named symbol with the requested name pattern + +\*******************************************************************/ + +symbolt &get_fresh_aux_symbol( + const typet &type, + const std::string &name_prefix, + const std::string &basename_prefix, + const source_locationt &source_location, + const irep_idt &symbol_mode, + symbol_tablet &symbol_table) +{ + static size_t temporary_counter=0; + auxiliary_symbolt new_symbol; + symbolt *symbol_ptr; + + do + { + new_symbol.base_name= + basename_prefix+ + "$"+ + std::to_string(++temporary_counter); + if(name_prefix.empty()) + new_symbol.name=new_symbol.base_name; + else + new_symbol.name= + name_prefix+ + "::"+ + id2string(new_symbol.base_name); + new_symbol.type=type; + new_symbol.location=source_location; + new_symbol.mode=symbol_mode; + } + while(symbol_table.move(new_symbol, symbol_ptr)); + + return *symbol_ptr; +} diff --git a/src/util/fresh_symbol.h b/src/util/fresh_symbol.h new file mode 100644 index 00000000000..c3b2749cbe3 --- /dev/null +++ b/src/util/fresh_symbol.h @@ -0,0 +1,27 @@ +/*******************************************************************\ + +Module: Fresh auxiliary symbol creation + +Author: Chris Smowton, chris.smowton@diffblue.com + +\*******************************************************************/ + +#ifndef CPROVER_UTIL_FRESH_SYMBOL_H +#define CPROVER_UTIL_FRESH_SYMBOL_H + +#include + +#include +#include +#include +#include + +symbolt &get_fresh_aux_symbol( + const typet &type, + const std::string &name_prefix, + const std::string &basename_prefix, + const source_locationt &source_location, + const irep_idt &symbol_mode, + symbol_tablet &symbol_table); + +#endif // CPROVER_UTIL_FRESH_SYMBOL_H From 1134248c10c1d20c13fac8e0334ea9f4d7d995ca Mon Sep 17 00:00:00 2001 From: Daniel Poetzl Date: Wed, 1 Feb 2017 17:46:39 +0000 Subject: [PATCH 02/67] compute dominators per function in dependence graph --- src/analyses/dependence_graph.cpp | 52 ++++++++++++++--------- src/analyses/dependence_graph.h | 14 ++++-- src/goto-instrument/full_slicer.cpp | 24 ++++++++--- src/goto-instrument/full_slicer_class.h | 2 +- src/goto-programs/goto_program_template.h | 17 ++++++++ 5 files changed, 79 insertions(+), 30 deletions(-) diff --git a/src/analyses/dependence_graph.cpp b/src/analyses/dependence_graph.cpp index 538f2c70dee..93588e209a7 100644 --- a/src/analyses/dependence_graph.cpp +++ b/src/analyses/dependence_graph.cpp @@ -94,6 +94,9 @@ void dep_graph_domaint::control_dependencies( from->is_assume()) control_deps.insert(from); + const irep_idt id=goto_programt::get_function_id(from); + const cfg_post_dominatorst &pd=dep_graph.cfg_post_dominators().at(id); + // check all candidates for M for(depst::iterator it=control_deps.begin(); @@ -111,15 +114,17 @@ void dep_graph_domaint::control_dependencies( // we could hard-code assume and goto handling here to improve // performance cfg_post_dominatorst::cfgt::entry_mapt::const_iterator e= - dep_graph.cfg_post_dominators().cfg.entry_map.find(*it); - assert(e!=dep_graph.cfg_post_dominators().cfg.entry_map.end()); + pd.cfg.entry_map.find(*it); + + assert(e!=pd.cfg.entry_map.end()); + const cfg_post_dominatorst::cfgt::nodet &m= - dep_graph.cfg_post_dominators().cfg[e->second]; + pd.cfg[e->second]; for(const auto &edge : m.out) { const cfg_post_dominatorst::cfgt::nodet &m_s= - dep_graph.cfg_post_dominators().cfg[edge.first]; + pd.cfg[edge.first]; if(m_s.dominators.find(to)!=m_s.dominators.end()) post_dom_one=true; @@ -252,7 +257,7 @@ void dep_graph_domaint::transform( const namespacet &ns) { dependence_grapht *dep_graph=dynamic_cast(&ai); - assert(dep_graph!=0); + assert(dep_graph!=nullptr); // propagate control dependencies across function calls if(from->is_function_call()) @@ -260,22 +265,31 @@ void dep_graph_domaint::transform( goto_programt::const_targett next=from; ++next; - dep_graph_domaint *s= - dynamic_cast(&(dep_graph->get_state(next))); - assert(s!=0); - - depst::iterator it=s->control_deps.begin(); - for(const auto &c_dep : control_deps) + if(next==to) { - while(it!=s->control_deps.end() && *itcontrol_deps.end() || c_dep<*it) - s->control_deps.insert(it, c_dep); - else if(it!=s->control_deps.end()) - ++it; + control_dependencies(from, to, *dep_graph); + } + else + { + // edge to function entry point + + dep_graph_domaint *s= + dynamic_cast(&(dep_graph->get_state(next))); + assert(s!=nullptr); + + depst::iterator it=s->control_deps.begin(); + for(const auto &c_dep : control_deps) + { + while(it!=s->control_deps.end() && *itcontrol_deps.end() || c_dep<*it) + s->control_deps.insert(it, c_dep); + else if(it!=s->control_deps.end()) + ++it; + } + + control_deps.clear(); } - - control_dependencies(from, next, *dep_graph); } else control_dependencies(from, to, *dep_graph); diff --git a/src/analyses/dependence_graph.h b/src/analyses/dependence_graph.h index f82d6f369ec..8b627dd36b0 100644 --- a/src/analyses/dependence_graph.h +++ b/src/analyses/dependence_graph.h @@ -154,6 +154,8 @@ class dependence_grapht: using ait::operator[]; using grapht::operator[]; + typedef std::map post_dominators_mapt; + explicit dependence_grapht(const namespacet &_ns): ns(_ns), rd(ns) @@ -169,7 +171,13 @@ class dependence_grapht: void initialize(const goto_programt &goto_program) { ait::initialize(goto_program); - post_dominators(goto_program); + + if(!goto_program.empty()) + { + const irep_idt id=goto_programt::get_function_id(goto_program); + cfg_post_dominatorst &pd=post_dominators[id]; + pd(goto_program); + } } void add_dep( @@ -177,7 +185,7 @@ class dependence_grapht: goto_programt::const_targett from, goto_programt::const_targett to); - const cfg_post_dominatorst &cfg_post_dominators() const + const post_dominators_mapt &cfg_post_dominators() const { return post_dominators; } @@ -205,7 +213,7 @@ class dependence_grapht: protected: const namespacet &ns; - cfg_post_dominatorst post_dominators; + post_dominators_mapt post_dominators; reaching_definitions_analysist rd; }; diff --git a/src/goto-instrument/full_slicer.cpp b/src/goto-instrument/full_slicer.cpp index 4eb720744e3..59bda7f0af0 100644 --- a/src/goto-instrument/full_slicer.cpp +++ b/src/goto-instrument/full_slicer.cpp @@ -140,7 +140,7 @@ Function: full_slicert::add_jumps void full_slicert::add_jumps( queuet &queue, jumpst &jumps, - const cfg_post_dominatorst &cfg_post_dominators) + const dependence_grapht::post_dominators_mapt &post_dominators) { // Based on: // On slicing programs with jump statements @@ -197,11 +197,16 @@ void full_slicert::add_jumps( continue; } + const irep_idt id=goto_programt::get_function_id(j.PC); + const cfg_post_dominatorst &pd=post_dominators.at(id); + cfg_post_dominatorst::cfgt::entry_mapt::const_iterator e= - cfg_post_dominators.cfg.entry_map.find(j.PC); - assert(e!=cfg_post_dominators.cfg.entry_map.end()); + pd.cfg.entry_map.find(j.PC); + + assert(e!=pd.cfg.entry_map.end()); + const cfg_post_dominatorst::cfgt::nodet &n= - cfg_post_dominators.cfg[e->second]; + pd.cfg[e->second]; // find the nearest post-dominator in slice if(n.dominators.find(lex_succ)==n.dominators.end()) @@ -226,11 +231,16 @@ void full_slicert::add_jumps( if(cfg[entry->second].node_required) { + const irep_idt id2=goto_programt::get_function_id(*d_it); + assert(id==id2); + cfg_post_dominatorst::cfgt::entry_mapt::const_iterator e2= - cfg_post_dominators.cfg.entry_map.find(*d_it); - assert(e2!=cfg_post_dominators.cfg.entry_map.end()); + pd.cfg.entry_map.find(*d_it); + + assert(e2!=pd.cfg.entry_map.end()); + const cfg_post_dominatorst::cfgt::nodet &n2= - cfg_post_dominators.cfg[e2->second]; + pd.cfg[e2->second]; if(n2.dominators.size()>post_dom_size) { diff --git a/src/goto-instrument/full_slicer_class.h b/src/goto-instrument/full_slicer_class.h index cf5be5685c2..4495fa95246 100644 --- a/src/goto-instrument/full_slicer_class.h +++ b/src/goto-instrument/full_slicer_class.h @@ -95,7 +95,7 @@ class full_slicert void add_jumps( queuet &queue, jumpst &jumps, - const cfg_post_dominatorst &cfg_post_dominators); + const dependence_grapht::post_dominators_mapt &post_dominators); void add_to_queue( queuet &queue, diff --git a/src/goto-programs/goto_program_template.h b/src/goto-programs/goto_program_template.h index 77161fcb4d8..845a7b94bdc 100644 --- a/src/goto-programs/goto_program_template.h +++ b/src/goto-programs/goto_program_template.h @@ -288,6 +288,23 @@ class goto_program_templatet return t; } + static const irep_idt get_function_id( + const_targett l) + { + while(!l->is_end_function()) + l++; + + return l->function; + } + + static const irep_idt get_function_id( + const goto_program_templatet &p) + { + assert(!p.empty()); + + return get_function_id(--p.instructions.end()); + } + void get_successors( targett target, targetst &successors); From 21b049eee69e54469895ddc9a86214ff81f740c3 Mon Sep 17 00:00:00 2001 From: Daniel Poetzl Date: Sat, 18 Feb 2017 14:23:58 +0000 Subject: [PATCH 03/67] marked slice16 as KNOWNBUG for now --- regression/goto-instrument/slice16/test.desc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/regression/goto-instrument/slice16/test.desc b/regression/goto-instrument/slice16/test.desc index 0f63776547f..846baaf2a8b 100644 --- a/regression/goto-instrument/slice16/test.desc +++ b/regression/goto-instrument/slice16/test.desc @@ -1,4 +1,4 @@ -CORE +KNOWNBUG main.c --full-slice --unwind 2 ^EXIT=0$ From bc96ff4481372b9dad8a849bc06ad6cc88d89731 Mon Sep 17 00:00:00 2001 From: martin Date: Tue, 28 Feb 2017 13:53:48 +0000 Subject: [PATCH 04/67] Remove an unnecessary loop over all instructions from flow insensitive analysis. --- .../value_set_analysis_fi.cpp | 24 ++++++------------- 1 file changed, 7 insertions(+), 17 deletions(-) diff --git a/src/pointer-analysis/value_set_analysis_fi.cpp b/src/pointer-analysis/value_set_analysis_fi.cpp index 2408f9816ed..3ed2a07bc7d 100644 --- a/src/pointer-analysis/value_set_analysis_fi.cpp +++ b/src/pointer-analysis/value_set_analysis_fi.cpp @@ -202,31 +202,21 @@ void value_set_analysis_fit::add_vars( get_globals(globals); value_set_fit &v=state.value_set; + v.add_vars(globals); - for(goto_functionst::function_mapt::const_iterator - f_it=goto_functions.function_map.begin(); - f_it!=goto_functions.function_map.end(); - f_it++) + forall_goto_functions(f_it, goto_functions) { // get the locals std::set locals; get_local_identifiers(f_it->second, locals); - forall_goto_program_instructions(i_it, f_it->second.body) + for(auto l : locals) { - v.add_vars(globals); + const symbolt &symbol=ns.lookup(l); - for(std::set::const_iterator - l_it=locals.begin(); - l_it!=locals.end(); - l_it++) - { - const symbolt &symbol=ns.lookup(*l_it); - - std::list entries; - get_entries(symbol, entries); - v.add_vars(entries); - } + std::list entries; + get_entries(symbol, entries); + v.add_vars(entries); } } } From b71febf006d97439db9f9db91f46b5de16384d68 Mon Sep 17 00:00:00 2001 From: martin Date: Fri, 10 Feb 2017 17:50:16 +0000 Subject: [PATCH 05/67] Fix similar issues in other places in pointer-analysis. It seems that there is a spurious loop over all instructions. I suspect this is a copy and paste error from location sensitive code. --- .../value_set_analysis_fivr.cpp | 56 ++++++------------- .../value_set_analysis_fivrns.cpp | 56 ++++++------------- 2 files changed, 36 insertions(+), 76 deletions(-) diff --git a/src/pointer-analysis/value_set_analysis_fivr.cpp b/src/pointer-analysis/value_set_analysis_fivr.cpp index fe428100a72..0180768250c 100644 --- a/src/pointer-analysis/value_set_analysis_fivr.cpp +++ b/src/pointer-analysis/value_set_analysis_fivr.cpp @@ -84,33 +84,23 @@ void value_set_analysis_fivrt::add_vars( entry_cachet entry_cache; value_set_fivrt &v=state.value_set; + v.add_vars(globals); - for(goto_programt::instructionst::const_iterator - i_it=goto_program.instructions.begin(); - i_it!=goto_program.instructions.end(); - i_it++) + for(auto l : locals) { - v.add_vars(globals); + // cache hit? + entry_cachet::const_iterator e_it=entry_cache.find(l); - for(goto_programt::decl_identifierst::const_iterator - l_it=locals.begin(); - l_it!=locals.end(); - l_it++) + if(e_it==entry_cache.end()) { - // cache hit? - entry_cachet::const_iterator e_it=entry_cache.find(*l_it); + const symbolt &symbol=ns.lookup(l); - if(e_it==entry_cache.end()) - { - const symbolt &symbol=ns.lookup(*l_it); - - std::list &entries=entry_cache[*l_it]; - get_entries(symbol, entries); - v.add_vars(entries); - } - else - v.add_vars(e_it->second); + std::list &entries=entry_cache[l]; + get_entries(symbol, entries); + v.add_vars(entries); } + else + v.add_vars(e_it->second); } } @@ -202,31 +192,21 @@ void value_set_analysis_fivrt::add_vars( get_globals(globals); value_set_fivrt &v=state.value_set; + v.add_vars(globals); - for(goto_functionst::function_mapt::const_iterator - f_it=goto_functions.function_map.begin(); - f_it!=goto_functions.function_map.end(); - f_it++) + forall_goto_functions(f_it, goto_functions) { // get the locals std::set locals; get_local_identifiers(f_it->second, locals); - forall_goto_program_instructions(i_it, f_it->second.body) + for(auto l : locals) { - v.add_vars(globals); + const symbolt &symbol=ns.lookup(l); - for(std::set::const_iterator - l_it=locals.begin(); - l_it!=locals.end(); - l_it++) - { - const symbolt &symbol=ns.lookup(*l_it); - - std::list entries; - get_entries(symbol, entries); - v.add_vars(entries); - } + std::list entries; + get_entries(symbol, entries); + v.add_vars(entries); } } } diff --git a/src/pointer-analysis/value_set_analysis_fivrns.cpp b/src/pointer-analysis/value_set_analysis_fivrns.cpp index d2f9e966437..1b7d2422186 100644 --- a/src/pointer-analysis/value_set_analysis_fivrns.cpp +++ b/src/pointer-analysis/value_set_analysis_fivrns.cpp @@ -84,33 +84,23 @@ void value_set_analysis_fivrnst::add_vars( entry_cachet entry_cache; value_set_fivrnst &v=state.value_set; + v.add_vars(globals); - for(goto_programt::instructionst::const_iterator - i_it=goto_program.instructions.begin(); - i_it!=goto_program.instructions.end(); - i_it++) + for(auto l : locals) { - v.add_vars(globals); + // cache hit? + entry_cachet::const_iterator e_it=entry_cache.find(l); - for(goto_programt::decl_identifierst::const_iterator - l_it=locals.begin(); - l_it!=locals.end(); - l_it++) + if(e_it==entry_cache.end()) { - // cache hit? - entry_cachet::const_iterator e_it=entry_cache.find(*l_it); + const symbolt &symbol=ns.lookup(l); - if(e_it==entry_cache.end()) - { - const symbolt &symbol=ns.lookup(*l_it); - - std::list &entries=entry_cache[*l_it]; - get_entries(symbol, entries); - v.add_vars(entries); - } - else - v.add_vars(e_it->second); + std::list &entries=entry_cache[l]; + get_entries(symbol, entries); + v.add_vars(entries); } + else + v.add_vars(e_it->second); } } @@ -202,31 +192,21 @@ void value_set_analysis_fivrnst::add_vars( get_globals(globals); value_set_fivrnst &v=state.value_set; + v.add_vars(globals); - for(goto_functionst::function_mapt::const_iterator - f_it=goto_functions.function_map.begin(); - f_it!=goto_functions.function_map.end(); - f_it++) + forall_goto_functions(f_it, goto_functions) { // get the locals std::set locals; get_local_identifiers(f_it->second, locals); - forall_goto_program_instructions(i_it, f_it->second.body) + for(auto l : locals) { - v.add_vars(globals); + const symbolt &symbol=ns.lookup(l); - for(std::set::const_iterator - l_it=locals.begin(); - l_it!=locals.end(); - l_it++) - { - const symbolt &symbol=ns.lookup(*l_it); - - std::list entries; - get_entries(symbol, entries); - v.add_vars(entries); - } + std::list entries; + get_entries(symbol, entries); + v.add_vars(entries); } } } From 5c121b9ab33d95e8b34f9386880a5570c8f815cc Mon Sep 17 00:00:00 2001 From: martin Date: Fri, 10 Feb 2017 16:58:28 +0000 Subject: [PATCH 06/67] Remove the top variable from the cfg_dominator analysis. This variable is not used anywhere, it is not clear what it's purpose is and in profiling it was shown to be expensive. --- src/analyses/cfg_dominators.h | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/analyses/cfg_dominators.h b/src/analyses/cfg_dominators.h index 687d84e1416..1a4d6090f47 100644 --- a/src/analyses/cfg_dominators.h +++ b/src/analyses/cfg_dominators.h @@ -35,7 +35,6 @@ class cfg_dominators_templatet void operator()(P &program); - target_sett top; T entry_node; void output(std::ostream &) const; @@ -101,10 +100,6 @@ template void cfg_dominators_templatet::initialise(P &program) { cfg(program); - - // initialise top element - for(const auto &node : cfg.entry_map) - top.insert(cfg[node.second].PC); } /*******************************************************************\ From 7cbf75e494318dd6b11cbcc0fd1568560fd69aae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Tue, 14 Feb 2017 11:53:11 +0100 Subject: [PATCH 07/67] initial support for miniz --- src/java_bytecode/jar_file.cpp | 92 +++++++++++++--------------------- src/java_bytecode/jar_file.h | 14 ++++-- 2 files changed, 45 insertions(+), 61 deletions(-) diff --git a/src/java_bytecode/jar_file.cpp b/src/java_bytecode/jar_file.cpp index 09c18a9cb4c..d679f21c070 100644 --- a/src/java_bytecode/jar_file.cpp +++ b/src/java_bytecode/jar_file.cpp @@ -6,15 +6,12 @@ Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ +#include #include #include #include "jar_file.h" -#ifdef HAVE_LIBZIP -#include -#endif - /*******************************************************************\ Function: jar_filet::open @@ -29,33 +26,32 @@ Function: jar_filet::open void jar_filet::open(const std::string &filename) { - #ifdef HAVE_LIBZIP - if(zip!=nullptr) - // NOLINTNEXTLINE(readability/identifiers) - zip_close(static_cast(zip)); - - int zip_error; - zip=zip_open(filename.c_str(), 0, &zip_error); + if(!mz_ok) + { + memset(&zip, 0, sizeof(zip)); + mz_bool mz_open=mz_zip_reader_init_file(&zip, filename.c_str(), 0); + mz_ok=mz_open==MZ_TRUE; + } - if(zip!=nullptr) + if(mz_ok) { std::size_t number_of_files= - // NOLINTNEXTLINE(readability/identifiers) - zip_get_num_entries(static_cast(zip), 0); + mz_zip_reader_get_num_files(&zip); index.reserve(number_of_files); for(std::size_t i=0; i(zip), i, 0); + mz_uint filename_length=mz_zip_reader_get_filename(&zip, i, nullptr, 0); + char *filename_char=new char[filename_length+1]; + mz_uint filename_len= + mz_zip_reader_get_filename(&zip, i, filename_char, filename_length); + assert(filename_length==filename_len); + std::string file_name(filename_char); + delete[] filename_char; index.push_back(file_name); } } - #else - zip=nullptr; - #endif } /*******************************************************************\ @@ -72,11 +68,11 @@ Function: jar_filet::~jar_filet jar_filet::~jar_filet() { - #ifdef HAVE_LIBZIP - if(zip!=nullptr) - // NOLINTNEXTLINE(readability/identifiers) - zip_close(static_cast(zip)); - #endif + if(mz_ok) + { + mz_zip_reader_end(&zip); + mz_ok=false; + } } /*******************************************************************\ @@ -91,47 +87,29 @@ Function: jar_filet::get_entry \*******************************************************************/ -#define ZIP_READ_SIZE 10000 - std::string jar_filet::get_entry(std::size_t i) { - if(zip==nullptr) + if(!mz_ok) return std::string(""); assert(i(zip_e); - - // NOLINTNEXTLINE(readability/identifiers) - struct zip_file *zip_file=zip_fopen_index(zip_p, i, 0); - - if(zip_file==NULL) - { - zip_close(zip_p); - zip=nullptr; - return std::string(""); // error - } - + mz_zip_archive_file_stat file_stat; + memset(&file_stat, 0, sizeof(file_stat)); + mz_bool stat_ok=mz_zip_reader_file_stat(&zip, i, &file_stat); + if(stat_ok!=MZ_TRUE) + return std::string(); std::vector buffer; - buffer.resize(ZIP_READ_SIZE); - - while(true) - { - int bytes_read= - zip_fread(zip_file, buffer.data(), ZIP_READ_SIZE); - assert(bytes_read<=ZIP_READ_SIZE); - if(bytes_read<=0) - break; - dest.insert(dest.end(), buffer.begin(), buffer.begin()+bytes_read); - } - - zip_fclose(zip_file); - #endif + size_t bufsize=file_stat.m_uncomp_size; + buffer.resize(bufsize); + mz_bool read_ok= + mz_zip_reader_extract_to_mem(&zip, i, buffer.data(), bufsize, 0); + if(read_ok!=MZ_TRUE) + return std::string(); + + dest.insert(dest.end(), buffer.begin(), buffer.end()); return dest; } diff --git a/src/java_bytecode/jar_file.h b/src/java_bytecode/jar_file.h index a128a2fcc37..6c2229d65be 100644 --- a/src/java_bytecode/jar_file.h +++ b/src/java_bytecode/jar_file.h @@ -9,6 +9,10 @@ Author: Daniel Kroening, kroening@kroening.com #ifndef CPROVER_JAVA_BYTECODE_JAR_FILE_H #define CPROVER_JAVA_BYTECODE_JAR_FILE_H +//#define MINIZ_HEADER_FILE_ONLY +#define _LARGEFILE64_SOURCE 1 +#include "miniz_zip.h" + #include #include #include @@ -16,9 +20,9 @@ Author: Daniel Kroening, kroening@kroening.com class jar_filet { public: - jar_filet():zip(nullptr) { } + jar_filet():mz_ok(false) { } - explicit jar_filet(const std::string &file_name):zip(nullptr) + inline explicit jar_filet(const std::string &file_name) { open(file_name); } @@ -28,7 +32,8 @@ class jar_filet void open(const std::string &); // Test for error; 'true' means we are good. - explicit operator bool() const { return zip!=nullptr; } + inline explicit operator bool() const { return true; // TODO + } typedef std::vector indext; indext index; @@ -39,7 +44,8 @@ class jar_filet manifestt get_manifest(); protected: - void *zip; + mz_zip_archive zip; + bool mz_ok; }; class jar_poolt From 9a953528d7d02edbc60d5ca12281f5c8a5ca2984 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Thu, 23 Feb 2017 12:39:16 +0100 Subject: [PATCH 08/67] use amalgamated files from release tarball --- src/java_bytecode/jar_file.h | 3 +- src/miniz/Makefile | 15 + src/miniz/miniz.cpp | 7189 ++++++++++++++++++++++++++++++++++ src/miniz/miniz.h | 1352 +++++++ 4 files changed, 8557 insertions(+), 2 deletions(-) create mode 100644 src/miniz/Makefile create mode 100644 src/miniz/miniz.cpp create mode 100644 src/miniz/miniz.h diff --git a/src/java_bytecode/jar_file.h b/src/java_bytecode/jar_file.h index 6c2229d65be..53f673102bf 100644 --- a/src/java_bytecode/jar_file.h +++ b/src/java_bytecode/jar_file.h @@ -9,9 +9,8 @@ Author: Daniel Kroening, kroening@kroening.com #ifndef CPROVER_JAVA_BYTECODE_JAR_FILE_H #define CPROVER_JAVA_BYTECODE_JAR_FILE_H -//#define MINIZ_HEADER_FILE_ONLY #define _LARGEFILE64_SOURCE 1 -#include "miniz_zip.h" +#include "miniz/miniz.h" #include #include diff --git a/src/miniz/Makefile b/src/miniz/Makefile new file mode 100644 index 00000000000..f2367695802 --- /dev/null +++ b/src/miniz/Makefile @@ -0,0 +1,15 @@ +SRC = miniz.cpp + +INCLUDES= -I .. + +include ../config.inc +include ../common + +CLEANFILES = miniz$(LIBEXT) + +all: miniz$(LIBEXT) + +############################################################################### + +miniz$(LIBEXT): $(OBJ) + $(LINKLIB) diff --git a/src/miniz/miniz.cpp b/src/miniz/miniz.cpp new file mode 100644 index 00000000000..fa5c1903e83 --- /dev/null +++ b/src/miniz/miniz.cpp @@ -0,0 +1,7189 @@ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + +#include "miniz.h" + +typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; +typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; +typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API's */ + +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) +{ + mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); + size_t block_len = buf_len % 5552; + if (!ptr) + return MZ_ADLER32_INIT; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + return (s2 << 16) + s1; +} + +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ +#if 0 + mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) + { + static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, + 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; + mz_uint32 crcu32 = (mz_uint32)crc; + if (!ptr) + return MZ_CRC32_INIT; + crcu32 = ~crcu32; + while (buf_len--) + { + mz_uint8 b = *ptr++; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; + crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; + } + return ~crcu32; + } +#else +/* Faster, but larger CPU cache footprint. + */ +mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) +{ + static const mz_uint32 s_crc_table[256] = + { + 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419, 0x706AF48F, 0xE963A535, + 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, + 0xE7B82D07, 0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, 0x1ADAD47D, + 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, + 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4, + 0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, 0x35B5A8FA, 0x42B2986C, + 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, + 0x51DE003A, 0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, + 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, 0x2F6F7C87, 0x58684C11, 0xC1611DAB, + 0xB6662D3D, 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F, + 0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, 0x7F6A0DBB, + 0x086D3D2D, 0x91646C97, 0xE6635C01, 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, + 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, + 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, 0x4DB26158, 0x3AB551CE, + 0xA3BC0074, 0xD4BB30E2, 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A, + 0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, + 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, + 0xCE61E49F, 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17, 0x2EB40D81, + 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, 0xEAD54739, + 0x9DD277AF, 0x04DB2615, 0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, + 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344, 0x8708A3D2, 0x1E01F268, + 0x6906C2FE, 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, + 0x10DA7A5A, 0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, 0xD6D6A3E8, + 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, + 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, + 0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, 0xCC0C7795, 0xBB0B4703, + 0x220216B9, 0x5505262F, 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, + 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, + 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, + 0x0CB61B38, 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242, + 0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, 0x88085AE6, + 0xFF0F6A70, 0x66063BCA, 0x11010B5C, 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, + 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7, 0x4969474D, + 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, + 0x47B2CF7F, 0x30B5FFE9, 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605, + 0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, + 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D + }; + + mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; + const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; + + while (buf_len >= 4) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[2]) & 0xFF]; + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[3]) & 0xFF]; + pByte_buf += 4; + buf_len -= 4; + } + + while (buf_len) + { + crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; + ++pByte_buf; + --buf_len; + } + + return ~crc32; +} +#endif + +void mz_free(void *p) +{ + MZ_FREE(p); +} + +#ifndef MINIZ_NO_ZLIB_APIS + +void *miniz_def_alloc_func(void *opaque, size_t items, size_t size) +{ + (void)opaque, (void)items, (void)size; + return MZ_MALLOC(items * size); +} +void miniz_def_free_func(void *opaque, void *address) +{ + (void)opaque, (void)address; + MZ_FREE(address); +} +void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size) +{ + (void)opaque, (void)address, (void)items, (void)size; + return MZ_REALLOC(address, items * size); +} + +const char *mz_version(void) +{ + return MZ_VERSION; +} + +int mz_deflateInit(mz_streamp pStream, int level) +{ + return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); +} + +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) +{ + tdefl_compressor *pComp; + mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); + + if (!pStream) + return MZ_STREAM_ERROR; + if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = MZ_ADLER32_INIT; + pStream->msg = NULL; + pStream->reserved = 0; + pStream->total_in = 0; + pStream->total_out = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pComp; + + if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + { + mz_deflateEnd(pStream); + return MZ_PARAM_ERROR; + } + + return MZ_OK; +} + +int mz_deflateReset(mz_streamp pStream) +{ + if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) + return MZ_STREAM_ERROR; + pStream->total_in = pStream->total_out = 0; + tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); + return MZ_OK; +} + +int mz_deflate(mz_streamp pStream, int flush) +{ + size_t in_bytes, out_bytes; + mz_ulong orig_total_in, orig_total_out; + int mz_status = MZ_OK; + + if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) + return MZ_STREAM_ERROR; + if (!pStream->avail_out) + return MZ_BUF_ERROR; + + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + + if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; + + orig_total_in = pStream->total_in; + orig_total_out = pStream->total_out; + for (;;) + { + tdefl_status defl_status; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + + defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); + + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (defl_status < 0) + { + mz_status = MZ_STREAM_ERROR; + break; + } + else if (defl_status == TDEFL_STATUS_DONE) + { + mz_status = MZ_STREAM_END; + break; + } + else if (!pStream->avail_out) + break; + else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + { + if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + break; + return MZ_BUF_ERROR; /* Can't make forward progress without some input. + */ + } + } + return mz_status; +} + +int mz_deflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) +{ + (void)pStream; + /* This is really over conservative. (And lame, but it's actually pretty tricky to compute a true upper bound given the way tdefl's blocking works.) */ + return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); +} + +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) +{ + int status; + mz_stream stream; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32) * pDest_len; + + status = mz_deflateInit(&stream, level); + if (status != MZ_OK) + return status; + + status = mz_deflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_deflateEnd(&stream); + return (status == MZ_OK) ? MZ_BUF_ERROR : status; + } + + *pDest_len = stream.total_out; + return mz_deflateEnd(&stream); +} + +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); +} + +mz_ulong mz_compressBound(mz_ulong source_len) +{ + return mz_deflateBound(NULL, source_len); +} + +typedef struct +{ + tinfl_decompressor m_decomp; + mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; + int m_window_bits; + mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; + tinfl_status m_last_status; +} inflate_state; + +int mz_inflateInit2(mz_streamp pStream, int window_bits) +{ + inflate_state *pDecomp; + if (!pStream) + return MZ_STREAM_ERROR; + if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + return MZ_PARAM_ERROR; + + pStream->data_type = 0; + pStream->adler = 0; + pStream->msg = NULL; + pStream->total_in = 0; + pStream->total_out = 0; + pStream->reserved = 0; + if (!pStream->zalloc) + pStream->zalloc = miniz_def_alloc_func; + if (!pStream->zfree) + pStream->zfree = miniz_def_free_func; + + pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); + if (!pDecomp) + return MZ_MEM_ERROR; + + pStream->state = (struct mz_internal_state *)pDecomp; + + tinfl_init(&pDecomp->m_decomp); + pDecomp->m_dict_ofs = 0; + pDecomp->m_dict_avail = 0; + pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; + pDecomp->m_first_call = 1; + pDecomp->m_has_flushed = 0; + pDecomp->m_window_bits = window_bits; + + return MZ_OK; +} + +int mz_inflateInit(mz_streamp pStream) +{ + return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); +} + +int mz_inflate(mz_streamp pStream, int flush) +{ + inflate_state *pState; + mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; + size_t in_bytes, out_bytes, orig_avail_in; + tinfl_status status; + + if ((!pStream) || (!pStream->state)) + return MZ_STREAM_ERROR; + if (flush == MZ_PARTIAL_FLUSH) + flush = MZ_SYNC_FLUSH; + if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + + pState = (inflate_state *)pStream->state; + if (pState->m_window_bits > 0) + decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; + orig_avail_in = pStream->avail_in; + + first_call = pState->m_first_call; + pState->m_first_call = 0; + if (pState->m_last_status < 0) + return MZ_DATA_ERROR; + + if (pState->m_has_flushed && (flush != MZ_FINISH)) + return MZ_STREAM_ERROR; + pState->m_has_flushed |= (flush == MZ_FINISH); + + if ((flush == MZ_FINISH) && (first_call)) + { + /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ + decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; + in_bytes = pStream->avail_in; + out_bytes = pStream->avail_out; + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); + pState->m_last_status = status; + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + pStream->next_out += (mz_uint)out_bytes; + pStream->avail_out -= (mz_uint)out_bytes; + pStream->total_out += (mz_uint)out_bytes; + + if (status < 0) + return MZ_DATA_ERROR; + else if (status != TINFL_STATUS_DONE) + { + pState->m_last_status = TINFL_STATUS_FAILED; + return MZ_BUF_ERROR; + } + return MZ_STREAM_END; + } + /* flush != MZ_FINISH then we must assume there's more input. */ + if (flush != MZ_FINISH) + decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; + + if (pState->m_dict_avail) + { + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; + } + + for (;;) + { + in_bytes = pStream->avail_in; + out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; + + status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); + pState->m_last_status = status; + + pStream->next_in += (mz_uint)in_bytes; + pStream->avail_in -= (mz_uint)in_bytes; + pStream->total_in += (mz_uint)in_bytes; + pStream->adler = tinfl_get_adler32(&pState->m_decomp); + + pState->m_dict_avail = (mz_uint)out_bytes; + + n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); + memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); + pStream->next_out += n; + pStream->avail_out -= n; + pStream->total_out += n; + pState->m_dict_avail -= n; + pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); + + if (status < 0) + return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ + else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ + else if (flush == MZ_FINISH) + { + /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ + if (status == TINFL_STATUS_DONE) + return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; + /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ + else if (!pStream->avail_out) + return MZ_BUF_ERROR; + } + else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + break; + } + + return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; +} + +int mz_inflateEnd(mz_streamp pStream) +{ + if (!pStream) + return MZ_STREAM_ERROR; + if (pStream->state) + { + pStream->zfree(pStream->opaque, pStream->state); + pStream->state = NULL; + } + return MZ_OK; +} + +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) +{ + mz_stream stream; + int status; + memset(&stream, 0, sizeof(stream)); + + /* In case mz_ulong is 64-bits (argh I hate longs). */ + if ((source_len | *pDest_len) > 0xFFFFFFFFU) + return MZ_PARAM_ERROR; + + stream.next_in = pSource; + stream.avail_in = (mz_uint32)source_len; + stream.next_out = pDest; + stream.avail_out = (mz_uint32) * pDest_len; + + status = mz_inflateInit(&stream); + if (status != MZ_OK) + return status; + + status = mz_inflate(&stream, MZ_FINISH); + if (status != MZ_STREAM_END) + { + mz_inflateEnd(&stream); + return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; + } + *pDest_len = stream.total_out; + + return mz_inflateEnd(&stream); +} + +const char *mz_error(int err) +{ + static struct + { + int m_err; + const char *m_pDesc; + } s_error_descs[] = + { + { MZ_OK, "" }, { MZ_STREAM_END, "stream end" }, { MZ_NEED_DICT, "need dictionary" }, { MZ_ERRNO, "file error" }, { MZ_STREAM_ERROR, "stream error" }, + { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } + }; + mz_uint i; + for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if (s_error_descs[i].m_err == err) + return s_error_descs[i].m_pDesc; + return NULL; +} + +#endif /*MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif + +/* + This is free and unencumbered software released into the public domain. + + Anyone is free to copy, modify, publish, use, compile, sell, or + distribute this software, either in source code form or as a compiled + binary, for any purpose, commercial or non-commercial, and by any + means. + + In jurisdictions that recognize copyright laws, the author or authors + of this software dedicate any and all copyright interest in the + software to the public domain. We make this dedication for the benefit + of the public at large and to the detriment of our heirs and + successors. We intend this dedication to be an overt act of + relinquishment in perpetuity of all present and future rights to this + software under copyright law. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR + OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, + ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + For more information, please refer to +*/ +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + + + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Compression (independent from all decompression API's) */ + +/* Purposely making these tables static for faster init and thread safety. */ +static const mz_uint16 s_tdefl_len_sym[256] = + { + 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, + 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, + 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, + 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, + 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, + 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, + 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, + 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285 + }; + +static const mz_uint8 s_tdefl_len_extra[256] = + { + 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0 + }; + +static const mz_uint8 s_tdefl_small_dist_sym[512] = + { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, + 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, + 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, + 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, + 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17 + }; + +static const mz_uint8 s_tdefl_small_dist_extra[512] = + { + 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, + 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, + 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, + 7, 7, 7, 7, 7, 7, 7, 7 + }; + +static const mz_uint8 s_tdefl_large_dist_sym[128] = + { + 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, + 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, + 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 + }; + +static const mz_uint8 s_tdefl_large_dist_extra[128] = + { + 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, + 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, + 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13 + }; + +/* Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted values. */ +typedef struct +{ + mz_uint16 m_key, m_sym_index; +} tdefl_sym_freq; +static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) +{ + mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; + tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; + MZ_CLEAR_OBJ(hist); + for (i = 0; i < num_syms; i++) + { + mz_uint freq = pSyms0[i].m_key; + hist[freq & 0xFF]++; + hist[256 + ((freq >> 8) & 0xFF)]++; + } + while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + total_passes--; + for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + { + const mz_uint32 *pHist = &hist[pass << 8]; + mz_uint offsets[256], cur_ofs = 0; + for (i = 0; i < 256; i++) + { + offsets[i] = cur_ofs; + cur_ofs += pHist[i]; + } + for (i = 0; i < num_syms; i++) + pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; + { + tdefl_sym_freq *t = pCur_syms; + pCur_syms = pNew_syms; + pNew_syms = t; + } + } + return pCur_syms; +} + +/* tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. */ +static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) +{ + int root, leaf, next, avbl, used, dpth; + if (n == 0) + return; + else if (n == 1) + { + A[0].m_key = 1; + return; + } + A[0].m_key += A[1].m_key; + root = 0; + leaf = 2; + for (next = 1; next < n - 1; next++) + { + if (leaf >= n || A[root].m_key < A[leaf].m_key) + { + A[next].m_key = A[root].m_key; + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = A[leaf++].m_key; + if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + { + A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); + A[root++].m_key = (mz_uint16)next; + } + else + A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); + } + A[n - 2].m_key = 0; + for (next = n - 3; next >= 0; next--) + A[next].m_key = A[A[next].m_key].m_key + 1; + avbl = 1; + used = dpth = 0; + root = n - 2; + next = n - 1; + while (avbl > 0) + { + while (root >= 0 && (int)A[root].m_key == dpth) + { + used++; + root--; + } + while (avbl > used) + { + A[next--].m_key = (mz_uint16)(dpth); + avbl--; + } + avbl = 2 * used; + dpth++; + used = 0; + } +} + +/* Limits canonical Huffman code table's max code size. */ +enum +{ + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 +}; +static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) +{ + int i; + mz_uint32 total = 0; + if (code_list_len <= 1) + return; + for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + pNum_codes[max_code_size] += pNum_codes[i]; + for (i = max_code_size; i > 0; i--) + total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); + while (total != (1UL << max_code_size)) + { + pNum_codes[max_code_size]--; + for (i = max_code_size - 1; i > 0; i--) + if (pNum_codes[i]) + { + pNum_codes[i]--; + pNum_codes[i + 1] += 2; + break; + } + total--; + } +} + +static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) +{ + int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; + mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; + MZ_CLEAR_OBJ(num_codes); + if (static_table) + { + for (i = 0; i < table_len; i++) + num_codes[d->m_huff_code_sizes[table_num][i]]++; + } + else + { + tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; + int num_used_syms = 0; + const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; + for (i = 0; i < table_len; i++) + if (pSym_count[i]) + { + syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; + syms0[num_used_syms++].m_sym_index = (mz_uint16)i; + } + + pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); + tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); + + for (i = 0; i < num_used_syms; i++) + num_codes[pSyms[i].m_key]++; + + tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); + + MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); + MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); + for (i = 1, j = num_used_syms; i <= code_size_limit; i++) + for (l = num_codes[i]; l > 0; l--) + d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); + } + + next_code[1] = 0; + for (j = 0, i = 2; i <= code_size_limit; i++) + next_code[i] = j = ((j + num_codes[i - 1]) << 1); + + for (i = 0; i < table_len; i++) + { + mz_uint rev_code = 0, code, code_size; + if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + continue; + code = next_code[code_size]++; + for (l = code_size; l > 0; l--, code >>= 1) + rev_code = (rev_code << 1) | (code & 1); + d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; + } +} + +#define TDEFL_PUT_BITS(b, l) \ + do \ + { \ + mz_uint bits = b; \ + mz_uint len = l; \ + MZ_ASSERT(bits <= ((1U << len) - 1U)); \ + d->m_bit_buffer |= (bits << d->m_bits_in); \ + d->m_bits_in += len; \ + while (d->m_bits_in >= 8) \ + { \ + if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ + d->m_bit_buffer >>= 8; \ + d->m_bits_in -= 8; \ + } \ + } \ + MZ_MACRO_END + +#define TDEFL_RLE_PREV_CODE_SIZE() \ + { \ + if (rle_repeat_count) \ + { \ + if (rle_repeat_count < 3) \ + { \ + d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ + while (rle_repeat_count--) \ + packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ + } \ + else \ + { \ + d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 16; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_repeat_count - 3); \ + } \ + rle_repeat_count = 0; \ + } \ + } + +#define TDEFL_RLE_ZERO_CODE_SIZE() \ + { \ + if (rle_z_count) \ + { \ + if (rle_z_count < 3) \ + { \ + d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ + while (rle_z_count--) \ + packed_code_sizes[num_packed_code_sizes++] = 0; \ + } \ + else if (rle_z_count <= 10) \ + { \ + d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 17; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 3); \ + } \ + else \ + { \ + d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ + packed_code_sizes[num_packed_code_sizes++] = 18; \ + packed_code_sizes[num_packed_code_sizes++] = (mz_uint8)(rle_z_count - 11); \ + } \ + rle_z_count = 0; \ + } \ + } + +static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + +static void tdefl_start_dynamic_block(tdefl_compressor *d) +{ + int num_lit_codes, num_dist_codes, num_bit_lengths; + mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; + mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; + + d->m_huff_count[0][256] = 1; + + tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); + tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); + + for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + break; + for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + break; + + memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); + memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); + total_code_sizes_to_pack = num_lit_codes + num_dist_codes; + num_packed_code_sizes = 0; + rle_z_count = 0; + rle_repeat_count = 0; + + memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); + for (i = 0; i < total_code_sizes_to_pack; i++) + { + mz_uint8 code_size = code_sizes_to_pack[i]; + if (!code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + if (++rle_z_count == 138) + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + if (code_size != prev_code_size) + { + TDEFL_RLE_PREV_CODE_SIZE(); + d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); + packed_code_sizes[num_packed_code_sizes++] = code_size; + } + else if (++rle_repeat_count == 6) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + } + prev_code_size = code_size; + } + if (rle_repeat_count) + { + TDEFL_RLE_PREV_CODE_SIZE(); + } + else + { + TDEFL_RLE_ZERO_CODE_SIZE(); + } + + tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); + + TDEFL_PUT_BITS(2, 2); + + TDEFL_PUT_BITS(num_lit_codes - 257, 5); + TDEFL_PUT_BITS(num_dist_codes - 1, 5); + + for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + break; + num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); + TDEFL_PUT_BITS(num_bit_lengths - 4, 4); + for (i = 0; (int)i < num_bit_lengths; i++) + TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); + + for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) + { + mz_uint code = packed_code_sizes[packed_code_sizes_index++]; + MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); + TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); + if (code >= 16) + TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); + } +} + +static void tdefl_start_static_block(tdefl_compressor *d) +{ + mz_uint i; + mz_uint8 *p = &d->m_huff_code_sizes[0][0]; + + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + + memset(d->m_huff_code_sizes[1], 5, 32); + + tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); + tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); + + TDEFL_PUT_BITS(1, 2); +} + +static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF }; + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES &&MINIZ_LITTLE_ENDIAN &&MINIZ_HAS_64BIT_REGISTERS +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + mz_uint8 *pOutput_buf = d->m_pOutput_buf; + mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; + mz_uint64 bit_buffer = d->m_bit_buffer; + mz_uint bits_in = d->m_bits_in; + +#define TDEFL_PUT_BITS_FAST(b, l) \ + { \ + bit_buffer |= (((mz_uint64)(b)) << bits_in); \ + bits_in += (l); \ + } + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + + if (flags & 1) + { + mz_uint s0, s1, n0, n1, sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + /* This sequence coaxes MSVC into using cmov's vs. jmp's. */ + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + n0 = s_tdefl_small_dist_extra[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[match_dist >> 8]; + n1 = s_tdefl_large_dist_extra[match_dist >> 8]; + sym = (match_dist < 512) ? s0 : s1; + num_extra_bits = (match_dist < 512) ? n0 : n1; + + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + + if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + { + flags >>= 1; + lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + } + + if (pOutput_buf >= d->m_pOutput_buf_end) + return MZ_FALSE; + + *(mz_uint64 *)pOutput_buf = bit_buffer; + pOutput_buf += (bits_in >> 3); + bit_buffer >>= (bits_in & ~7); + bits_in &= 7; + } + +#undef TDEFL_PUT_BITS_FAST + + d->m_pOutput_buf = pOutput_buf; + d->m_bits_in = 0; + d->m_bit_buffer = 0; + + while (bits_in) + { + mz_uint32 n = MZ_MIN(bits_in, 16); + TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); + bit_buffer >>= n; + bits_in -= n; + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#else +static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) +{ + mz_uint flags; + mz_uint8 *pLZ_codes; + + flags = 1; + for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + { + if (flags == 1) + flags = *pLZ_codes++ | 0x100; + if (flags & 1) + { + mz_uint sym, num_extra_bits; + mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); + pLZ_codes += 3; + + MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); + TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); + + if (match_dist < 512) + { + sym = s_tdefl_small_dist_sym[match_dist]; + num_extra_bits = s_tdefl_small_dist_extra[match_dist]; + } + else + { + sym = s_tdefl_large_dist_sym[match_dist >> 8]; + num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; + } + MZ_ASSERT(d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); + TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); + } + else + { + mz_uint lit = *pLZ_codes++; + MZ_ASSERT(d->m_huff_code_sizes[0][lit]); + TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); + } + } + + TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); + + return (d->m_pOutput_buf < d->m_pOutput_buf_end); +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && MINIZ_HAS_64BIT_REGISTERS */ + +static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) +{ + if (static_block) + tdefl_start_static_block(d); + else + tdefl_start_dynamic_block(d); + return tdefl_compress_lz_codes(d); +} + +static int tdefl_flush_block(tdefl_compressor *d, int flush) +{ + mz_uint saved_bit_buf, saved_bits_in; + mz_uint8 *pSaved_output_buf; + mz_bool comp_block_succeeded = MZ_FALSE; + int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; + mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; + + d->m_pOutput_buf = pOutput_buf_start; + d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; + + MZ_ASSERT(!d->m_output_flush_remaining); + d->m_output_flush_ofs = 0; + d->m_output_flush_remaining = 0; + + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); + d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); + + if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + { + TDEFL_PUT_BITS(0x78, 8); + TDEFL_PUT_BITS(0x01, 8); + } + + TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); + + pSaved_output_buf = d->m_pOutput_buf; + saved_bit_buf = d->m_bit_buffer; + saved_bits_in = d->m_bits_in; + + if (!use_raw_block) + comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); + + /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ + if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) + { + mz_uint i; + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + TDEFL_PUT_BITS(0, 2); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + { + TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); + } + for (i = 0; i < d->m_total_lz_bytes; ++i) + { + TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); + } + } + /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ + else if (!comp_block_succeeded) + { + d->m_pOutput_buf = pSaved_output_buf; + d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; + tdefl_compress_block(d, MZ_TRUE); + } + + if (flush) + { + if (flush == TDEFL_FINISH) + { + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + { + mz_uint i, a = d->m_adler32; + for (i = 0; i < 4; i++) + { + TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); + a <<= 8; + } + } + } + else + { + mz_uint i, z = 0; + TDEFL_PUT_BITS(0, 3); + if (d->m_bits_in) + { + TDEFL_PUT_BITS(0, 8 - d->m_bits_in); + } + for (i = 2; i; --i, z ^= 0xFFFF) + { + TDEFL_PUT_BITS(z & 0xFFFF, 16); + } + } + } + + MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); + + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; + d->m_total_lz_bytes = 0; + d->m_block_index++; + + if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + { + if (d->m_pPut_buf_func) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); + } + else if (pOutput_buf_start == d->m_output_buf) + { + int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); + d->m_out_buf_ofs += bytes_to_copy; + if ((n -= bytes_to_copy) != 0) + { + d->m_output_flush_ofs = bytes_to_copy; + d->m_output_flush_remaining = n; + } + } + else + { + d->m_out_buf_ofs += n; + } + } + + return d->m_output_flush_remaining; +} + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES +#define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; + mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + q = (const mz_uint16 *)(d->m_dict + probe_pos); + if (TDEFL_READ_UNALIGNED_WORD(q) != s01) + continue; + p = s; + probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); + if (!probe_len) + { + *pMatch_dist = dist; + *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); + break; + } + else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) + break; + c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); + } + } +} +#else +static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) +{ + mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; + mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; + const mz_uint8 *s = d->m_dict + pos, *p, *q; + mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; + MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); + if (max_match_len <= match_len) + return; + for (;;) + { + for (;;) + { + if (--num_probes_left == 0) + return; +#define TDEFL_PROBE \ + next_probe_pos = d->m_next[probe_pos]; \ + if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + return; \ + probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ + if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ + break; + TDEFL_PROBE; + TDEFL_PROBE; + TDEFL_PROBE; + } + if (!dist) + break; + p = s; + q = d->m_dict + probe_pos; + for (probe_len = 0; probe_len < max_match_len; probe_len++) + if (*p++ != *q++) + break; + if (probe_len > match_len) + { + *pMatch_dist = dist; + if ((*pMatch_len = match_len = probe_len) == max_match_len) + return; + c0 = d->m_dict[pos + match_len]; + c1 = d->m_dict[pos + match_len - 1]; + } + } +} +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES */ + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES &&MINIZ_LITTLE_ENDIAN +static mz_bool tdefl_compress_fast(tdefl_compressor *d) +{ + /* Faster, minimally featured LZRW1-style match+parse loop with better register utilization. Intended for applications where raw throughput is valued more highly than ratio. */ + mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; + mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; + mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + + while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + { + const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; + mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); + d->m_src_buf_left -= num_bytes_to_process; + lookahead_size += num_bytes_to_process; + + while (num_bytes_to_process) + { + mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); + memcpy(d->m_dict + dst_pos, d->m_pSrc, n); + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); + d->m_pSrc += n; + dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; + num_bytes_to_process -= n; + } + + dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); + if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + break; + + while (lookahead_size >= 4) + { + mz_uint cur_match_dist, cur_match_len = 1; + mz_uint8 *pCur_dict = d->m_dict + cur_pos; + mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; + mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; + mz_uint probe_pos = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)lookahead_pos; + + if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + { + const mz_uint16 *p = (const mz_uint16 *)pCur_dict; + const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); + mz_uint32 probe_len = 32; + do + { + } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); + cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); + if (!probe_len) + cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; + + if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) + { + cur_match_len = 1; + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + else + { + mz_uint32 s0, s1; + cur_match_len = MZ_MIN(cur_match_len, lookahead_size); + + MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); + + cur_match_dist--; + + pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); + *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; + pLZ_code_buf += 3; + *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); + + s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; + s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; + d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; + + d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; + } + } + else + { + *pLZ_code_buf++ = (mz_uint8)first_trigram; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + d->m_huff_count[0][(mz_uint8)first_trigram]++; + } + + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + total_lz_bytes += cur_match_len; + lookahead_pos += cur_match_len; + dict_size = MZ_MIN(dict_size + cur_match_len, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; + MZ_ASSERT(lookahead_size >= cur_match_len); + lookahead_size -= cur_match_len; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + + while (lookahead_size) + { + mz_uint8 lit = d->m_dict[cur_pos]; + + total_lz_bytes++; + *pLZ_code_buf++ = lit; + *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); + if (--num_flags_left == 0) + { + num_flags_left = 8; + pLZ_flags = pLZ_code_buf++; + } + + d->m_huff_count[0][lit]++; + + lookahead_pos++; + dict_size = MZ_MIN(dict_size + 1, (mz_uint)TDEFL_LZ_DICT_SIZE); + cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + lookahead_size--; + + if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + { + int n; + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + total_lz_bytes = d->m_total_lz_bytes; + pLZ_code_buf = d->m_pLZ_code_buf; + pLZ_flags = d->m_pLZ_flags; + num_flags_left = d->m_num_flags_left; + } + } + } + + d->m_lookahead_pos = lookahead_pos; + d->m_lookahead_size = lookahead_size; + d->m_dict_size = dict_size; + d->m_total_lz_bytes = total_lz_bytes; + d->m_pLZ_code_buf = pLZ_code_buf; + d->m_pLZ_flags = pLZ_flags; + d->m_num_flags_left = num_flags_left; + return MZ_TRUE; +} +#endif /* MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + +static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) +{ + d->m_total_lz_bytes++; + *d->m_pLZ_code_buf++ = lit; + *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + d->m_huff_count[0][lit]++; +} + +static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) +{ + mz_uint32 s0, s1; + + MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); + + d->m_total_lz_bytes += match_len; + + d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); + + match_dist -= 1; + d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); + d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); + d->m_pLZ_code_buf += 3; + + *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); + if (--d->m_num_flags_left == 0) + { + d->m_num_flags_left = 8; + d->m_pLZ_flags = d->m_pLZ_code_buf++; + } + + s0 = s_tdefl_small_dist_sym[match_dist & 511]; + s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; + d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; + + if (match_len >= TDEFL_MIN_MATCH_LEN) + d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; +} + +static mz_bool tdefl_compress_normal(tdefl_compressor *d) +{ + const mz_uint8 *pSrc = d->m_pSrc; + size_t src_buf_left = d->m_src_buf_left; + tdefl_flush flush = d->m_flush; + + while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + { + mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; + /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ + if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + { + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; + mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; + mz_uint num_bytes_to_process = (mz_uint)MZ_MIN(src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); + const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; + src_buf_left -= num_bytes_to_process; + d->m_lookahead_size += num_bytes_to_process; + while (pSrc != pSrc_end) + { + mz_uint8 c = *pSrc++; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; + ins_pos++; + } + } + else + { + while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + { + mz_uint8 c = *pSrc++; + mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; + src_buf_left--; + d->m_dict[dst_pos] = c; + if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; + if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + { + mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; + mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); + d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; + d->m_hash[hash] = (mz_uint16)(ins_pos); + } + } + } + d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); + if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + break; + + /* Simple lazy/greedy parsing state machine. */ + len_to_move = 1; + cur_match_dist = 0; + cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); + cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; + if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + { + if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + { + mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; + cur_match_len = 0; + while (cur_match_len < d->m_lookahead_size) + { + if (d->m_dict[cur_pos + cur_match_len] != c) + break; + cur_match_len++; + } + if (cur_match_len < TDEFL_MIN_MATCH_LEN) + cur_match_len = 0; + else + cur_match_dist = 1; + } + } + else + { + tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); + } + if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + { + cur_match_dist = cur_match_len = 0; + } + if (d->m_saved_match_len) + { + if (cur_match_len > d->m_saved_match_len) + { + tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); + if (cur_match_len >= 128) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + d->m_saved_match_len = 0; + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[cur_pos]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + } + else + { + tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); + len_to_move = d->m_saved_match_len - 1; + d->m_saved_match_len = 0; + } + } + else if (!cur_match_dist) + tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); + else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + { + tdefl_record_match(d, cur_match_len, cur_match_dist); + len_to_move = cur_match_len; + } + else + { + d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; + d->m_saved_match_dist = cur_match_dist; + d->m_saved_match_len = cur_match_len; + } + /* Move the lookahead forward by len_to_move bytes. */ + d->m_lookahead_pos += len_to_move; + MZ_ASSERT(d->m_lookahead_size >= len_to_move); + d->m_lookahead_size -= len_to_move; + d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); + /* Check if it's time to flush the current LZ codes to the internal output buffer. */ + if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) + { + int n; + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + if ((n = tdefl_flush_block(d, 0)) != 0) + return (n < 0) ? MZ_FALSE : MZ_TRUE; + } + } + + d->m_pSrc = pSrc; + d->m_src_buf_left = src_buf_left; + return MZ_TRUE; +} + +static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) +{ + if (d->m_pIn_buf_size) + { + *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; + } + + if (d->m_pOut_buf_size) + { + size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); + memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); + d->m_output_flush_ofs += (mz_uint)n; + d->m_output_flush_remaining -= (mz_uint)n; + d->m_out_buf_ofs += n; + + *d->m_pOut_buf_size = d->m_out_buf_ofs; + } + + return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) +{ + if (!d) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return TDEFL_STATUS_BAD_PARAM; + } + + d->m_pIn_buf = pIn_buf; + d->m_pIn_buf_size = pIn_buf_size; + d->m_pOut_buf = pOut_buf; + d->m_pOut_buf_size = pOut_buf_size; + d->m_pSrc = (const mz_uint8 *)(pIn_buf); + d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; + d->m_out_buf_ofs = 0; + d->m_flush = flush; + + if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) + { + if (pIn_buf_size) + *pIn_buf_size = 0; + if (pOut_buf_size) + *pOut_buf_size = 0; + return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); + } + d->m_wants_to_finish |= (flush == TDEFL_FINISH); + + if ((d->m_output_flush_remaining) || (d->m_finished)) + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES &&MINIZ_LITTLE_ENDIAN + if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && + ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) + { + if (!tdefl_compress_fast(d)) + return d->m_prev_return_status; + } + else +#endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ + { + if (!tdefl_compress_normal(d)) + return d->m_prev_return_status; + } + + if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); + + if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + { + if (tdefl_flush_block(d, flush) < 0) + return d->m_prev_return_status; + d->m_finished = (flush == TDEFL_FINISH); + if (flush == TDEFL_FULL_FLUSH) + { + MZ_CLEAR_OBJ(d->m_hash); + MZ_CLEAR_OBJ(d->m_next); + d->m_dict_size = 0; + } + } + + return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); +} + +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) +{ + MZ_ASSERT(d->m_pPut_buf_func); + return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); +} + +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + d->m_pPut_buf_func = pPut_buf_func; + d->m_pPut_buf_user = pPut_buf_user; + d->m_flags = (mz_uint)(flags); + d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; + d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; + d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; + if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + MZ_CLEAR_OBJ(d->m_hash); + d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; + d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; + d->m_pLZ_code_buf = d->m_lz_code_buf + 1; + d->m_pLZ_flags = d->m_lz_code_buf; + d->m_num_flags_left = 8; + d->m_pOutput_buf = d->m_output_buf; + d->m_pOutput_buf_end = d->m_output_buf; + d->m_prev_return_status = TDEFL_STATUS_OKAY; + d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; + d->m_adler32 = 1; + d->m_pIn_buf = NULL; + d->m_pOut_buf = NULL; + d->m_pIn_buf_size = NULL; + d->m_pOut_buf_size = NULL; + d->m_flush = TDEFL_NO_FLUSH; + d->m_pSrc = NULL; + d->m_src_buf_left = 0; + d->m_out_buf_ofs = 0; + memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); + memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); + return TDEFL_STATUS_OKAY; +} + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) +{ + return d->m_prev_return_status; +} + +mz_uint32 tdefl_get_adler32(tdefl_compressor *d) +{ + return d->m_adler32; +} + +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + tdefl_compressor *pComp; + mz_bool succeeded; + if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + return MZ_FALSE; + pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + if (!pComp) + return MZ_FALSE; + succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); + succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); + MZ_FREE(pComp); + return succeeded; +} + +typedef struct +{ + size_t m_size, m_capacity; + mz_uint8 *m_pBuf; + mz_bool m_expandable; +} tdefl_output_buffer; + +static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) +{ + tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; + size_t new_size = p->m_size + len; + if (new_size > p->m_capacity) + { + size_t new_capacity = p->m_capacity; + mz_uint8 *pNew_buf; + if (!p->m_expandable) + return MZ_FALSE; + do + { + new_capacity = MZ_MAX(128U, new_capacity << 1U); + } while (new_size > new_capacity); + pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); + if (!pNew_buf) + return MZ_FALSE; + p->m_pBuf = pNew_buf; + p->m_capacity = new_capacity; + } + memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); + p->m_size = new_size; + return MZ_TRUE; +} + +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_len) + return nullptr; + else + *pOut_len = 0; + out_buf.m_expandable = MZ_TRUE; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return NULL; + *pOut_len = out_buf.m_size; + return out_buf.m_pBuf; +} + +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tdefl_output_buffer out_buf; + MZ_CLEAR_OBJ(out_buf); + if (!pOut_buf) + return 0; + out_buf.m_pBuf = (mz_uint8 *)pOut_buf; + out_buf.m_capacity = out_buf_len; + if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + return 0; + return out_buf.m_size; +} + +#ifndef MINIZ_NO_ZLIB_APIS +static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + +/* level may actually range from [0,10] (10 is a "hidden" max level, where we want a bit more compression and it's fine if throughput to fall off a cliff on some files). */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) +{ + mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); + if (window_bits > 0) + comp_flags |= TDEFL_WRITE_ZLIB_HEADER; + + if (!level) + comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; + else if (strategy == MZ_FILTERED) + comp_flags |= TDEFL_FILTER_MATCHES; + else if (strategy == MZ_HUFFMAN_ONLY) + comp_flags &= ~TDEFL_MAX_PROBES_MASK; + else if (strategy == MZ_FIXED) + comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; + else if (strategy == MZ_RLE) + comp_flags |= TDEFL_RLE_MATCHES; + + return comp_flags; +} +#endif /*MINIZ_NO_ZLIB_APIS */ + +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4204) /* nonstandard extension used : non-constant aggregate initializer (also supported by GNU C and C99, so no big deal) */ +#endif + +/* Simple PNG writer function by Alex Evans, 2011. Released into the public domain: https://gist.github.com/908299, more context at + http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. + This is actually a modification of Alex's original code so PNG files generated by this function pass pngcheck. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) +{ + /* Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was defined. */ + static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500 }; + tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); + tdefl_output_buffer out_buf; + int i, bpl = w * num_chans, y, z; + mz_uint32 c; + *pLen_out = 0; + if (!pComp) + return NULL; + MZ_CLEAR_OBJ(out_buf); + out_buf.m_expandable = MZ_TRUE; + out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); + if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) + { + MZ_FREE(pComp); + return NULL; + } + /* write dummy header */ + for (z = 41; z; --z) + tdefl_output_buffer_putter(&z, 1, &out_buf); + /* compress image data */ + tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); + for (y = 0; y < h; ++y) + { + tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); + tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); + } + if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) + { + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + /* write real header */ + *pLen_out = out_buf.m_size - 41; + { + static const mz_uint8 chans[] = { 0x00, 0x00, 0x04, 0x02, 0x06 }; + mz_uint8 pnghdr[41] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, + 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, + (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8) * pLen_out, 0x49, 0x44, 0x41, 0x54 }; + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); + for (i = 0; i < 4; ++i, c <<= 8) + ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); + memcpy(out_buf.m_pBuf, pnghdr, 41); + } + /* write footer (IDAT CRC-32, followed by IEND chunk) */ + if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + { + *pLen_out = 0; + MZ_FREE(pComp); + MZ_FREE(out_buf.m_pBuf); + return NULL; + } + c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); + for (i = 0; i < 4; ++i, c <<= 8) + (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); + /* compute final size of file, grab compressed data buffer and return */ + *pLen_out += 57; + MZ_FREE(pComp); + return out_buf.m_pBuf; +} +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) +{ + /* Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's where #defined out) */ + return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); +} + +/* Allocate the tdefl_compressor and tinfl_decompressor structures in C so that */ +/* non-C language bindings to tdefL_ and tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc() +{ + return (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); +} + +void tdefl_compressor_free(tdefl_compressor *pComp) +{ + MZ_FREE(pComp); +} + +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +#ifdef __cplusplus +} +#endif +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- Low-level Decompression (completely independent from all compression API's) */ + +#define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) +#define TINFL_MEMSET(p, c, l) memset(p, c, l) + +#define TINFL_CR_BEGIN \ + switch (r->m_state) \ + { \ + case 0: +#define TINFL_CR_RETURN(state_index, result) \ + do \ + { \ + status = result; \ + r->m_state = state_index; \ + goto common_exit; \ + case state_index: \ + ; \ + } \ + MZ_MACRO_END +#define TINFL_CR_RETURN_FOREVER(state_index, result) \ + do \ + { \ + for (;;) \ + { \ + TINFL_CR_RETURN(state_index, result); \ + } \ + } \ + MZ_MACRO_END +#define TINFL_CR_FINISH } + +#define TINFL_GET_BYTE(state_index, c) \ + do \ + { \ + while (pIn_buf_cur >= pIn_buf_end) \ + { \ + TINFL_CR_RETURN(state_index, (decomp_flags &TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ + } \ + c = *pIn_buf_cur++; \ + } \ + MZ_MACRO_END + +#define TINFL_NEED_BITS(state_index, n) \ + do \ + { \ + mz_uint c; \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < (mz_uint)(n)) +#define TINFL_SKIP_BITS(state_index, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END +#define TINFL_GET_BITS(state_index, b, n) \ + do \ + { \ + if (num_bits < (mz_uint)(n)) \ + { \ + TINFL_NEED_BITS(state_index, n); \ + } \ + b = bit_buf & ((1 << (n)) - 1); \ + bit_buf >>= (n); \ + num_bits -= (n); \ + } \ + MZ_MACRO_END + +/* TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes remaining in the input buffer falls below 2. */ +/* It reads just enough bytes from the input stream that are needed to decode the next Huffman code (and absolutely no more). It works by trying to fully decode a */ +/* Huffman code by using whatever bits are currently present in the bit buffer. If this fails, it reads another byte, and tries again until it succeeds or until the */ +/* bit buffer contains >=15 bits (deflate's max. Huffman code size). */ +#define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ + do \ + { \ + temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ + if (temp >= 0) \ + { \ + code_len = temp >> 9; \ + if ((code_len) && (num_bits >= code_len)) \ + break; \ + } \ + else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while ((temp < 0) && (num_bits >= (code_len + 1))); \ + if (temp >= 0) \ + break; \ + } \ + TINFL_GET_BYTE(state_index, c); \ + bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ + num_bits += 8; \ + } while (num_bits < 15); + +/* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ +/* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ +/* decode the next Huffman code.) Handling this properly is particularly important on raw deflate (non-zlib) streams, which aren't followed by a byte aligned adler-32. */ +/* The slow path is only executed at the very end of the input buffer. */ +/* v1.16: The original macro handled the case at the very end of the passed-in input buffer, but we also need to handle the case where the user passes in 1+zillion bytes */ +/* following the deflate data and our non-conservative read-ahead path won't kick in here on this code. This is much trickier. */ +#define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ + do \ + { \ + int temp; \ + mz_uint code_len, c; \ + if (num_bits < 15) \ + { \ + if ((pIn_buf_end - pIn_buf_cur) < 2) \ + { \ + TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ + } \ + else \ + { \ + bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ + pIn_buf_cur += 2; \ + num_bits += 16; \ + } \ + } \ + if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + code_len = temp >> 9, temp &= 511; \ + else \ + { \ + code_len = TINFL_FAST_LOOKUP_BITS; \ + do \ + { \ + temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ + } while (temp < 0); \ + } \ + sym = temp; \ + bit_buf >>= code_len; \ + num_bits -= code_len; \ + } \ + MZ_MACRO_END + +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) +{ + static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 }; + static const int s_length_extra[31] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0 }; + static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 }; + static const int s_dist_extra[32] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; + static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; + static const int s_min_table_sizes[3] = { 257, 1, 4 }; + + tinfl_status status = TINFL_STATUS_FAILED; + mz_uint32 num_bits, dist, counter, num_extra; + tinfl_bit_buf_t bit_buf; + const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; + mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; + size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t) - 1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; + + /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ + if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) + { + *pIn_buf_size = *pOut_buf_size = 0; + return TINFL_STATUS_BAD_PARAM; + } + + num_bits = r->m_num_bits; + bit_buf = r->m_bit_buf; + dist = r->m_dist; + counter = r->m_counter; + num_extra = r->m_num_extra; + dist_from_out_buf_start = r->m_dist_from_out_buf_start; + TINFL_CR_BEGIN + + bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; + r->m_z_adler32 = r->m_check_adler32 = 1; + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + TINFL_GET_BYTE(1, r->m_zhdr0); + TINFL_GET_BYTE(2, r->m_zhdr1); + counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); + if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); + if (counter) + { + TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); + } + } + + do + { + TINFL_GET_BITS(3, r->m_final, 3); + r->m_type = r->m_final >> 1; + if (r->m_type == 0) + { + TINFL_SKIP_BITS(5, num_bits & 7); + for (counter = 0; counter < 4; ++counter) + { + if (num_bits) + TINFL_GET_BITS(6, r->m_raw_header[counter], 8); + else + TINFL_GET_BYTE(7, r->m_raw_header[counter]); + } + if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + { + TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); + } + while ((counter) && (num_bits)) + { + TINFL_GET_BITS(51, dist, 8); + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)dist; + counter--; + } + while (counter) + { + size_t n; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); + } + while (pIn_buf_cur >= pIn_buf_end) + { + TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); + } + n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); + TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); + pIn_buf_cur += n; + pOut_buf_cur += n; + counter -= (mz_uint)n; + } + } + else if (r->m_type == 3) + { + TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); + } + else + { + if (r->m_type == 1) + { + mz_uint8 *p = r->m_tables[0].m_code_size; + mz_uint i; + r->m_table_sizes[0] = 288; + r->m_table_sizes[1] = 32; + TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); + for (i = 0; i <= 143; ++i) + *p++ = 8; + for (; i <= 255; ++i) + *p++ = 9; + for (; i <= 279; ++i) + *p++ = 7; + for (; i <= 287; ++i) + *p++ = 8; + } + else + { + for (counter = 0; counter < 3; counter++) + { + TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); + r->m_table_sizes[counter] += s_min_table_sizes[counter]; + } + MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); + for (counter = 0; counter < r->m_table_sizes[2]; counter++) + { + mz_uint s; + TINFL_GET_BITS(14, s, 3); + r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; + } + r->m_table_sizes[2] = 19; + } + for (; (int)r->m_type >= 0; r->m_type--) + { + int tree_next, tree_cur; + tinfl_huff_table *pTable; + mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; + pTable = &r->m_tables[r->m_type]; + MZ_CLEAR_OBJ(total_syms); + MZ_CLEAR_OBJ(pTable->m_look_up); + MZ_CLEAR_OBJ(pTable->m_tree); + for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + total_syms[pTable->m_code_size[i]]++; + used_syms = 0, total = 0; + next_code[0] = next_code[1] = 0; + for (i = 1; i <= 15; ++i) + { + used_syms += total_syms[i]; + next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); + } + if ((65536 != total) && (used_syms > 1)) + { + TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); + } + for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + { + mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; + if (!code_size) + continue; + cur_code = next_code[code_size]++; + for (l = code_size; l > 0; l--, cur_code >>= 1) + rev_code = (rev_code << 1) | (cur_code & 1); + if (code_size <= TINFL_FAST_LOOKUP_BITS) + { + mz_int16 k = (mz_int16)((code_size << 9) | sym_index); + while (rev_code < TINFL_FAST_LOOKUP_SIZE) + { + pTable->m_look_up[rev_code] = k; + rev_code += (1 << code_size); + } + continue; + } + if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + { + pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); + for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + { + tree_cur -= ((rev_code >>= 1) & 1); + if (!pTable->m_tree[-tree_cur - 1]) + { + pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; + tree_cur = tree_next; + tree_next -= 2; + } + else + tree_cur = pTable->m_tree[-tree_cur - 1]; + } + tree_cur -= ((rev_code >>= 1) & 1); + pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; + } + if (r->m_type == 2) + { + for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) + { + mz_uint s; + TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); + if (dist < 16) + { + r->m_len_codes[counter++] = (mz_uint8)dist; + continue; + } + if ((dist == 16) && (!counter)) + { + TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); + } + num_extra = "\02\03\07"[dist - 16]; + TINFL_GET_BITS(18, s, num_extra); + s += "\03\03\013"[dist - 16]; + TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); + counter += s; + } + if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + { + TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); + } + TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); + TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); + } + } + for (;;) + { + mz_uint8 *pSrc; + for (;;) + { + if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + { + TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); + if (counter >= 256) + break; + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = (mz_uint8)counter; + } + else + { + int sym2; + mz_uint code_len; +#if TINFL_USE_64BIT_BITBUF + if (num_bits < 30) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 4; + num_bits += 32; + } +#else + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + counter = sym2; + bit_buf >>= code_len; + num_bits -= code_len; + if (counter & 256) + break; + +#if !TINFL_USE_64BIT_BITBUF + if (num_bits < 15) + { + bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); + pIn_buf_cur += 2; + num_bits += 16; + } +#endif + if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + code_len = sym2 >> 9; + else + { + code_len = TINFL_FAST_LOOKUP_BITS; + do + { + sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; + } while (sym2 < 0); + } + bit_buf >>= code_len; + num_bits -= code_len; + + pOut_buf_cur[0] = (mz_uint8)counter; + if (sym2 & 256) + { + pOut_buf_cur++; + counter = sym2; + break; + } + pOut_buf_cur[1] = (mz_uint8)sym2; + pOut_buf_cur += 2; + } + } + if ((counter &= 511) == 256) + break; + + num_extra = s_length_extra[counter - 257]; + counter = s_length_base[counter - 257]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(25, extra_bits, num_extra); + counter += extra_bits; + } + + TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); + num_extra = s_dist_extra[dist]; + dist = s_dist_base[dist]; + if (num_extra) + { + mz_uint extra_bits; + TINFL_GET_BITS(27, extra_bits, num_extra); + dist += extra_bits; + } + + dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; + if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + { + TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); + } + + pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); + + if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + { + while (counter--) + { + while (pOut_buf_cur >= pOut_buf_end) + { + TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); + } + *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; + } + continue; + } +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES + else if ((counter >= 9) && (counter <= dist)) + { + const mz_uint8 *pSrc_end = pSrc + (counter & ~7); + do + { + ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; + ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; + pOut_buf_cur += 8; + } while ((pSrc += 8) < pSrc_end); + if ((counter &= 7) < 3) + { + if (counter) + { + pOut_buf_cur[0] = pSrc[0]; + if (counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + continue; + } + } +#endif + do + { + pOut_buf_cur[0] = pSrc[0]; + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur[2] = pSrc[2]; + pOut_buf_cur += 3; + pSrc += 3; + } while ((int)(counter -= 3) > 2); + if ((int)counter > 0) + { + pOut_buf_cur[0] = pSrc[0]; + if ((int)counter > 1) + pOut_buf_cur[1] = pSrc[1]; + pOut_buf_cur += counter; + } + } + } + } while (!(r->m_final & 1)); + + /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ + TINFL_SKIP_BITS(32, num_bits & 7); + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + bit_buf &= (tinfl_bit_buf_t)((1ULL << num_bits) - 1ULL); + MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ + + if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + { + for (counter = 0; counter < 4; ++counter) + { + mz_uint s; + if (num_bits) + TINFL_GET_BITS(41, s, 8); + else + TINFL_GET_BYTE(42, s); + r->m_z_adler32 = (r->m_z_adler32 << 8) | s; + } + } + TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); + + TINFL_CR_FINISH + +common_exit: + /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ + /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ + /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ + if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) + { + while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + { + --pIn_buf_cur; + num_bits -= 8; + } + } + r->m_num_bits = num_bits; + r->m_bit_buf = bit_buf & (tinfl_bit_buf_t)((1ULL << num_bits) - 1ULL); + r->m_dist = dist; + r->m_counter = counter; + r->m_num_extra = num_extra; + r->m_dist_from_out_buf_start = dist_from_out_buf_start; + *pIn_buf_size = pIn_buf_cur - pIn_buf_next; + *pOut_buf_size = pOut_buf_cur - pOut_buf_next; + if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + { + const mz_uint8 *ptr = pOut_buf_next; + size_t buf_len = *pOut_buf_size; + mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; + size_t block_len = buf_len % 5552; + while (buf_len) + { + for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + { + s1 += ptr[0], s2 += s1; + s1 += ptr[1], s2 += s1; + s1 += ptr[2], s2 += s1; + s1 += ptr[3], s2 += s1; + s1 += ptr[4], s2 += s1; + s1 += ptr[5], s2 += s1; + s1 += ptr[6], s2 += s1; + s1 += ptr[7], s2 += s1; + } + for (; i < block_len; ++i) + s1 += *ptr++, s2 += s1; + s1 %= 65521U, s2 %= 65521U; + buf_len -= block_len; + block_len = 5552; + } + r->m_check_adler32 = (s2 << 16) + s1; + if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) + status = TINFL_STATUS_ADLER32_MISMATCH; + } + return status; +} + +/* Higher level helper functions. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) +{ + tinfl_decompressor decomp; + void *pBuf = NULL, *pNew_buf; + size_t src_buf_ofs = 0, out_buf_capacity = 0; + *pOut_len = 0; + tinfl_init(&decomp); + for (;;) + { + size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, + (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + src_buf_ofs += src_buf_size; + *pOut_len += dst_buf_size; + if (status == TINFL_STATUS_DONE) + break; + new_out_buf_capacity = out_buf_capacity * 2; + if (new_out_buf_capacity < 128) + new_out_buf_capacity = 128; + pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); + if (!pNew_buf) + { + MZ_FREE(pBuf); + *pOut_len = 0; + return NULL; + } + pBuf = pNew_buf; + out_buf_capacity = new_out_buf_capacity; + } + return pBuf; +} + +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) +{ + tinfl_decompressor decomp; + tinfl_status status; + tinfl_init(&decomp); + status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); + return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; +} + +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) +{ + int result = 0; + tinfl_decompressor decomp; + mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); + size_t in_buf_ofs = 0, dict_ofs = 0; + if (!pDict) + return TINFL_STATUS_FAILED; + tinfl_init(&decomp); + for (;;) + { + size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; + tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, + (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); + in_buf_ofs += in_buf_size; + if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + break; + if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + { + result = (status == TINFL_STATUS_DONE); + break; + } + dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); + } + MZ_FREE(pDict); + *pIn_buf_size = in_buf_ofs; + return result; +} + +tinfl_decompressor *tinfl_decompressor_alloc() +{ + tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); + if (pDecomp) + tinfl_init(pDecomp); + return pDecomp; +} + +void tinfl_decompressor_free(tinfl_decompressor *pDecomp) +{ + MZ_FREE(pDecomp); +} + +#ifdef __cplusplus +} +#endif +/************************************************************************** + * + * Copyright 2013-2014 RAD Game Tools and Valve Software + * Copyright 2010-2014 Rich Geldreich and Tenacious Software LLC + * Copyright 2016 Martin Raiber + * All Rights Reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + **************************************************************************/ + + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- .ZIP archive reading */ + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include + +#if defined(_MSC_VER) || defined(__MINGW64__) +static FILE *mz_fopen(const char *pFilename, const char *pMode) +{ + FILE *pFile = NULL; + fopen_s(&pFile, pFilename, pMode); + return pFile; +} +static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) +{ + FILE *pFile = NULL; + if (freopen_s(&pFile, pPath, pMode, pStream)) + return NULL; + return pFile; +} +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN mz_fopen +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 _ftelli64 +#define MZ_FSEEK64 _fseeki64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN mz_freopen +#define MZ_DELETE_FILE remove +#elif defined(__MINGW32__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT _stat +#define MZ_FILE_STAT _stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__TINYC__) +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftell +#define MZ_FSEEK64 fseek +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__GNUC__) && _LARGEFILE64_SOURCE +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen64(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello64 +#define MZ_FSEEK64 fseeko64 +#define MZ_FILE_STAT_STRUCT stat64 +#define MZ_FILE_STAT stat64 +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen64(p, m, s) +#define MZ_DELETE_FILE remove +#elif defined(__APPLE__) && _LARGEFILE64_SOURCE +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(p, m, s) freopen(p, m, s) +#define MZ_DELETE_FILE remove + +#else +#pragma message("Using fopen, ftello, fseeko, stat() etc. path for file I/O - this path may not support large files.") +#ifndef MINIZ_NO_TIME +#include +#endif +#define MZ_FOPEN(f, m) fopen(f, m) +#define MZ_FCLOSE fclose +#define MZ_FREAD fread +#define MZ_FWRITE fwrite +#define MZ_FTELL64 ftello +#define MZ_FSEEK64 fseeko +#define MZ_FILE_STAT_STRUCT stat +#define MZ_FILE_STAT stat +#define MZ_FFLUSH fflush +#define MZ_FREOPEN(f, m, s) freopen(f, m, s) +#define MZ_DELETE_FILE remove +#endif /* #ifdef _MSC_VER */ +#endif /* #ifdef MINIZ_NO_STDIO */ + +#define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) + +/* Various ZIP archive enums. To completely avoid cross platform compiler alignment and platform endian issues, miniz.c doesn't use structs for any of this stuff. */ +enum +{ + /* ZIP archive identifiers and record sizes */ + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, + MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, + MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, + + /* ZIP64 archive identifier and record sizes */ + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG = 0x07064b50, + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE = 56, + MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE = 20, + MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID = 0x0001, + MZ_ZIP_DATA_DESCRIPTOR_ID = 0x08074b50, + MZ_ZIP_DATA_DESCRIPTER_SIZE64 = 24, + MZ_ZIP_DATA_DESCRIPTER_SIZE32 = 16, + + /* Central directory header record offsets */ + MZ_ZIP_CDH_SIG_OFS = 0, + MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, + MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, + MZ_ZIP_CDH_BIT_FLAG_OFS = 8, + MZ_ZIP_CDH_METHOD_OFS = 10, + MZ_ZIP_CDH_FILE_TIME_OFS = 12, + MZ_ZIP_CDH_FILE_DATE_OFS = 14, + MZ_ZIP_CDH_CRC32_OFS = 16, + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, + MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, + MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, + MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, + MZ_ZIP_CDH_DISK_START_OFS = 34, + MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, + MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, + + /* Local directory header offsets */ + MZ_ZIP_LDH_SIG_OFS = 0, + MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, + MZ_ZIP_LDH_BIT_FLAG_OFS = 6, + MZ_ZIP_LDH_METHOD_OFS = 8, + MZ_ZIP_LDH_FILE_TIME_OFS = 10, + MZ_ZIP_LDH_FILE_DATE_OFS = 12, + MZ_ZIP_LDH_CRC32_OFS = 14, + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, + MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, + MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, + MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR = 1 << 3, + + /* End of central directory offsets */ + MZ_ZIP_ECDH_SIG_OFS = 0, + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, + MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, + MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, + MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, + + /* ZIP64 End of central directory locator offsets */ + MZ_ZIP64_ECDL_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDL_NUM_DISK_CDIR_OFS = 4, /* 4 bytes */ + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS = 8, /* 8 bytes */ + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS = 16, /* 4 bytes */ + + /* ZIP64 End of central directory header offsets */ + MZ_ZIP64_ECDH_SIG_OFS = 0, /* 4 bytes */ + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS = 4, /* 8 bytes */ + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS = 12, /* 2 bytes */ + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS = 14, /* 2 bytes */ + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS = 16, /* 4 bytes */ + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS = 20, /* 4 bytes */ + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 24, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS = 32, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_SIZE_OFS = 40, /* 8 bytes */ + MZ_ZIP64_ECDH_CDIR_OFS_OFS = 48, /* 8 bytes */ + MZ_ZIP_VERSION_MADE_BY_DOS_FILESYSTEM_ID = 0, + MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG = 0x10, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED = 1, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG = 32, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION = 64, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED = 8192, + MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8 = 1 << 11 +}; + +typedef struct +{ + void *m_p; + size_t m_size, m_capacity; + mz_uint m_element_size; +} mz_zip_array; + +struct mz_zip_internal_state_tag +{ + mz_zip_array m_central_dir; + mz_zip_array m_central_dir_offsets; + mz_zip_array m_sorted_central_dir_offsets; + + /* The flags passed in when the archive is initially opened. */ + uint32_t m_init_flags; + + /* MZ_TRUE if the archive has a zip64 end of central directory headers, etc. */ + mz_bool m_zip64; + + /* MZ_TRUE if we found zip64 extended info in the central directory (m_zip64 will also be slammed to true too, even if we didn't find a zip64 end of central dir header, etc.) */ + mz_bool m_zip64_has_extended_info_fields; + + /* These fields are used by the file, FILE, memory, and memory/heap read/write helpers. */ + MZ_FILE *m_pFile; + mz_uint64 m_file_archive_start_ofs; + + void *m_pMem; + size_t m_mem_size; + size_t m_mem_capacity; +}; + +#define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) (array_ptr)->m_element_size = element_size + +#if defined(DEBUG) || defined(_DEBUG) || defined(NDEBUG) +static MZ_FORCEINLINE mz_uint mz_zip_array_range_check(const mz_zip_array *pArray, mz_uint index) +{ + MZ_ASSERT(index < pArray->m_size); + return index; +} +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[mz_zip_array_range_check(array_ptr, index)] +#else +#define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) ((element_type *)((array_ptr)->m_p))[index] +#endif + +static MZ_FORCEINLINE void mz_zip_array_init(mz_zip_array *pArray, mz_uint32 element_size) +{ + memset(pArray, 0, sizeof(mz_zip_array)); + pArray->m_element_size = element_size; +} + +static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) +{ + pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); + memset(pArray, 0, sizeof(mz_zip_array)); +} + +static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) +{ + void *pNew_p; + size_t new_capacity = min_new_capacity; + MZ_ASSERT(pArray->m_element_size); + if (pArray->m_capacity >= min_new_capacity) + return MZ_TRUE; + if (growing) + { + new_capacity = MZ_MAX(1, pArray->m_capacity); + while (new_capacity < min_new_capacity) + new_capacity *= 2; + } + if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) + return MZ_FALSE; + pArray->m_p = pNew_p; + pArray->m_capacity = new_capacity; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) +{ + if (new_capacity > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + return MZ_FALSE; + } + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) +{ + if (new_size > pArray->m_capacity) + { + if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + return MZ_FALSE; + } + pArray->m_size = new_size; + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) +{ + return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); +} + +static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) +{ + size_t orig_size = pArray->m_size; + if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + return MZ_FALSE; + memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); + return MZ_TRUE; +} + +#ifndef MINIZ_NO_TIME +static MZ_TIME_T mz_zip_dos_to_time_t(int dos_time, int dos_date) +{ + struct tm tm; + memset(&tm, 0, sizeof(tm)); + tm.tm_isdst = -1; + tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; + tm.tm_mon = ((dos_date >> 5) & 15) - 1; + tm.tm_mday = dos_date & 31; + tm.tm_hour = (dos_time >> 11) & 31; + tm.tm_min = (dos_time >> 5) & 63; + tm.tm_sec = (dos_time << 1) & 62; + return mktime(&tm); +} + +static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) +{ +#ifdef _MSC_VER + struct tm tm_struct; + struct tm *tm = &tm_struct; + errno_t err = localtime_s(tm, &time); + if (err) + { + *pDOS_date = 0; + *pDOS_time = 0; + return; + } +#else + struct tm *tm = localtime(&time); +#endif /* #ifdef _MSC_VER */ + + *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); + *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); +} + +#ifndef MINIZ_NO_STDIO +static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *pTime) +{ + struct MZ_FILE_STAT_STRUCT file_stat; + + /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ + if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + return MZ_FALSE; + + *pTime = file_stat.st_mtime; + + return MZ_TRUE; +} + +static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_time, MZ_TIME_T modified_time) +{ + struct utimbuf t; + + memset(&t, 0, sizeof(t)); + t.actime = access_time; + t.modtime = modified_time; + + return !utime(pFilename, &t); +} +#endif /* #ifndef MINIZ_NO_STDIO */ +#endif /* #ifndef MINIZ_NO_TIME */ + +static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + if (pZip) + pZip->m_last_error = err_num; + return MZ_FALSE; +} + +static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) +{ + (void)flags; + if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = 0; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + pZip->m_last_error = MZ_ZIP_NO_ERROR; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + pZip->m_pState->m_init_flags = flags; + pZip->m_pState->m_zip64 = MZ_FALSE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_FALSE; + + pZip->m_zip_mode = MZ_ZIP_MODE_READING; + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (l_len < r_len) : (l < r); +} + +#define MZ_SWAP_UINT32(a, b) \ + do \ + { \ + mz_uint32 t = a; \ + a = b; \ + b = t; \ + } \ + MZ_MACRO_END + +/* Heap sort of lowercased filenames, used to help accelerate plain central directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), but it could allocate memory.) */ +static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices; + mz_uint32 start, end; + const mz_uint32 size = pZip->m_total_files; + + if (size <= 1U) + return; + + pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + + start = (size - 2U) >> 1U; + for (;;) + { + mz_uint64 child, root = start; + for (;;) + { + if ((child = (root << 1U) + 1U) >= size) + break; + child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + if (!start) + break; + start--; + } + + end = size - 1; + while (end > 0) + { + mz_uint64 child, root = 0; + MZ_SWAP_UINT32(pIndices[end], pIndices[0]); + for (;;) + { + if ((child = (root << 1U) + 1U) >= end) + break; + child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); + if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + break; + MZ_SWAP_UINT32(pIndices[root], pIndices[child]); + root = child; + } + end--; + } +} + +static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 record_sig, mz_uint32 record_size, mz_int64 *pOfs) +{ + mz_int64 cur_file_ofs; + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + + /* Basic sanity checks - reject files which are too small */ + if (pZip->m_archive_size < record_size) + return MZ_FALSE; + + /* Find the record by scanning the file from the end towards the beginning. */ + cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); + for (;;) + { + int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); + + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + return MZ_FALSE; + + for (i = n - 4; i >= 0; --i) + { + mz_uint s = MZ_READ_LE32(pBuf + i); + if (s == record_sig) + { + if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + break; + } + } + + if (i >= 0) + { + cur_file_ofs += i; + break; + } + + /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ + if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) + return MZ_FALSE; + + cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); + } + + *pOfs = cur_file_ofs; + return MZ_TRUE; +} + +static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flags) +{ + mz_uint cdir_size = 0, cdir_entries_on_this_disk = 0, num_this_disk = 0, cdir_disk_index = 0; + mz_uint64 cdir_ofs = 0; + mz_int64 cur_file_ofs = 0; + const mz_uint8 *p; + + mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; + mz_uint8 *pBuf = (mz_uint8 *)buf_u32; + mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); + mz_uint32 zip64_end_of_central_dir_locator_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_locator = (mz_uint8 *)zip64_end_of_central_dir_locator_u32; + + mz_uint32 zip64_end_of_central_dir_header_u32[(MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pZip64_end_of_central_dir = (mz_uint8 *)zip64_end_of_central_dir_header_u32; + + mz_uint64 zip64_end_of_central_dir_ofs = 0; + + /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ + if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); + + /* Read and verify the end of central directory record. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + { + if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) + { + zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); + if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + { + if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) + { + pZip->m_pState->m_zip64 = MZ_TRUE; + } + } + } + } + } + + pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS); + cdir_entries_on_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); + cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); + cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); + cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); + + if (pZip->m_pState->m_zip64) + { + mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); + mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); + mz_uint64 zip64_cdir_total_entries_on_this_disk = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS); + mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); + mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); + + if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (zip64_total_num_of_disks != 1U) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + /* Check for miniz's practical limits */ + if (zip64_cdir_total_entries > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; + + if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; + + /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ + if (zip64_size_of_central_directory > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + cdir_size = (mz_uint32)zip64_size_of_central_directory; + + num_this_disk = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_THIS_DISK_OFS); + + cdir_disk_index = MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_NUM_DISK_CDIR_OFS); + + cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); + } + + if (pZip->m_total_files != cdir_entries_on_this_disk) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pZip->m_central_directory_file_ofs = cdir_ofs; + + if (pZip->m_total_files) + { + mz_uint i, n; + /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ + if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (sort_central_dir) + { + if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + /* Now create an index into the central directory file records, do some basic sanity checking on each record */ + p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; + for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + { + mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; + mz_uint64 comp_size, decomp_size, local_header_ofs; + + if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); + + if (sort_central_dir) + MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + (ext_data_size) && + (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = ext_data_size; + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; + + do + { + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + mz_uint32 field_id = MZ_READ_LE16(pExtra_data); + mz_uint32 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ + pZip->m_pState->m_zip64 = MZ_TRUE; + pZip->m_pState->m_zip64_has_extended_info_fields = MZ_TRUE; + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ + if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) + { + if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); + if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); + + if (comp_size != MZ_UINT32_MAX) + { + if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + n -= total_header_size; + p += total_header_size; + } + } + + if (sort_central_dir) + mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); + + return MZ_TRUE; +} + +void mz_zip_zero_struct(mz_zip_archive *pZip) +{ + if (pZip) + MZ_CLEAR_OBJ(*pZip); +} + +static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_bool status = MZ_TRUE; + + if (!pZip) + return MZ_FALSE; + + if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; + + return MZ_FALSE; + } + + if (pZip->m_pState) + { + mz_zip_internal_state *pState = pZip->m_pState; + pZip->m_pState = NULL; + + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; + status = MZ_FALSE; + } + } + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + } + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + + return status; +} + +mz_bool mz_zip_reader_end(mz_zip_archive *pZip) +{ + return mz_zip_reader_end_internal(pZip, MZ_TRUE); +} +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) +{ + if ((!pZip) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_archive_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); + memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); + return s; +} + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) +{ + if (!pMem) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; + pZip->m_archive_size = size; + pZip->m_pRead = mz_zip_mem_read_func; + pZip->m_pIO_opaque = pZip; + +#ifdef __cplusplus + pZip->m_pState->m_pMem = const_cast(pMem); +#else + pZip->m_pState->m_pMem = (void *)pMem; +#endif + + pZip->m_pState->m_mem_size = size; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + return 0; + + return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) +{ + return mz_zip_reader_init_file_v2(pZip, pFilename, flags, 0, 0); +} + +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) +{ + if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + mz_uint64 file_size; + MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + file_size = archive_size; + if (!file_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + { + MZ_FCLOSE(pFile); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + } + + file_size = MZ_FTELL64(pFile); + } + + /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ + + if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + + if (!mz_zip_reader_init_internal(pZip, flags)) + { + MZ_FCLOSE(pFile); + return MZ_FALSE; + } + + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + pZip->m_pRead = mz_zip_file_read_func; + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = file_size; + pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags) +{ + mz_uint64 cur_file_ofs; + + if ((!pZip) || (!pFile)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + cur_file_ofs = MZ_FTELL64(pFile); + + if (!archive_size) + { + if (MZ_FSEEK64(pFile, 0, SEEK_END)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + + archive_size = MZ_FTELL64(pFile) - cur_file_ofs; + + if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); + } + + if (!mz_zip_reader_init_internal(pZip, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + pZip->m_pState->m_pFile = pFile; + pZip->m_archive_size = archive_size; + pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; + + if (!mz_zip_reader_read_central_dir(pZip, flags)) + { + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) +{ + if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + return NULL; + return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); +} + +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint m_bit_flag; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + return (m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) != 0; +} + +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint bit_flag; + mz_uint method; + + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); + bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + + if ((method != 0) && (method != MZ_DEFLATED)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + return MZ_FALSE; + } + + if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + return MZ_FALSE; + } + + if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) + { + mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) +{ + mz_uint filename_len, attribute_mapping_id, external_attr; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_len) + { + if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + return MZ_TRUE; + } + + /* Bugfix: This code was also checking if the internal attribute was non-zero, which wasn't correct. */ + /* Most/all zip writers (hopefully) set DOS file/directory attributes in the low 16-bits, so check for the DOS directory flag and ignore the source OS ID in the created by field. */ + /* FIXME: Remove this check? Is it necessary - we already check the filename. */ + attribute_mapping_id = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS) >> 8; + (void)attribute_mapping_id; + + external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) + { + return MZ_TRUE; + } + + return MZ_FALSE; +} + +static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_index, const mz_uint8 *pCentral_dir_header, mz_zip_archive_file_stat *pStat, mz_bool *pFound_zip64_extra_data) +{ + mz_uint n; + const mz_uint8 *p = pCentral_dir_header; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_FALSE; + + if ((!p) || (!pStat)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Extract fields from the central directory record. */ + pStat->m_file_index = file_index; + pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); + pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); + pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); + pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); + pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); +#ifndef MINIZ_NO_TIME + pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); +#endif + pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); + pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); + pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); + pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); + + /* Copy as much of the filename and comment as possible. */ + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); + memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pStat->m_filename[n] = '\0'; + + n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); + n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); + pStat->m_comment_size = n; + memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); + pStat->m_comment[n] = '\0'; + + /* Set some flags for convienance */ + pStat->m_is_directory = mz_zip_reader_is_file_a_directory(pZip, file_index); + pStat->m_is_encrypted = mz_zip_reader_is_file_encrypted(pZip, file_index); + pStat->m_is_supported = mz_zip_reader_is_file_supported(pZip, file_index); + + /* See if we need to read any zip64 extended information fields. */ + /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ + if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) + { + /* Attempt to find zip64 extended information field in the entry's extra data */ + mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); + + if (extra_size_remaining) + { + const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + + do + { + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + mz_uint32 field_id = MZ_READ_LE16(pExtra_data); + mz_uint32 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + + if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; + mz_uint32 field_data_remaining = field_data_size; + + if (pFound_zip64_extra_data) + *pFound_zip64_extra_data = MZ_TRUE; + + if (pStat->m_uncomp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_uncomp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_comp_size == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_comp_size = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + if (pStat->m_local_header_ofs == MZ_UINT32_MAX) + { + if (field_data_remaining < sizeof(mz_uint64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); + pField_data += sizeof(mz_uint64); + field_data_remaining -= sizeof(mz_uint64); + } + + break; + } + + pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; + extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; + } while (extra_size_remaining); + } + } + + return MZ_TRUE; +} + +static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) +{ + mz_uint i; + if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + return 0 == memcmp(pA, pB, len); + for (i = 0; i < len; ++i) + if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + return MZ_FALSE; + return MZ_TRUE; +} + +static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) +{ + const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; + mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); + mz_uint8 l = 0, r = 0; + pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + pE = pL + MZ_MIN(l_len, r_len); + while (pL < pE) + { + if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + break; + pL++; + pR++; + } + return (pL == pE) ? (int)(l_len - r_len) : (l - r); +} + +static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename, mz_uint32 *pIndex) +{ + mz_zip_internal_state *pState = pZip->m_pState; + const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; + const mz_zip_array *pCentral_dir = &pState->m_central_dir; + mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); + const uint32_t size = pZip->m_total_files; + const mz_uint filename_len = (mz_uint)strlen(pFilename); + + if (pIndex) + *pIndex = 0; + + if (size) + { + /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ + /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ + mz_int64 l = 0, h = (mz_int64)size - 1; + + while (l <= h) + { + mz_int64 m = l + ((h - l) >> 1); + uint32_t file_index = pIndices[(uint32_t)m]; + + int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); + if (!comp) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + else if (comp < 0) + l = m + 1; + else + h = m - 1; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) +{ + mz_uint32 index; + if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + return -1; + else + return (int)index; +} + +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex) +{ + mz_uint file_index; + size_t name_len, comment_len; + + if (pIndex) + *pIndex = 0; + + if ((!pZip) || (!pZip->m_pState) || (!pName)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* See if we can use a binary search */ + if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && + ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) + { + return mz_zip_locate_file_binary_search(pZip, pName, pIndex); + } + + /* Locate the entry by scanning the entire central directory */ + name_len = strlen(pName); + if (name_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + comment_len = pComment ? strlen(pComment) : 0; + if (comment_len > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + for (file_index = 0; file_index < pZip->m_total_files; file_index++) + { + const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); + mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); + const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; + if (filename_len < name_len) + continue; + if (comment_len) + { + mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); + const char *pFile_comment = pFilename + filename_len + file_extra_len; + if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) + continue; + } + if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + { + int ofs = filename_len - 1; + do + { + if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + break; + } while (--ofs >= 0); + ofs++; + pFilename += ofs; + filename_len -= ofs; + } + if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) + { + if (pIndex) + *pIndex = file_index; + return MZ_TRUE; + } + } + + return mz_zip_set_error(pZip, MZ_ZIP_FILE_NOT_FOUND); +} + +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + int status = TINFL_STATUS_DONE; + mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; + mz_zip_archive_file_stat file_stat; + void *pRead_buf; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + tinfl_decompressor inflator; + + if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Ensure supplied output buffer is large enough. */ + needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; + if (buf_size < needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); + + /* Read and parse the local directory entry. */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) + { + if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + } +#endif + + return MZ_TRUE; + } + + /* Decompress the file either directly from memory or from a file input buffer. */ + tinfl_init(&inflator); + + if (pZip->m_pState->m_pMem) + { + /* Read directly from the archive in memory. */ + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else if (pUser_read_buf) + { + /* Use a user provided read buffer. */ + if (!user_read_buf_size) + return MZ_FALSE; + pRead_buf = (mz_uint8 *)pUser_read_buf; + read_buf_size = user_read_buf_size; + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + else + { + /* Temporarily allocate a read buffer. */ + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + do + { + /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ + size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + status = TINFL_STATUS_FAILED; + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + out_buf_ofs += out_buf_size; + } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + + if (status == TINFL_STATUS_DONE) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); +} + +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); +} + +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) +{ + return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); +} + +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) +{ + mz_uint64 comp_size, uncomp_size, alloc_size; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + void *pBuf; + + if (pSize) + *pSize = 0; + + if (!p) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return NULL; + } + + comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); + uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); + + alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; + if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + return NULL; + } + + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return NULL; + } + + if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return NULL; + } + + if (pSize) + *pSize = (size_t)alloc_size; + return pBuf; +} + +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + { + if (pSize) + *pSize = 0; + return nullptr; + } + return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); +} + +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + int status = TINFL_STATUS_DONE; + mz_uint file_crc32 = MZ_CRC32_INIT; + mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; + mz_zip_archive_file_stat file_stat; + void *pRead_buf = NULL; + void *pWrite_buf = NULL; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + + if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports decompressing stored and deflate. */ + if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ + cur_file_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + /* Decompress the file either directly from memory or from a file input buffer. */ + if (pZip->m_pState->m_pMem) + { + pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; + read_buf_size = read_buf_avail = file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + read_buf_avail = 0; + comp_remaining = file_stat.m_comp_size; + } + + if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + { + /* The file is stored or the caller has requested the compressed data. */ + if (pZip->m_pState->m_pMem) + { + if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + } + else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); +#endif + } + + cur_file_ofs += file_stat.m_comp_size; + out_buf_ofs += file_stat.m_comp_size; + comp_remaining = 0; + } + else + { + while (comp_remaining) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); + } +#endif + + if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + + cur_file_ofs += read_buf_avail; + out_buf_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + } + } + } + else + { + tinfl_decompressor inflator; + tinfl_init(&inflator); + + if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + status = TINFL_STATUS_FAILED; + } + else + { + do + { + mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); + if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + { + read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); + if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + cur_file_ofs += read_buf_avail; + comp_remaining -= read_buf_avail; + read_buf_ofs = 0; + } + + in_buf_size = (size_t)read_buf_avail; + status = tinfl_decompress(&inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); + read_buf_avail -= in_buf_size; + read_buf_ofs += in_buf_size; + + if (out_buf_size) + { + if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); +#endif + if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + break; + } + } + } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } + } + + if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + { + /* Make sure the entire file was decompressed, and check its CRC. */ + if (out_buf_ofs != file_stat.m_uncomp_size) + { + mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); + status = TINFL_STATUS_FAILED; + } +#ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS + else if (file_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); + status = TINFL_STATUS_FAILED; + } +#endif + } + + if (!pZip->m_pState->m_pMem) + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + + if (pWrite_buf) + pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); + + return status == TINFL_STATUS_DONE; +} + +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) +{ + (void)ofs; + + return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); +} + +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) +{ + mz_bool status; + mz_zip_archive_file_stat file_stat; + MZ_FILE *pFile; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + pFile = MZ_FOPEN(pDst_filename, "wb"); + if (!pFile) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); + + if (MZ_FCLOSE(pFile) == EOF) + { + if (status) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + + status = MZ_FALSE; + } + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + if (status) + mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); +#endif + + return status; +} + +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); +} + +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *pFile, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + + if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + return MZ_FALSE; + + if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); +} + +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) +{ + mz_uint32 file_index; + if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + return MZ_FALSE; + + return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static size_t mz_zip_compute_crc32_callback(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_uint32 *p = (mz_uint32 *)pOpaque; + (void)file_ofs; + *p = (mz_uint32)mz_crc32(*p, (const mz_uint8 *)pBuf, n); + return n; +} + +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags) +{ + mz_zip_archive_file_stat file_stat; + mz_zip_internal_state *pState; + const mz_uint8 *pCentral_dir_header; + mz_bool found_zip64_ext_data_in_cdir = MZ_FALSE; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint64 local_header_ofs = 0; + mz_uint32 local_header_filename_len, local_header_extra_len, local_header_crc32; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_uint32 uncomp_crc32 = MZ_CRC32_INIT; + mz_bool has_data_descriptor; + mz_uint32 local_header_bit_flags; + + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (file_index > pZip->m_total_files) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); + + if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) + return MZ_FALSE; + + /* A directory or zero length file */ + if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) + return MZ_TRUE; + + /* Encryption and patch files are not supported. */ + if (file_stat.m_is_encrypted) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); + + /* This function only supports stored and deflate. */ + if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); + + if (!file_stat.m_is_supported) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); + + /* Read and parse the local directory entry. */ + local_header_ofs = file_stat.m_local_header_ofs; + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + local_header_crc32 = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_CRC32_OFS); + local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + has_data_descriptor = (local_header_bit_flags & 8) != 0; + + if (local_header_filename_len != strlen(file_stat.m_filename)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (local_header_filename_len) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ + if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + goto handle_failure; + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ + /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ + if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) + { + mz_uint8 descriptor_buf[32]; + + mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; + + if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + goto handle_failure; + } + + mz_bool has_id = (MZ_READ_LE32(descriptor_buf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + const mz_uint8 *pSrc = has_id ? (descriptor_buf + sizeof(mz_uint32)) : descriptor_buf; + + mz_uint32 file_crc32 = MZ_READ_LE32(pSrc); + mz_uint64 comp_size = 0, uncomp_size = 0; + + if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); + } + else + { + comp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32)); + uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); + } + + if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + else + { + if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + goto handle_failure; + } + } + + mz_zip_array_clear(pZip, &file_data_array); + + if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) + { + if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + return MZ_FALSE; + + /* 1 more check to be sure, although the extract checks too. */ + if (uncomp_crc32 != file_stat.m_crc32) + { + mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + return MZ_FALSE; + } + } + + return MZ_TRUE; + +handle_failure: + mz_zip_array_clear(pZip, &file_data_array); + return MZ_FALSE; +} + +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) +{ + mz_zip_internal_state *pState; + uint32_t i; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Basic sanity checks */ + if (!pState->m_zip64) + { + if (pZip->m_total_files > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pZip->m_archive_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + else + { + if (pZip->m_total_files >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + for (i = 0; i < pZip->m_total_files; i++) + { + if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) + { + mz_uint32 found_index; + mz_zip_archive_file_stat stat; + + if (!mz_zip_reader_file_stat(pZip, i, &stat)) + return MZ_FALSE; + + if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) + return MZ_FALSE; + + /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ + if (found_index != i) + return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); + } + + if (!mz_zip_validate_file(pZip, i, flags)) + return MZ_FALSE; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if ((!pMem) || (!size)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr) +{ + mz_bool success = MZ_TRUE; + mz_zip_archive zip; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + if (!pFilename) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + mz_zip_zero_struct(&zip); + + if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) + { + if (pErr) + *pErr = zip.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_validate_archive(&zip, flags)) + { + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (!mz_zip_reader_end_internal(&zip, success)) + { + if (!actual_err) + actual_err = zip.m_last_error; + success = MZ_FALSE; + } + + if (pErr) + *pErr = actual_err; + + return success; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +/* ------------------- .ZIP archive writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +static MZ_FORCEINLINE void mz_write_le16(mz_uint8 *p, mz_uint16 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); +} +static MZ_FORCEINLINE void mz_write_le32(mz_uint8 *p, mz_uint32 v) +{ + p[0] = (mz_uint8)v; + p[1] = (mz_uint8)(v >> 8); + p[2] = (mz_uint8)(v >> 16); + p[3] = (mz_uint8)(v >> 24); +} +static MZ_FORCEINLINE void mz_write_le64(mz_uint8 *p, mz_uint64 v) +{ + mz_write_le32(p, (mz_uint32)v); + mz_write_le32(p + sizeof(mz_uint32), (mz_uint32)(v >> 32)); +} + +#define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) +#define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) +#define MZ_WRITE_LE64(p, v) mz_write_le64((mz_uint8 *)(p), (mz_uint64)(v)) + +static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); + + if (!n) + return 0; + + /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ + if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + return 0; + } + + if (new_size > pState->m_mem_capacity) + { + void *pNew_block; + size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); + + while (new_capacity < new_size) + new_capacity *= 2; + + if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + { + mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + return 0; + } + + pState->m_pMem = pNew_block; + pState->m_mem_capacity = new_capacity; + } + memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); + pState->m_mem_size = (size_t)new_size; + return n; +} + +static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last_error) +{ + mz_zip_internal_state *pState; + mz_bool status = MZ_TRUE; + + if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return MZ_FALSE; + } + + pState = pZip->m_pState; + pZip->m_pState = NULL; + mz_zip_array_clear(pZip, &pState->m_central_dir); + mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); + mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); + +#ifndef MINIZ_NO_STDIO + if (pState->m_pFile) + { + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (MZ_FCLOSE(pState->m_pFile) == EOF) + { + if (set_last_error) + mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); + status = MZ_FALSE; + } + } + + pState->m_pFile = NULL; + } +#endif /* #ifndef MINIZ_NO_STDIO */ + + if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); + pState->m_pMem = NULL; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pState); + pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; + return status; +} + +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags) +{ + mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; + + if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + { + if (!pZip->m_pRead) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (pZip->m_file_offset_alignment) + { + /* Ensure user specified file offset alignment is a power of 2. */ + if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + if (!pZip->m_pAlloc) + pZip->m_pAlloc = miniz_def_alloc_func; + if (!pZip->m_pFree) + pZip->m_pFree = miniz_def_free_func; + if (!pZip->m_pRealloc) + pZip->m_pRealloc = miniz_def_realloc_func; + + pZip->m_archive_size = existing_size; + pZip->m_central_directory_file_ofs = 0; + pZip->m_total_files = 0; + + if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); + + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); + MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); + + pZip->m_pState->m_zip64 = zip64; + pZip->m_pState->m_zip64_has_extended_info_fields = zip64; + + pZip->m_zip_type = MZ_ZIP_TYPE_USER; + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) +{ + return mz_zip_writer_init_v2(pZip, existing_size, 0); +} + +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_heap_write_func; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_mem_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; + + if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + { + if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + { + mz_zip_writer_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + pZip->m_pState->m_mem_capacity = initial_allocation_size; + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) +{ + return mz_zip_writer_init_heap_v2(pZip, size_to_reserve_at_beginning, initial_allocation_size, 0); +} + +#ifndef MINIZ_NO_STDIO +static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) +{ + mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; + mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + + file_ofs += pZip->m_pState->m_file_archive_start_ofs; + + if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); + return 0; + } + + return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); +} + +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) +{ + return mz_zip_writer_init_file_v2(pZip, pFilename, size_to_reserve_at_beginning, 0); +} + +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags) +{ + MZ_FILE *pFile; + + pZip->m_pWrite = mz_zip_file_write_func; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + return MZ_FALSE; + + if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + + pZip->m_pState->m_pFile = pFile; + pZip->m_zip_type = MZ_ZIP_TYPE_FILE; + + if (size_to_reserve_at_beginning) + { + mz_uint64 cur_ofs = 0; + char buf[4096]; + + MZ_CLEAR_OBJ(buf); + + do + { + size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + { + mz_zip_writer_end(pZip); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_ofs += n; + size_to_reserve_at_beginning -= n; + } while (size_to_reserve_at_beginning); + } + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags) +{ + pZip->m_pWrite = mz_zip_file_write_func; + + if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + pZip->m_pRead = mz_zip_file_read_func; + + pZip->m_pIO_opaque = pZip; + + if (!mz_zip_writer_init_v2(pZip, 0, flags)) + return MZ_FALSE; + + pZip->m_pState->m_pFile = pFile; + pZip->m_pState->m_file_archive_start_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); + pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; + + return MZ_TRUE; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags) +{ + mz_zip_internal_state *pState; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) + { + /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ + if (!pZip->m_pState->m_zip64) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* No sense in trying to write to an archive that's already at the support max size */ + if (pZip->m_pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + + if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + pState = pZip->m_pState; + + if (pState->m_pFile) + { +#ifdef MINIZ_NO_STDIO + (void)pFilename; + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); +#else + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + { + if (!pFilename) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ + if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + { + /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ + mz_zip_reader_end_internal(pZip, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + } + } + + pZip->m_pWrite = mz_zip_file_write_func; +#endif /* #ifdef MINIZ_NO_STDIO */ + } + else if (pState->m_pMem) + { + /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ + if (pZip->m_pIO_opaque != pZip) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState->m_mem_capacity = pState->m_mem_size; + pZip->m_pWrite = mz_zip_heap_write_func; + } + /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ + else if (!pZip->m_pWrite) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Start writing new files at the archive's current central directory location. */ + /* TODO: We could add a flag that lets the user start writing immediately AFTER the existing central dir - this would be safer. */ + pZip->m_archive_size = pZip->m_central_directory_file_ofs; + pZip->m_central_directory_file_ofs = 0; + + /* Clear the sorted central dir offsets, they aren't useful or maintained now. */ + /* Even though we're now in write mode, files can still be extracted and verified, but file locates will be slow. */ + /* TODO: We could easily maintain the sorted central directory offsets. */ + mz_zip_array_clear(pZip, &pZip->m_pState->m_sorted_central_dir_offsets); + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) +{ + return mz_zip_writer_init_from_reader_v2(pZip, pFilename, 0); +} + +/* TODO: pArchive_name is a terrible name here! */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) +{ + return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); +} + +typedef struct +{ + mz_zip_archive *m_pZip; + mz_uint64 m_cur_archive_file_ofs; + mz_uint64 m_comp_size; +} mz_zip_writer_add_state; + +static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) +{ + mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; + if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + return MZ_FALSE; + + pState->m_cur_archive_file_ofs += len; + pState->m_comp_size += len; + return MZ_TRUE; +} + +#define MZ_ZIP64_MAX_LOCAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 2) +#define MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE (sizeof(mz_uint16) * 2 + sizeof(mz_uint64) * 3) +static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 *pUncomp_size, mz_uint64 *pComp_size, mz_uint64 *pLocal_header_ofs) +{ + mz_uint8 *pDst = pBuf; + + MZ_WRITE_LE16(pDst + 0, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + MZ_WRITE_LE16(pDst + 2, 0); + pDst += sizeof(mz_uint16) * 2; + + mz_uint32 field_size = 0; + + if (pUncomp_size) + { + MZ_WRITE_LE64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pComp_size) + { + MZ_WRITE_LE64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + MZ_WRITE_LE64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + field_size += sizeof(mz_uint64); + } + + MZ_WRITE_LE16(pBuf + 2, field_size); + + return (mz_uint32)(pDst - pBuf); +} + +static mz_bool mz_zip_writer_create_local_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_create_central_dir_header(mz_zip_archive *pZip, mz_uint8 *pDst, + mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes) +{ + (void)pZip; + memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_MIN(comp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_MIN(uncomp_size, MZ_UINT32_MAX)); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); + MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); + MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_MIN(local_header_ofs, MZ_UINT32_MAX)); + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, + const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, + mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, + mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, + mz_uint64 local_header_ofs, mz_uint32 ext_attributes, + const char *user_extra_data, mz_uint user_extra_data_len) +{ + mz_zip_internal_state *pState = pZip->m_pState; + mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; + size_t orig_central_dir_size = pState->m_central_dir.m_size; + mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + + if (!pZip->m_pState->m_zip64) + { + if (local_header_ofs > 0xFFFFFFFF) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); + } + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size + user_extra_data_len, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || + (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, ¢ral_dir_ofs, 1))) + { + /* Try to resize the central directory array back into its original state. */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + return MZ_TRUE; +} + +static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) +{ + /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ + if (*pArchive_name == '/') + return MZ_FALSE; + + while (*pArchive_name) + { + if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + return MZ_FALSE; + + pArchive_name++; + } + + return MZ_TRUE; +} + +static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) +{ + mz_uint32 n; + if (!pZip->m_file_offset_alignment) + return 0; + n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); + return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); +} + +static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) +{ + char buf[4096]; + memset(buf, 0, MZ_MIN(sizeof(buf), n)); + while (n) + { + mz_uint32 s = MZ_MIN(sizeof(buf), n); + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_file_ofs += s; + n -= s; + } + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) +{ + return mz_zip_writer_add_mem_ex_v2(pZip, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, uncomp_size, uncomp_crc32, NULL, NULL, 0, NULL, 0); +} + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, + mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 method = 0, dos_time = 0, dos_date = 0; + mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; + mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + tdefl_compressor *pComp = NULL; + mz_bool store_data_uncompressed; + mz_zip_internal_state *pState; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_uint16 bit_flags = 0; + + if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + + if (level_and_flags & MZ_ZIP_FLAG_UTF8_FILENAME) + bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (last_modified != NULL) + { + mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); + } + else + { +#ifndef MINIZ_NO_TIME + { + MZ_TIME_T cur_time; + time(&cur_time); + mz_zip_time_t_to_dos_time(cur_time, &dos_time, &dos_date); + } +#endif /* #ifndef MINIZ_NO_TIME */ + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + + if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + { + /* Set DOS Subdirectory attribute bit. */ + ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; + + /* Subdirectories cannot contain data. */ + if ((buf_size) || (uncomp_size)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + } + + /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ + if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if ((!store_data_uncompressed) && (buf_size)) + { + if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return MZ_FALSE; + } + + local_dir_header_ofs += num_alignment_padding_bytes; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + cur_archive_file_ofs += num_alignment_padding_bytes; + + MZ_CLEAR_OBJ(local_dir_header); + + if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + method = MZ_DEFLATED; + } + + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + + if (pExtra_data != NULL) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + { + uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); + uncomp_size = buf_size; + if (uncomp_size <= 3) + { + level = 0; + store_data_uncompressed = MZ_TRUE; + } + } + + if (store_data_uncompressed) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += buf_size; + comp_size = buf_size; + } + else if (buf_size) + { + mz_zip_writer_add_state state; + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + return mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pComp = NULL; + + if (uncomp_size) + { + MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); + + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + } + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, + comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + const char *user_extra_data, mz_uint user_extra_data_len, const char *user_extra_data_central, mz_uint user_extra_data_central_len) +{ + mz_uint16 gen_flags = MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; + mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; + mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; + mz_uint64 local_dir_header_ofs, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = size_to_add, comp_size = 0; + size_t archive_name_size; + mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; + mz_uint8 *pExtra_data = NULL; + mz_uint32 extra_size = 0; + mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; + mz_zip_internal_state *pState; + + if (level_and_flags & MZ_ZIP_FLAG_UTF8_FILENAME) + gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; + + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + level = level_and_flags & 0xF; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if ((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX)) + { + /* Source file is too large for non-zip64 */ + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + pState->m_zip64 = MZ_TRUE; + } + + /* We could support this, but why? */ + if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + if (pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if (pZip->m_total_files == MZ_UINT16_MAX) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ + } + } + + archive_name_size = strlen(pArchive_name); + if (archive_name_size > MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ + if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + if (!pState->m_zip64) + { + /* Bail early if the archive would obviously become too large */ + if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024) > 0xFFFFFFFF) + { + pState->m_zip64 = MZ_TRUE; + /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ + } + } + +#ifndef MINIZ_NO_TIME + if (pFile_time) + { + mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); + } +#endif + + if (uncomp_size <= 3) + level = 0; + + if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += num_alignment_padding_bytes; + local_dir_header_ofs = cur_archive_file_ofs; + + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + if (uncomp_size && level) + { + method = MZ_DEFLATED; + } + + MZ_CLEAR_OBJ(local_dir_header); + if (pState->m_zip64) + { + if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + { + pExtra_data = extra_data; + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += extra_size; + } + else + { + if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += sizeof(local_dir_header); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + { + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_archive_file_ofs += archive_name_size; + } + + if (user_extra_data_len > 0) + { + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_archive_file_ofs += user_extra_data_len; + } + + if (uncomp_size) + { + mz_uint64 uncomp_remaining = uncomp_size; + void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); + if (!pRead_buf) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!level) + { + while (uncomp_remaining) + { + mz_uint n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); + if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); + uncomp_remaining -= n; + cur_archive_file_ofs += n; + } + comp_size = uncomp_size; + } + else + { + mz_bool result = MZ_FALSE; + mz_zip_writer_add_state state; + tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); + if (!pComp) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + state.m_pZip = pZip; + state.m_cur_archive_file_ofs = cur_archive_file_ofs; + state.m_comp_size = 0; + + if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); + } + + for (;;) + { + size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); + tdefl_status status; + + if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) + { + mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + break; + } + + uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); + uncomp_remaining -= in_buf_size; + + status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); + if (status == TDEFL_STATUS_DONE) + { + result = MZ_TRUE; + break; + } + else if (status != TDEFL_STATUS_OKAY) + { + mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); + break; + } + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); + + if (!result) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + return MZ_FALSE; + } + + comp_size = state.m_comp_size; + cur_archive_file_ofs = state.m_cur_archive_file_ofs; + } + + pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); + } + + mz_uint8 local_dir_footer[MZ_ZIP_DATA_DESCRIPTER_SIZE64]; + mz_uint32 local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE32; + + MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); + MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); + if (pExtra_data == NULL) + { + if (comp_size > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(local_dir_footer + 8, comp_size); + MZ_WRITE_LE32(local_dir_footer + 12, uncomp_size); + } + else + { + MZ_WRITE_LE64(local_dir_footer + 8, comp_size); + MZ_WRITE_LE64(local_dir_footer + 16, uncomp_size); + local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + return MZ_FALSE; + + cur_archive_file_ofs += local_dir_footer_size; + + if (pExtra_data != NULL) + { + extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, + (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); + } + + if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, comment_size, + uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, + user_extra_data_central, user_extra_data_central_len)) + return MZ_FALSE; + + pZip->m_total_files++; + pZip->m_archive_size = cur_archive_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + MZ_FILE *pSrc_file = NULL; + mz_uint64 uncomp_size = 0; + MZ_TIME_T file_modified_time; + MZ_TIME_T *pFile_time = NULL; + + memset(&file_modified_time, 0, sizeof(file_modified_time)); + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) + pFile_time = &file_modified_time; + if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); +#endif + + pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); + if (!pSrc_file) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); + + MZ_FSEEK64(pSrc_file, 0, SEEK_END); + uncomp_size = MZ_FTELL64(pSrc_file); + MZ_FSEEK64(pSrc_file, 0, SEEK_SET); + + mz_bool status = mz_zip_writer_add_cfile(pZip, pArchive_name, pSrc_file, uncomp_size, pFile_time, pComment, comment_size, level_and_flags, NULL, 0, NULL, 0); + + MZ_FCLOSE(pSrc_file); + + return status; +} +#endif /* #ifndef MINIZ_NO_STDIO */ + +static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) +{ + /* + 64 should be enough for any new zip64 data */ + if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); + + if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) + { + mz_uint8 new_ext_block[64]; + mz_uint8 *pDst = new_ext_block; + mz_write_le16(pDst, MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID); + mz_write_le16(pDst + sizeof(mz_uint16), 0); + pDst += sizeof(mz_uint16) * 2; + + if (pUncomp_size) + { + mz_write_le64(pDst, *pUncomp_size); + pDst += sizeof(mz_uint64); + } + + if (pComp_size) + { + mz_write_le64(pDst, *pComp_size); + pDst += sizeof(mz_uint64); + } + + if (pLocal_header_ofs) + { + mz_write_le64(pDst, *pLocal_header_ofs); + pDst += sizeof(mz_uint64); + } + + if (pDisk_start) + { + mz_write_le32(pDst, *pDisk_start); + pDst += sizeof(mz_uint32); + } + + mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); + + if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if ((pExt) && (ext_len)) + { + mz_uint32 extra_size_remaining = ext_len; + const mz_uint8 *pExtra_data = pExt; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + } + + return MZ_TRUE; +} + +/* TODO: This func is now pretty freakin complex due to zip64, split it up? */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index) +{ + mz_uint n, bit_flags, num_alignment_padding_bytes, src_central_dir_following_data_size; + mz_uint64 src_archive_bytes_remaining, local_dir_header_ofs; + mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; + mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; + mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; + mz_uint8 new_central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; + size_t orig_central_dir_size; + mz_zip_internal_state *pState; + void *pBuf; + const mz_uint8 *pSrc_central_header; + mz_zip_archive_file_stat src_file_stat; + mz_uint32 src_filename_len, src_comment_len, src_ext_len; + mz_uint32 local_header_filename_size, local_header_extra_len; + mz_uint64 local_header_comp_size, local_header_uncomp_size; + mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; + + /* Sanity checks */ + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ + if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + /* Get pointer to the source central dir header and crack it */ + if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); + src_comment_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); + src_ext_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS); + src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; + + /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ + if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + + num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); + + if (!pState->m_zip64) + { + if (pZip->m_total_files == MZ_UINT16_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ + if (pZip->m_total_files == MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) + return MZ_FALSE; + + cur_src_file_ofs = src_file_stat.m_local_header_ofs; + cur_dst_file_ofs = pZip->m_archive_size; + + /* Read the source archive's local dir header */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + + if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + + cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Compute the total size we need to copy (filename+extra data+compressed data) */ + local_header_filename_size = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); + local_header_extra_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); + local_header_comp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS); + local_header_uncomp_size = MZ_READ_LE32(pLocal_header + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS); + src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; + + /* Try to find a zip64 extended information field */ + if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + { + mz_zip_array file_data_array; + mz_zip_array_init(&file_data_array, 1); + if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) + { + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + mz_uint32 extra_size_remaining = local_header_extra_len; + const mz_uint8 *pExtra_data = (const mz_uint8 *)file_data_array.m_p; + + do + { + mz_uint32 field_id, field_data_size, field_total_size; + + if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + field_id = MZ_READ_LE16(pExtra_data); + field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); + field_total_size = field_data_size + sizeof(mz_uint16) * 2; + + if (field_total_size > extra_size_remaining) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + { + const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); + + if (field_data_size < sizeof(mz_uint64) * 2) + { + mz_zip_array_clear(pZip, &file_data_array); + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); + } + + local_header_uncomp_size = MZ_READ_LE64(pSrc_field_data); + local_header_comp_size = MZ_READ_LE64(pSrc_field_data + sizeof(mz_uint64)); /* may be 0 if there's a descriptor */ + + found_zip64_ext_data_in_ldir = MZ_TRUE; + break; + } + + pExtra_data += field_total_size; + extra_size_remaining -= field_total_size; + } while (extra_size_remaining); + + mz_zip_array_clear(pZip, &file_data_array); + } + + if (!pState->m_zip64) + { + /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ + /* We also check when the archive is finalized so this doesn't need to be perfect. */ + mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; + + if (approx_new_archive_size >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + } + + /* Write dest archive padding */ + if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + return MZ_FALSE; + + cur_dst_file_ofs += num_alignment_padding_bytes; + + local_dir_header_ofs = cur_dst_file_ofs; + if (pZip->m_file_offset_alignment) + { + MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); + } + + /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; + + /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ + if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + while (src_archive_bytes_remaining) + { + n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + cur_src_file_ofs += n; + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + cur_dst_file_ofs += n; + + src_archive_bytes_remaining -= n; + } + + /* Now deal with the optional data descriptor */ + bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); + if (bit_flags & 8) + { + /* Copy data descriptor */ + if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + { + /* src is zip64, dest must be zip64 */ + + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ + /* uncomp_size 2 */ + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID) ? 6 : 5); + } + else + { + /* src is NOT zip64 */ + mz_bool has_id; + + if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); + } + + has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); + + if (pZip->m_pState->m_zip64) + { + /* dest is zip64, so upgrade the data descriptor */ + const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0)); + const mz_uint32 src_crc32 = pSrc_descriptor[0]; + const mz_uint64 src_comp_size = pSrc_descriptor[1]; + const mz_uint64 src_uncomp_size = pSrc_descriptor[2]; + + mz_write_le32((mz_uint8 *)pBuf, MZ_ZIP_DATA_DESCRIPTOR_ID); + mz_write_le32((mz_uint8 *)pBuf + sizeof(mz_uint32) * 1, src_crc32); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 2, src_comp_size); + mz_write_le64((mz_uint8 *)pBuf + sizeof(mz_uint32) * 4, src_uncomp_size); + + n = sizeof(mz_uint32) * 6; + } + else + { + /* dest is NOT zip64, just copy it as-is */ + n = sizeof(mz_uint32) * (has_id ? 4 : 3); + } + } + + if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + { + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + } + + cur_src_file_ofs += n; + cur_dst_file_ofs += n; + } + pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); + + /* Finally, add the new central dir header */ + orig_central_dir_size = pState->m_central_dir.m_size; + + memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); + + if (pState->m_zip64) + { + /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ + const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; + mz_zip_array new_ext_block; + + mz_zip_array_init(&new_ext_block, sizeof(mz_uint8)); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); + + if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return MZ_FALSE; + } + + MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + { + mz_zip_array_clear(pZip, &new_ext_block); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) + { + mz_zip_array_clear(pZip, &new_ext_block); + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + mz_zip_array_clear(pZip, &new_ext_block); + } + else + { + /* sanity checks */ + if (cur_dst_file_ofs > MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + if (local_dir_header_ofs >= MZ_UINT32_MAX) + return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); + + MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + } + + /* This shouldn't trigger unless we screwed up during the initial sanity checks */ + if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + { + /* TODO: Support central dirs >= 32-bits in size */ + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); + } + + n = (mz_uint32)orig_central_dir_size; + if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + { + mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); + return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); + } + + pZip->m_total_files++; + pZip->m_archive_size = cur_dst_file_ofs; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) +{ + mz_zip_internal_state *pState; + mz_uint64 central_dir_ofs, central_dir_size; + mz_uint8 hdr[256]; + + if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + pState = pZip->m_pState; + + if (pState->m_zip64) + { + if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + else + { + if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); + } + + central_dir_ofs = 0; + central_dir_size = 0; + if (pZip->m_total_files) + { + /* Write central directory */ + central_dir_ofs = pZip->m_archive_size; + central_dir_size = pState->m_central_dir.m_size; + pZip->m_central_directory_file_ofs = central_dir_ofs; + if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += central_dir_size; + } + + if (pState->m_zip64) + { + /* Write zip64 end of central directory header */ + mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; + + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDH_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - sizeof(mz_uint32) - sizeof(mz_uint64)); + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_MADE_BY_OFS, 0x031E); /* TODO: always Unix */ + MZ_WRITE_LE16(hdr + MZ_ZIP64_ECDH_VERSION_NEEDED_OFS, 0x002D); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; + + /* Write zip64 end of central directory locator */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); + MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); + MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + + pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; + } + + /* Write end of central directory record */ + MZ_CLEAR_OBJ(hdr); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, MZ_MIN(MZ_UINT16_MAX, pZip->m_total_files)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); + MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); + + if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); + +#ifndef MINIZ_NO_STDIO + if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); +#endif /* #ifndef MINIZ_NO_STDIO */ + + pZip->m_archive_size += MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE; + + pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; + return MZ_TRUE; +} + +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) +{ + if ((!ppBuf) || (!pSize)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + *ppBuf = NULL; + *pSize = 0; + + if ((!pZip) || (!pZip->m_pState)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (pZip->m_pWrite != mz_zip_heap_write_func) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + if (!mz_zip_writer_finalize_archive(pZip)) + return MZ_FALSE; + + *ppBuf = pZip->m_pState->m_pMem; + *pSize = pZip->m_pState->m_mem_size; + pZip->m_pState->m_pMem = NULL; + pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; + + return MZ_TRUE; +} + +mz_bool mz_zip_writer_end(mz_zip_archive *pZip) +{ + return mz_zip_writer_end_internal(pZip, MZ_TRUE); +} + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) +{ + return mz_zip_add_mem_to_archive_file_in_place_v2(pZip_filename, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, NULL); +} + +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr) +{ + mz_bool status, created_new_archive = MZ_FALSE; + mz_zip_archive zip_archive; + struct MZ_FILE_STAT_STRUCT file_stat; + mz_zip_error actual_err = MZ_ZIP_NO_ERROR; + + mz_zip_zero_struct(&zip_archive); + if ((int)level_and_flags < 0) + level_and_flags = MZ_DEFAULT_LEVEL; + + if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + return MZ_FALSE; + } + + if (!mz_zip_writer_validate_archive_name(pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_FILENAME; + return MZ_FALSE; + } + + /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ + /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ + if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + { + /* Create a new archive. */ + if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + created_new_archive = MZ_TRUE; + } + else + { + /* Append to an existing archive. */ + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + return MZ_FALSE; + } + + if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); + + return MZ_FALSE; + } + } + + status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); + actual_err = zip_archive.m_last_error; + + /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ + if (!mz_zip_writer_finalize_archive(&zip_archive)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if (!mz_zip_writer_end_internal(&zip_archive, status)) + { + if (!actual_err) + actual_err = zip_archive.m_last_error; + + status = MZ_FALSE; + } + + if ((!status) && (created_new_archive)) + { + /* It's a new archive and something went wrong, so just delete it. */ + int ignoredStatus = MZ_DELETE_FILE(pZip_filename); + (void)ignoredStatus; + } + + if (pErr) + *pErr = actual_err; + + return status; +} + +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr) +{ + mz_uint32 file_index; + mz_zip_archive zip_archive; + void *p = NULL; + + if (pSize) + *pSize = 0; + + if ((!pZip_filename) || (!pArchive_name)) + { + if (pErr) + *pErr = MZ_ZIP_INVALID_PARAMETER; + + return NULL; + } + + mz_zip_zero_struct(&zip_archive); + if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + { + if (pErr) + *pErr = zip_archive.m_last_error; + + return NULL; + } + + if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) + { + p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); + } + + mz_zip_reader_end_internal(&zip_archive, p != NULL); + + if (pErr) + *pErr = zip_archive.m_last_error; + + return p; +} + +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) +{ + return mz_zip_extract_archive_file_to_heap_v2(pZip_filename, pArchive_name, NULL, pSize, flags, NULL); +} + +#endif /* #ifndef MINIZ_NO_STDIO */ + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* ------------------- Misc utils */ + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_mode : MZ_ZIP_MODE_INVALID; +} + +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_zip_type : MZ_ZIP_TYPE_INVALID; +} + +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = err_num; + return prev_err; +} + +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + return pZip->m_last_error; +} + +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip) +{ + return mz_zip_set_last_error(pZip, MZ_ZIP_NO_ERROR); +} + +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) +{ + mz_zip_error prev_err; + + if (!pZip) + return MZ_ZIP_INVALID_PARAMETER; + + prev_err = pZip->m_last_error; + + pZip->m_last_error = MZ_ZIP_NO_ERROR; + return prev_err; +} + +const char *mz_zip_get_error_string(mz_zip_error mz_err) +{ + switch (mz_err) + { + case MZ_ZIP_NO_ERROR: + return "no error"; + case MZ_ZIP_UNDEFINED_ERROR: + return "undefined error"; + case MZ_ZIP_TOO_MANY_FILES: + return "too many files"; + case MZ_ZIP_FILE_TOO_LARGE: + return "file too large"; + case MZ_ZIP_UNSUPPORTED_METHOD: + return "unsupported method"; + case MZ_ZIP_UNSUPPORTED_ENCRYPTION: + return "unsupported encryption"; + case MZ_ZIP_UNSUPPORTED_FEATURE: + return "unsupported feature"; + case MZ_ZIP_FAILED_FINDING_CENTRAL_DIR: + return "failed finding central directory"; + case MZ_ZIP_NOT_AN_ARCHIVE: + return "not a ZIP archive"; + case MZ_ZIP_INVALID_HEADER_OR_CORRUPTED: + return "invalid header or archive is corrupted"; + case MZ_ZIP_UNSUPPORTED_MULTIDISK: + return "unsupported multidisk archive"; + case MZ_ZIP_DECOMPRESSION_FAILED: + return "decompression failed or archive is corrupted"; + case MZ_ZIP_COMPRESSION_FAILED: + return "compression failed"; + case MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE: + return "unexpected decompressed size"; + case MZ_ZIP_CRC_CHECK_FAILED: + return "CRC-32 check failed"; + case MZ_ZIP_UNSUPPORTED_CDIR_SIZE: + return "unsupported central directory size"; + case MZ_ZIP_ALLOC_FAILED: + return "allocation failed"; + case MZ_ZIP_FILE_OPEN_FAILED: + return "file open failed"; + case MZ_ZIP_FILE_CREATE_FAILED: + return "file create failed"; + case MZ_ZIP_FILE_WRITE_FAILED: + return "file write failed"; + case MZ_ZIP_FILE_READ_FAILED: + return "file read failed"; + case MZ_ZIP_FILE_CLOSE_FAILED: + return "file close failed"; + case MZ_ZIP_FILE_SEEK_FAILED: + return "file seek failed"; + case MZ_ZIP_FILE_STAT_FAILED: + return "file stat failed"; + case MZ_ZIP_INVALID_PARAMETER: + return "invalid parameter"; + case MZ_ZIP_INVALID_FILENAME: + return "invalid filename"; + case MZ_ZIP_BUF_TOO_SMALL: + return "buffer too small"; + case MZ_ZIP_INTERNAL_ERROR: + return "internal error"; + case MZ_ZIP_FILE_NOT_FOUND: + return "file not found"; + case MZ_ZIP_ARCHIVE_TOO_LARGE: + return "archive is too large"; + case MZ_ZIP_VALIDATION_FAILED: + return "validation failed"; + case MZ_ZIP_WRITE_CALLBACK_FAILED: + return "write calledback failed"; + default: + break; + } + + return "unknown error"; +} + +/* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return MZ_FALSE; + + return pZip->m_pState->m_zip64; +} + +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + + return pZip->m_pState->m_central_dir.m_size; +} + +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) +{ + return pZip ? pZip->m_total_files : 0; +} + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) +{ + if (!pZip) + return 0; + return pZip->m_archive_size; +} + +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_file_archive_start_ofs; +} + +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) +{ + if ((!pZip) || (!pZip->m_pState)) + return 0; + return pZip->m_pState->m_pFile; +} + +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) +{ + if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + + return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); +} + +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) +{ + mz_uint n; + const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); + if (!p) + { + if (filename_buf_size) + pFilename[0] = '\0'; + mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); + return 0; + } + n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); + if (filename_buf_size) + { + n = MZ_MIN(n, filename_buf_size - 1); + memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); + pFilename[n] = '\0'; + } + return n + 1; +} + +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) +{ + return mz_zip_file_stat_internal(pZip, file_index, mz_zip_get_cdh(pZip, file_index), pStat, NULL); +} + +mz_bool mz_zip_end(mz_zip_archive *pZip) +{ + if (!pZip) + return MZ_FALSE; + + if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + return mz_zip_reader_end(pZip); + else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + return mz_zip_writer_end(pZip); + + return MZ_FALSE; +} + +#ifdef __cplusplus +} +#endif diff --git a/src/miniz/miniz.h b/src/miniz/miniz.h new file mode 100644 index 00000000000..daa6423c08b --- /dev/null +++ b/src/miniz/miniz.h @@ -0,0 +1,1352 @@ +/* miniz.c v1.16 beta r1 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing + See "unlicense" statement at the end of this file. + Rich Geldreich , last updated Oct. 13, 2013 + Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt + + Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define + MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). + + * Change History + 10/19/13 v1.16 beta r1 - Two key inflator-only robustness and streaming related changes. Also merged in tdefl_compressor_alloc(), tdefl_compressor_free() helpers to make script bindings easier for rustyzip. + - The inflator coroutine func. is subtle and complex so I'm being cautious about this release. I would greatly appreciate any help with testing or any feedback. + I feel good about these changes, and they've been through several hours of automated testing, but they will probably not fix anything for the majority of prev. users so I'm + going to mark this release as beta for a few weeks and continue testing it at work/home on various things. + - The inflator in raw (non-zlib) mode is now usable on gzip or similiar data streams that have a bunch of bytes following the raw deflate data (problem discovered by rustyzip author williamw520). + This version should *never* read beyond the last byte of the raw deflate data independent of how many bytes you pass into the input buffer. This issue was caused by the various Huffman bitbuffer lookahead optimizations, and + would not be an issue if the caller knew and enforced the precise size of the raw compressed data *or* if the compressed data was in zlib format (i.e. always followed by the byte aligned zlib adler32). + So in other words, you can now call the inflator on deflate streams that are followed by arbitrary amounts of data and it's guaranteed that decompression will stop exactly on the last byte. + - The inflator now has a new failure status: TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS (-4). Previously, if the inflator was starved of bytes and could not make progress (because the input buffer was empty and the + caller did not set the TINFL_FLAG_HAS_MORE_INPUT flag - say on truncated or corrupted compressed data stream) it would append all 0's to the input and try to soldier on. + This is scary, because in the worst case, I believe it was possible for the prev. inflator to start outputting large amounts of literal data. If the caller didn't know when to stop accepting output + (because it didn't know how much uncompressed data was expected, or didn't enforce a sane maximum) it could continue forever. v1.16 cannot fall into this failure mode, instead it'll return + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS immediately if it needs 1 or more bytes to make progress, the input buf is empty, and the caller has indicated that no more input is available. This is a "soft" + failure, so you can call the inflator again with more input and it will try to continue, or you can give up and fail. This could be very useful in network streaming scenarios. + - Added documentation to all the tinfl return status codes, fixed miniz_tester so it accepts double minus params for Linux, tweaked example1.c, added a simple "follower bytes" test to miniz_tester.cpp. + 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): + - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug + would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() + (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). + - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size + - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. + Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). + - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes + - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed + - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. + - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti + - Merged MZ_FORCEINLINE fix from hdeanclark + - Fix include before config #ifdef, thanks emil.brink + - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can + set it to 1 for real-time compression). + - Merged in some compiler fixes from paulharris's github repro. + - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. + - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. + - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. + - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled + - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch + 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include (thanks fermtect). + 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. + - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. + - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. + - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly + "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). + - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. + - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. + - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. + - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) + - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). + 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. + level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson for the feedback/bug report. + 5/28/11 v1.11 - Added statement from unlicense.org + 5/27/11 v1.10 - Substantial compressor optimizations: + - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a + - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). + - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. + - Refactored the compression code for better readability and maintainability. + - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large + drop in throughput on some files). + 5/15/11 v1.09 - Initial stable release. + + * Low-level Deflate/Inflate implementation notes: + + Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or + greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses + approximately as well as zlib. + + Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function + coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory + block large enough to hold the entire file. + + The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. + + * zlib-style API notes: + + miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in + zlib replacement in many apps: + The z_stream struct, optional memory allocation callbacks + deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound + inflateInit/inflateInit2/inflate/inflateEnd + compress, compress2, compressBound, uncompress + CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. + Supports raw deflate streams or standard zlib streams with adler-32 checking. + + Limitations: + The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. + I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but + there are no guarantees that miniz.c pulls this off perfectly. + + * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by + Alex Evans. Supports 1-4 bytes/pixel images. + + * ZIP archive API notes: + + The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to + get the job done with minimal fuss. There are simple API's to retrieve file information, read files from + existing archives, create new archives, append new files to existing archives, or clone archive data from + one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), + or you can specify custom file read/write callbacks. + + - Archive reading: Just call this function to read a single file from a disk archive: + + void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, + size_t *pSize, mz_uint zip_flags); + + For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central + directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. + + - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: + + int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); + + The locate operation can optionally check file comments too, which (as one example) can be used to identify + multiple versions of the same file in an archive. This function uses a simple linear search through the central + directory, so it's not very fast. + + Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and + retrieve detailed info on each file by calling mz_zip_reader_file_stat(). + + - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data + to disk and builds an exact image of the central directory in memory. The central directory image is written + all at once at the end of the archive file when the archive is finalized. + + The archive writer can optionally align each file's local header and file data to any power of 2 alignment, + which can be useful when the archive will be read from optical media. Also, the writer supports placing + arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still + readable by any ZIP tool. + + - Archive appending: The simple way to add a single file to an archive is to call this function: + + mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, + const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + + The archive will be created if it doesn't already exist, otherwise it'll be appended to. + Note the appending is done in-place and is not an atomic operation, so if something goes wrong + during the operation it's possible the archive could be left without a central directory (although the local + file headers and file data will be fine, so the archive will be recoverable). + + For more complex archive modification scenarios: + 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to + preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the + compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and + you're done. This is safe but requires a bunch of temporary disk space or heap memory. + + 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), + append new files as needed, then finalize the archive which will write an updated central directory to the + original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a + possibility that the archive's central directory could be lost with this method if anything goes wrong, though. + + - ZIP archive support limitations: + No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. + Requires streams capable of seeking. + + * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the + below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. + + * Important: For best perf. be sure to customize the below macros for your target platform: + #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 + #define MINIZ_LITTLE_ENDIAN 1 + #define MINIZ_HAS_64BIT_REGISTERS 1 + + * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz + uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files + (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). +*/ +#pragma once + + + + + +/* Defines to completely disable specific portions of miniz.c: + If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ + +/* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ +/*#define MINIZ_NO_STDIO */ + +/* If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able to get the current time, or */ +/* get/set file times, and the C run-time funcs that get/set times won't be called. */ +/* The current downside is the times written to your archives will be from 1979. */ +/*#define MINIZ_NO_TIME */ + +/* Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_APIS */ + +/* Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive API's. */ +/*#define MINIZ_NO_ARCHIVE_WRITING_APIS */ + +/* Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression API's. */ +/*#define MINIZ_NO_ZLIB_APIS */ + +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ +/*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. + Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc + callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user + functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ +/*#define MINIZ_NO_MALLOC */ + +#if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) +/* TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc on Linux */ +#define MINIZ_NO_TIME +#endif + +#if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) +#include +#endif + +#if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || defined(__i386) || defined(__i486__) || defined(__i486) || defined(i386) || defined(__ia64__) || defined(__x86_64__) +/* MINIZ_X86_OR_X64_CPU is only used to help set the below macros. */ +#define MINIZ_X86_OR_X64_CPU 1 +#endif + +#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU +/* Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. */ +#define MINIZ_LITTLE_ENDIAN 1 +#endif + +#if MINIZ_X86_OR_X64_CPU +/* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ +#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 +#endif + +#if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || defined(_LP64) || defined(__LP64__) || defined(__ia64__) || defined(__x86_64__) +/* Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are reasonably fast (and don't involve compiler generated calls to helper functions). */ +#define MINIZ_HAS_64BIT_REGISTERS 1 +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +/* ------------------- zlib-style API Definitions. */ + +/* For more compatibility with zlib, miniz.c uses unsigned long for some parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! */ +typedef unsigned long mz_ulong; + +/* mz_free() internally uses the MZ_FREE() macro (which by default calls free() unless you've modified the MZ_MALLOC macro) to release a block allocated from the heap. */ +void mz_free(void *p); + +#define MZ_ADLER32_INIT (1) +/* mz_adler32() returns the initial adler-32 value to use when called with ptr==NULL. */ +mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); + +#define MZ_CRC32_INIT (0) +/* mz_crc32() returns the initial CRC-32 value to use when called with ptr==NULL. */ +mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); + +/* Compression strategies. */ +enum +{ + MZ_DEFAULT_STRATEGY = 0, + MZ_FILTERED = 1, + MZ_HUFFMAN_ONLY = 2, + MZ_RLE = 3, + MZ_FIXED = 4 +}; + +/* Method */ +#define MZ_DEFLATED 8 + +#ifndef MINIZ_NO_ZLIB_APIS + +/* Heap allocation callbacks. + Note that mz_alloc_func parameter types purpsosely differ from zlib's: items/size is size_t, not unsigned long. */ +typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); +typedef void (*mz_free_func)(void *opaque, void *address); +typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); + +/* TODO: I can't encode "1.16" here, argh */ +#define MZ_VERSION "9.1.15" +#define MZ_VERNUM 0x91F0 +#define MZ_VER_MAJOR 9 +#define MZ_VER_MINOR 1 +#define MZ_VER_REVISION 15 +#define MZ_VER_SUBREVISION 0 + +/* Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The other values are for advanced use (refer to the zlib docs). */ +enum +{ + MZ_NO_FLUSH = 0, + MZ_PARTIAL_FLUSH = 1, + MZ_SYNC_FLUSH = 2, + MZ_FULL_FLUSH = 3, + MZ_FINISH = 4, + MZ_BLOCK = 5 +}; + +/* Return status codes. MZ_PARAM_ERROR is non-standard. */ +enum +{ + MZ_OK = 0, + MZ_STREAM_END = 1, + MZ_NEED_DICT = 2, + MZ_ERRNO = -1, + MZ_STREAM_ERROR = -2, + MZ_DATA_ERROR = -3, + MZ_MEM_ERROR = -4, + MZ_BUF_ERROR = -5, + MZ_VERSION_ERROR = -6, + MZ_PARAM_ERROR = -10000 +}; + +/* Compression levels: 0-9 are the standard zlib-style levels, 10 is best possible compression (not zlib compatible, and may be very slow), MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. */ +enum +{ + MZ_NO_COMPRESSION = 0, + MZ_BEST_SPEED = 1, + MZ_BEST_COMPRESSION = 9, + MZ_UBER_COMPRESSION = 10, + MZ_DEFAULT_LEVEL = 6, + MZ_DEFAULT_COMPRESSION = -1 +}; + +/* Window bits */ +#define MZ_DEFAULT_WINDOW_BITS 15 + +struct mz_internal_state; + +/* Compression/decompression stream struct. */ +typedef struct mz_stream_s +{ + const unsigned char *next_in; /* pointer to next byte to read */ + unsigned int avail_in; /* number of bytes available at next_in */ + mz_ulong total_in; /* total number of bytes consumed so far */ + + unsigned char *next_out; /* pointer to next byte to write */ + unsigned int avail_out; /* number of bytes that can be written to next_out */ + mz_ulong total_out; /* total number of bytes produced so far */ + + char *msg; /* error msg (unused) */ + struct mz_internal_state *state; /* internal state, allocated by zalloc/zfree */ + + mz_alloc_func zalloc; /* optional heap allocation function (defaults to malloc) */ + mz_free_func zfree; /* optional heap free function (defaults to free) */ + void *opaque; /* heap alloc function user pointer */ + + int data_type; /* data_type (unused) */ + mz_ulong adler; /* adler32 of the source or uncompressed data */ + mz_ulong reserved; /* not used */ +} mz_stream; + +typedef mz_stream *mz_streamp; + +/* Returns the version string of miniz.c. */ +const char *mz_version(void); + +/* mz_deflateInit() initializes a compressor with default options: */ +/* Parameters: */ +/* pStream must point to an initialized mz_stream struct. */ +/* level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. */ +/* level 1 enables a specially optimized compression function that's been optimized purely for performance, not ratio. */ +/* (This special func. is currently only enabled when MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if the input parameters are bogus. */ +/* MZ_MEM_ERROR on out of memory. */ +int mz_deflateInit(mz_streamp pStream, int level); + +/* mz_deflateInit2() is like mz_deflate(), except with more control: */ +/* Additional parameters: */ +/* method must be MZ_DEFLATED */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no header or footer) */ +/* mem_level must be between [1, 9] (it's checked but ignored by miniz.c) */ +int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); + +/* Quickly resets a compressor without having to reallocate anything. Same as calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). */ +int mz_deflateReset(mz_streamp pStream); + +/* mz_deflate() compresses the input to output, consuming as much of the input and producing as much output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or MZ_FINISH. */ +/* Return values: */ +/* MZ_OK on success (when flushing, or if more input is needed but not available, and/or there's more output to be written but the output buffer is full). */ +/* MZ_STREAM_END if all input has been consumed and all output bytes have been written. Don't call mz_deflate() on the stream anymore. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input and/or output buffers are empty. (Fill up the input buffer or free up some output space and try again.) */ +int mz_deflate(mz_streamp pStream, int flush); + +/* mz_deflateEnd() deinitializes a compressor: */ +/* Return values: */ +/* MZ_OK on success. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +int mz_deflateEnd(mz_streamp pStream); + +/* mz_deflateBound() returns a (very) conservative upper bound on the amount of data that could be generated by deflate(), assuming flush is set to only MZ_NO_FLUSH or MZ_FINISH. */ +mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); + +/* Single-call compression functions mz_compress() and mz_compress2(): */ +/* Returns MZ_OK on success, or one of the error codes from mz_deflate() on failure. */ +int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); +int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); + +/* mz_compressBound() returns a (very) conservative upper bound on the amount of data that could be generated by calling mz_compress(). */ +mz_ulong mz_compressBound(mz_ulong source_len); + +/* Initializes a decompressor. */ +int mz_inflateInit(mz_streamp pStream); + +/* mz_inflateInit2() is like mz_inflateInit() with an additional option that controls the window size and whether or not the stream has been wrapped with a zlib header/footer: */ +/* window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate). */ +int mz_inflateInit2(mz_streamp pStream, int window_bits); + +/* Decompresses the input stream to the output, consuming only as much of the input as needed, and writing as much to the output as possible. */ +/* Parameters: */ +/* pStream is the stream to read from and write to. You must initialize/update the next_in, avail_in, next_out, and avail_out members. */ +/* flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. */ +/* On the first call, if flush is MZ_FINISH it's assumed the input and output buffers are both sized large enough to decompress the entire stream in a single call (this is slightly faster). */ +/* MZ_FINISH implies that there are no more source bytes available beside what's already in the input buffer, and that the output buffer is large enough to hold the rest of the decompressed data. */ +/* Return values: */ +/* MZ_OK on success. Either more input is needed but not available, and/or there's more output to be written but the output buffer is full. */ +/* MZ_STREAM_END if all needed input has been consumed and all output bytes have been written. For zlib streams, the adler-32 of the decompressed data has also been verified. */ +/* MZ_STREAM_ERROR if the stream is bogus. */ +/* MZ_DATA_ERROR if the deflate stream is invalid. */ +/* MZ_PARAM_ERROR if one of the parameters is invalid. */ +/* MZ_BUF_ERROR if no forward progress is possible because the input buffer is empty but the inflater needs more input to continue, or if the output buffer is not large enough. Call mz_inflate() again */ +/* with more input data, or with more room in the output buffer (except when using single call decompression, described above). */ +int mz_inflate(mz_streamp pStream, int flush); + +/* Deinitializes a decompressor. */ +int mz_inflateEnd(mz_streamp pStream); + +/* Single-call decompression. */ +/* Returns MZ_OK on success, or one of the error codes from mz_inflate() on failure. */ +int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); + +/* Returns a string description of the specified error code, or NULL if the error code is invalid. */ +const char *mz_error(int err); + +/* Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used as a drop-in replacement for the subset of zlib that miniz.c supports. */ +/* Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you use zlib in the same project. */ +#ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES +typedef unsigned char Byte; +typedef unsigned int uInt; +typedef mz_ulong uLong; +typedef Byte Bytef; +typedef uInt uIntf; +typedef char charf; +typedef int intf; +typedef void *voidpf; +typedef uLong uLongf; +typedef void *voidp; +typedef void *const voidpc; +#define Z_NULL 0 +#define Z_NO_FLUSH MZ_NO_FLUSH +#define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH +#define Z_SYNC_FLUSH MZ_SYNC_FLUSH +#define Z_FULL_FLUSH MZ_FULL_FLUSH +#define Z_FINISH MZ_FINISH +#define Z_BLOCK MZ_BLOCK +#define Z_OK MZ_OK +#define Z_STREAM_END MZ_STREAM_END +#define Z_NEED_DICT MZ_NEED_DICT +#define Z_ERRNO MZ_ERRNO +#define Z_STREAM_ERROR MZ_STREAM_ERROR +#define Z_DATA_ERROR MZ_DATA_ERROR +#define Z_MEM_ERROR MZ_MEM_ERROR +#define Z_BUF_ERROR MZ_BUF_ERROR +#define Z_VERSION_ERROR MZ_VERSION_ERROR +#define Z_PARAM_ERROR MZ_PARAM_ERROR +#define Z_NO_COMPRESSION MZ_NO_COMPRESSION +#define Z_BEST_SPEED MZ_BEST_SPEED +#define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION +#define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION +#define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY +#define Z_FILTERED MZ_FILTERED +#define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY +#define Z_RLE MZ_RLE +#define Z_FIXED MZ_FIXED +#define Z_DEFLATED MZ_DEFLATED +#define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS +#define alloc_func mz_alloc_func +#define free_func mz_free_func +#define internal_state mz_internal_state +#define z_stream mz_stream +#define deflateInit mz_deflateInit +#define deflateInit2 mz_deflateInit2 +#define deflateReset mz_deflateReset +#define deflate mz_deflate +#define deflateEnd mz_deflateEnd +#define deflateBound mz_deflateBound +#define compress mz_compress +#define compress2 mz_compress2 +#define compressBound mz_compressBound +#define inflateInit mz_inflateInit +#define inflateInit2 mz_inflateInit2 +#define inflate mz_inflate +#define inflateEnd mz_inflateEnd +#define uncompress mz_uncompress +#define crc32 mz_crc32 +#define adler32 mz_adler32 +#define MAX_WBITS 15 +#define MAX_MEM_LEVEL 9 +#define zError mz_error +#define ZLIB_VERSION MZ_VERSION +#define ZLIB_VERNUM MZ_VERNUM +#define ZLIB_VER_MAJOR MZ_VER_MAJOR +#define ZLIB_VER_MINOR MZ_VER_MINOR +#define ZLIB_VER_REVISION MZ_VER_REVISION +#define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION +#define zlibVersion mz_version +#define zlib_version mz_version() +#endif /* #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ + +#endif /* MINIZ_NO_ZLIB_APIS */ + +#ifdef __cplusplus +} +#endif +#pragma once +#include +#include +#include +#include + +/* ------------------- Types and macros */ +typedef unsigned char mz_uint8; +typedef signed short mz_int16; +typedef unsigned short mz_uint16; +typedef unsigned int mz_uint32; +typedef unsigned int mz_uint; +typedef int64_t mz_int64; +typedef uint64_t mz_uint64; +typedef int mz_bool; + +#define MZ_FALSE (0) +#define MZ_TRUE (1) + +/* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ +#ifdef _MSC_VER +#define MZ_MACRO_END while (0, 0) +#else +#define MZ_MACRO_END while (0) +#endif + +#ifdef MINIZ_NO_STDIO +#define MZ_FILE void * +#else +#include +#define MZ_FILE FILE +#endif /* #ifdef MINIZ_NO_STDIO */ + +#ifdef MINIZ_NO_TIME +typedef struct mz_dummy_time_t_tag +{ + int m_dummy; +} mz_dummy_time_t; +#define MZ_TIME_T mz_dummy_time_t +#else +#define MZ_TIME_T time_t +#endif + +#define MZ_ASSERT(x) assert(x) + +#ifdef MINIZ_NO_MALLOC +#define MZ_MALLOC(x) NULL +#define MZ_FREE(x) (void) x, ((void)0) +#define MZ_REALLOC(p, x) NULL +#else +#define MZ_MALLOC(x) malloc(x) +#define MZ_FREE(x) free(x) +#define MZ_REALLOC(p, x) realloc(p, x) +#endif + +#define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) +#define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) +#define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) + +#if MINIZ_USE_UNALIGNED_LOADS_AND_STORES &&MINIZ_LITTLE_ENDIAN +#define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) +#define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) +#else +#define MZ_READ_LE16(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) +#define MZ_READ_LE32(p) ((mz_uint32)(((const mz_uint8 *)(p))[0]) | ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) +#endif + +#define MZ_READ_LE64(p) (((mz_uint64)MZ_READ_LE32(p)) | (((mz_uint64)MZ_READ_LE32((const mz_uint8 *)(p) + sizeof(mz_uint32))) << 32U)) + +#ifdef _MSC_VER +#define MZ_FORCEINLINE __forceinline +#elif defined(__GNUC__) +#define MZ_FORCEINLINE __inline__ __attribute__((__always_inline__)) +#else +#define MZ_FORCEINLINE inline +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +extern void *miniz_def_alloc_func(void *opaque, size_t items, size_t size); +extern void miniz_def_free_func(void *opaque, void *address); +extern void *miniz_def_realloc_func(void *opaque, void *address, size_t items, size_t size); + +#define MZ_UINT16_MAX (0xFFFFU) +#define MZ_UINT32_MAX (0xFFFFFFFFU) + +#ifdef __cplusplus +} +#endif +#pragma once + + +#ifdef __cplusplus +extern "C" { +#endif +/* ------------------- Low-level Compression API Definitions */ + +/* Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly slower, and raw/dynamic blocks will be output more frequently). */ +#define TDEFL_LESS_MEMORY 0 + +/* tdefl_init() compression flags logically OR'd together (low 12 bits contain the max. number of probes per dictionary search): */ +/* TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap compression), 4095=Huffman+LZ (slowest/best compression). */ +enum +{ + TDEFL_HUFFMAN_ONLY = 0, + TDEFL_DEFAULT_MAX_PROBES = 128, + TDEFL_MAX_PROBES_MASK = 0xFFF +}; + +/* TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before the deflate data, and the Adler-32 of the source data at the end. Otherwise, you'll get raw deflate data. */ +/* TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even when not writing zlib headers). */ +/* TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more efficient lazy parsing. */ +/* TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's initialization time to the minimum, but the output may vary from run to run given the same input (depending on the contents of memory). */ +/* TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) */ +/* TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. */ +/* TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. */ +/* TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. */ +/* The low 12 bits are reserved to control the max # of hash probes per dictionary lookup (see TDEFL_MAX_PROBES_MASK). */ +enum +{ + TDEFL_WRITE_ZLIB_HEADER = 0x01000, + TDEFL_COMPUTE_ADLER32 = 0x02000, + TDEFL_GREEDY_PARSING_FLAG = 0x04000, + TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, + TDEFL_RLE_MATCHES = 0x10000, + TDEFL_FILTER_MATCHES = 0x20000, + TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, + TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 +}; + +/* High level compression functions: */ +/* tdefl_compress_mem_to_heap() compresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of source block to compress. */ +/* flags: The max match finder probes (default is 128) logically OR'd against the above flags. Higher probes are slower but improve compression. */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pOut_len will be set to the compressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must free() the returned block when it's no longer needed. */ +void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tdefl_compress_mem_to_mem() compresses a block in memory to another block in memory. */ +/* Returns 0 on failure. */ +size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* Compresses an image to a compressed PNG file in memory. */ +/* On entry: */ +/* pImage, w, h, and num_chans describe the image to compress. num_chans may be 1, 2, 3, or 4. */ +/* The image pitch in bytes per scanline will be w*num_chans. The leftmost pixel on the top scanline is stored first in memory. */ +/* level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL */ +/* If flip is true, the image will be flipped on the Y axis (useful for OpenGL apps). */ +/* On return: */ +/* Function returns a pointer to the compressed data, or NULL on failure. */ +/* *pLen_out will be set to the size of the PNG image file. */ +/* The caller must mz_free() the returned heap block (which will typically be larger than *pLen_out) when it's no longer needed. */ +void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); +void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); + +/* Output stream interface. The compressor uses this interface to write compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. */ +typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); + +/* tdefl_compress_mem_to_output() compresses a block to an output stream. The above helpers use this function internally. */ +mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +enum +{ + TDEFL_MAX_HUFF_TABLES = 3, + TDEFL_MAX_HUFF_SYMBOLS_0 = 288, + TDEFL_MAX_HUFF_SYMBOLS_1 = 32, + TDEFL_MAX_HUFF_SYMBOLS_2 = 19, + TDEFL_LZ_DICT_SIZE = 32768, + TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, + TDEFL_MIN_MATCH_LEN = 3, + TDEFL_MAX_MATCH_LEN = 258 +}; + +/* TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed output block (using static/fixed Huffman codes). */ +#if TDEFL_LESS_MEMORY +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 12, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#else +enum +{ + TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, + TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, + TDEFL_MAX_HUFF_SYMBOLS = 288, + TDEFL_LZ_HASH_BITS = 15, + TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, + TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, + TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS +}; +#endif + +/* The low-level tdefl functions below may be used directly if the above helper functions aren't flexible enough. The low-level functions don't make any heap allocations, unlike the above helper functions. */ +typedef enum +{ + TDEFL_STATUS_BAD_PARAM = -2, + TDEFL_STATUS_PUT_BUF_FAILED = -1, + TDEFL_STATUS_OKAY = 0, + TDEFL_STATUS_DONE = 1, +} tdefl_status; + +/* Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums */ +typedef enum +{ + TDEFL_NO_FLUSH = 0, + TDEFL_SYNC_FLUSH = 2, + TDEFL_FULL_FLUSH = 3, + TDEFL_FINISH = 4 +} tdefl_flush; + +/* tdefl's compression state structure. */ +typedef struct +{ + tdefl_put_buf_func_ptr m_pPut_buf_func; + void *m_pPut_buf_user; + mz_uint m_flags, m_max_probes[2]; + int m_greedy_parsing; + mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; + mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; + mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; + mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; + tdefl_status m_prev_return_status; + const void *m_pIn_buf; + void *m_pOut_buf; + size_t *m_pIn_buf_size, *m_pOut_buf_size; + tdefl_flush m_flush; + const mz_uint8 *m_pSrc; + size_t m_src_buf_left, m_out_buf_ofs; + mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; + mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; + mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; + mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; + mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; + mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; +} tdefl_compressor; + +/* Initializes the compressor. */ +/* There is no corresponding deinit() function because the tdefl API's do not dynamically allocate memory. */ +/* pBut_buf_func: If NULL, output data will be supplied to the specified callback. In this case, the user should call the tdefl_compress_buffer() API for compression. */ +/* If pBut_buf_func is NULL the user should always call the tdefl_compress() API. */ +/* flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, etc.) */ +tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +/* Compresses a block of data, consuming as much of the specified input buffer as possible, and writing as much compressed data to the specified output buffer as possible. */ +tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); + +/* tdefl_compress_buffer() is only usable when the tdefl_init() is called with a non-NULL tdefl_put_buf_func_ptr. */ +/* tdefl_compress_buffer() always consumes the entire input buffer. */ +tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); + +tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); +mz_uint32 tdefl_get_adler32(tdefl_compressor *d); + +/* Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't defined, because it uses some of its macros. */ +#ifndef MINIZ_NO_ZLIB_APIS +/* Create tdefl_compress() flags given zlib-style compression parameters. */ +/* level may range from [0,10] (where 10 is absolute max compression, but may be much slower on some files) */ +/* window_bits may be -15 (raw deflate) or 15 (zlib) */ +/* strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, MZ_RLE, or MZ_FIXED */ +mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); +#endif /* #ifndef MINIZ_NO_ZLIB_APIS */ + +/* Allocate the tdefl_compressor structure in C so that */ +/* non-C language bindings to tdefl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ +tdefl_compressor *tdefl_compressor_alloc(); +void tdefl_compressor_free(tdefl_compressor *pComp); + +#ifdef __cplusplus +} +#endif +#pragma once + +/* ------------------- Low-level Decompression API Definitions */ + +#ifdef __cplusplus +extern "C" { +#endif +/* Decompression flags used by tinfl_decompress(). */ +/* TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the input is a raw deflate stream. */ +/* TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available beyond the end of the supplied input buffer. If clear, the input buffer contains all remaining input. */ +/* TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large enough to hold the entire decompressed stream. If clear, the output buffer is at least the size of the dictionary (typically 32KB). */ +/* TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the decompressed bytes. */ +enum +{ + TINFL_FLAG_PARSE_ZLIB_HEADER = 1, + TINFL_FLAG_HAS_MORE_INPUT = 2, + TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, + TINFL_FLAG_COMPUTE_ADLER32 = 8 +}; + +/* High level decompression functions: */ +/* tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block allocated via malloc(). */ +/* On entry: */ +/* pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data to decompress. */ +/* On return: */ +/* Function returns a pointer to the decompressed data, or NULL on failure. */ +/* *pOut_len will be set to the decompressed data's size, which could be larger than src_buf_len on uncompressible data. */ +/* The caller must call mz_free() on the returned block when it's no longer needed. */ +void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); + +/* tinfl_decompress_mem_to_mem() decompresses a block in memory to another block in memory. */ +/* Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes written on success. */ +#define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) +size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); + +/* tinfl_decompress_mem_to_callback() decompresses a block in memory to an internal 32KB buffer, and a user provided callback function will be called to flush the buffer. */ +/* Returns 1 on success or 0 on failure. */ +typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); +int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); + +struct tinfl_decompressor_tag; +typedef struct tinfl_decompressor_tag tinfl_decompressor; + +/* Allocate the tinfl_decompressor structure in C so that */ +/* non-C language bindings to tinfl_ API don't need to worry about */ +/* structure size and allocation mechanism. */ + +tinfl_decompressor *tinfl_decompressor_alloc(); +void tinfl_decompressor_free(tinfl_decompressor *pDecomp); + +/* Max size of LZ dictionary. */ +#define TINFL_LZ_DICT_SIZE 32768 + +/* Return status. */ +typedef enum +{ + /* This flags indicates the inflator needs 1 or more input bytes to make forward progress, but the caller is indicating that no more are available. The compressed data */ + /* is probably corrupted. If you call the inflator again with more bytes it'll try to continue processing the input but this is a BAD sign (either the data is corrupted or you called it incorrectly). */ + /* If you call it again with no input you'll just get TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS again. */ + TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS = -4, + + /* This flag indicates that one or more of the input parameters was obviously bogus. (You can try calling it again, but if you get this error the calling code is wrong.) */ + TINFL_STATUS_BAD_PARAM = -3, + + /* This flags indicate the inflator is finished but the adler32 check of the uncompressed data didn't match. If you call it again it'll return TINFL_STATUS_DONE. */ + TINFL_STATUS_ADLER32_MISMATCH = -2, + + /* This flags indicate the inflator has somehow failed (bad code, corrupted input, etc.). If you call it again without resetting via tinfl_init() it it'll just keep on returning the same status failure code. */ + TINFL_STATUS_FAILED = -1, + + /* Any status code less than TINFL_STATUS_DONE must indicate a failure. */ + + /* This flag indicates the inflator has returned every byte of uncompressed data that it can, has consumed every byte that it needed, has successfully reached the end of the deflate stream, and */ + /* if zlib headers and adler32 checking enabled that it has successfully checked the uncompressed data's adler32. If you call it again you'll just get TINFL_STATUS_DONE over and over again. */ + TINFL_STATUS_DONE = 0, + + /* This flag indicates the inflator MUST have more input data (even 1 byte) before it can make any more forward progress, or you need to clear the TINFL_FLAG_HAS_MORE_INPUT */ + /* flag on the next call if you don't have any more source data. If the source data was somehow corrupted it's also possible (but unlikely) for the inflator to keep on demanding input to */ + /* proceed, so be sure to properly set the TINFL_FLAG_HAS_MORE_INPUT flag. */ + TINFL_STATUS_NEEDS_MORE_INPUT = 1, + + /* This flag indicates the inflator definitely has 1 or more bytes of uncompressed data available, but it cannot write this data into the output buffer. */ + /* Note if the source compressed data was corrupted it's possible for the inflator to return a lot of uncompressed data to the caller. I've been assuming you know how much uncompressed data to expect */ + /* (either exact or worst case) and will stop calling the inflator and fail after receiving too much. In pure streaming scenarios where you have no idea how many bytes to expect this may not be possible */ + /* so I may need to add some code to address this. */ + TINFL_STATUS_HAS_MORE_OUTPUT = 2 +} tinfl_status; + +/* Initializes the decompressor to its initial state. */ +#define tinfl_init(r) \ + do \ + { \ + (r)->m_state = 0; \ + } \ + MZ_MACRO_END +#define tinfl_get_adler32(r) (r)->m_check_adler32 + +/* Main low-level decompressor coroutine function. This is the only function actually needed for decompression. All the other functions are just high-level helpers for improved usability. */ +/* This is a universal API, i.e. it can be used as a building block to build any desired higher level decompression API. In the limit case, it can be called once per every byte input or output. */ +tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); + +/* Internal/private bits follow. */ +enum +{ + TINFL_MAX_HUFF_TABLES = 3, + TINFL_MAX_HUFF_SYMBOLS_0 = 288, + TINFL_MAX_HUFF_SYMBOLS_1 = 32, + TINFL_MAX_HUFF_SYMBOLS_2 = 19, + TINFL_FAST_LOOKUP_BITS = 10, + TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS +}; + +typedef struct +{ + mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; + mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; +} tinfl_huff_table; + +#if MINIZ_HAS_64BIT_REGISTERS +#define TINFL_USE_64BIT_BITBUF 1 +#endif + +#if TINFL_USE_64BIT_BITBUF +typedef mz_uint64 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (64) +#else +typedef mz_uint32 tinfl_bit_buf_t; +#define TINFL_BITBUF_SIZE (32) +#endif + +struct tinfl_decompressor_tag +{ + mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; + tinfl_bit_buf_t m_bit_buf; + size_t m_dist_from_out_buf_start; + tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; + mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; +}; + +#ifdef __cplusplus +} +#endif + +#pragma once + + +/* ------------------- ZIP archive reading/writing */ + +#ifdef __cplusplus +extern "C" { +#endif + +enum +{ + /* Note: These enums can be reduced as needed to save memory or stack space - they are pretty conservative. */ + MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, + MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 512, + MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 512 +}; + +typedef struct +{ + /* Central directory file index. */ + mz_uint32 m_file_index; + + /* Byte offset of this entry in the archive's central directory. Note we currently only support up to UINT_MAX or less bytes in the central dir. */ + mz_uint64 m_central_dir_ofs; + + /* These fields are copied directly from the zip's central dir. */ + mz_uint16 m_version_made_by; + mz_uint16 m_version_needed; + mz_uint16 m_bit_flag; + mz_uint16 m_method; + +#ifndef MINIZ_NO_TIME + MZ_TIME_T m_time; +#endif + + /* CRC-32 of uncompressed data. */ + mz_uint32 m_crc32; + + /* File's compressed size. */ + mz_uint64 m_comp_size; + + /* File's uncompressed size. Note, I've seen some old archives where directory entries had 512 bytes for their uncompressed sizes, but when you try to unpack them you actually get 0 bytes. */ + mz_uint64 m_uncomp_size; + + /* Zip internal and external file attributes. */ + mz_uint16 m_internal_attr; + mz_uint32 m_external_attr; + + /* Entry's local header file offset in bytes. */ + mz_uint64 m_local_header_ofs; + + /* Size of comment in bytes. */ + mz_uint32 m_comment_size; + + /* MZ_TRUE if the entry appears to be a directory. */ + mz_bool m_is_directory; + + /* MZ_TRUE if the entry uses encryption/strong encryption (which miniz_zip doesn't support) */ + mz_bool m_is_encrypted; + + /* MZ_TRUE if the file is not encrypted, a patch file, and if it uses a compression method we support. */ + mz_bool m_is_supported; + + /* Filename. If string ends in '/' it's a subdirectory entry. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; + + /* Comment field. */ + /* Guaranteed to be zero terminated, may be truncated to fit. */ + char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; + +} mz_zip_archive_file_stat; + +typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); +typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); + +struct mz_zip_internal_state_tag; +typedef struct mz_zip_internal_state_tag mz_zip_internal_state; + +typedef enum +{ + MZ_ZIP_MODE_INVALID = 0, + MZ_ZIP_MODE_READING = 1, + MZ_ZIP_MODE_WRITING = 2, + MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 +} mz_zip_mode; + +typedef enum +{ + MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, + MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, + MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, + MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800, + MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG = 0x1000, /* if enabled, mz_zip_reader_locate_file() will be called on each file as its validated to ensure the func finds the file in the central dir (intended for testing) */ + MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY = 0x2000, /* validate the local headers, but don't decompress the entire file and check the crc32 */ + MZ_ZIP_FLAG_WRITE_ZIP64 = 0x4000, /* use the zip64 file format, instead of the original zip file format */ + MZ_ZIP_FLAG_WRITE_ALLOW_READING = 0x8000, + MZ_ZIP_FLAG_UTF8_FILENAME = 0x10000 +} mz_zip_flags; + +typedef enum +{ + MZ_ZIP_TYPE_INVALID = 0, + MZ_ZIP_TYPE_USER, + MZ_ZIP_TYPE_MEMORY, + MZ_ZIP_TYPE_HEAP, + MZ_ZIP_TYPE_FILE, + MZ_ZIP_TYPE_CFILE, + MZ_ZIP_TOTAL_TYPES +} mz_zip_type; + +/* miniz error codes. Be sure to update mz_zip_get_error_string() if you add or modify this enum. */ +typedef enum +{ + MZ_ZIP_NO_ERROR = 0, + MZ_ZIP_UNDEFINED_ERROR, + MZ_ZIP_TOO_MANY_FILES, + MZ_ZIP_FILE_TOO_LARGE, + MZ_ZIP_UNSUPPORTED_METHOD, + MZ_ZIP_UNSUPPORTED_ENCRYPTION, + MZ_ZIP_UNSUPPORTED_FEATURE, + MZ_ZIP_FAILED_FINDING_CENTRAL_DIR, + MZ_ZIP_NOT_AN_ARCHIVE, + MZ_ZIP_INVALID_HEADER_OR_CORRUPTED, + MZ_ZIP_UNSUPPORTED_MULTIDISK, + MZ_ZIP_DECOMPRESSION_FAILED, + MZ_ZIP_COMPRESSION_FAILED, + MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE, + MZ_ZIP_CRC_CHECK_FAILED, + MZ_ZIP_UNSUPPORTED_CDIR_SIZE, + MZ_ZIP_ALLOC_FAILED, + MZ_ZIP_FILE_OPEN_FAILED, + MZ_ZIP_FILE_CREATE_FAILED, + MZ_ZIP_FILE_WRITE_FAILED, + MZ_ZIP_FILE_READ_FAILED, + MZ_ZIP_FILE_CLOSE_FAILED, + MZ_ZIP_FILE_SEEK_FAILED, + MZ_ZIP_FILE_STAT_FAILED, + MZ_ZIP_INVALID_PARAMETER, + MZ_ZIP_INVALID_FILENAME, + MZ_ZIP_BUF_TOO_SMALL, + MZ_ZIP_INTERNAL_ERROR, + MZ_ZIP_FILE_NOT_FOUND, + MZ_ZIP_ARCHIVE_TOO_LARGE, + MZ_ZIP_VALIDATION_FAILED, + MZ_ZIP_WRITE_CALLBACK_FAILED, + MZ_ZIP_TOTAL_ERRORS +} mz_zip_error; + +typedef struct +{ + mz_uint64 m_archive_size; + mz_uint64 m_central_directory_file_ofs; + + /* We only support up to UINT32_MAX files in zip64 mode. */ + mz_uint32 m_total_files; + mz_zip_mode m_zip_mode; + mz_zip_type m_zip_type; + mz_zip_error m_last_error; + + mz_uint64 m_file_offset_alignment; + + mz_alloc_func m_pAlloc; + mz_free_func m_pFree; + mz_realloc_func m_pRealloc; + void *m_pAlloc_opaque; + + mz_file_read_func m_pRead; + mz_file_write_func m_pWrite; + void *m_pIO_opaque; + + mz_zip_internal_state *m_pState; + +} mz_zip_archive; + +/* -------- ZIP reading */ + +/* Inits a ZIP archive reader. */ +/* These functions read and validate the archive's central directory. */ +mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags); + +mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +/* Read a archive from a disk file. */ +/* file_start_ofs is the file offset where the archive actually begins, or 0. */ +/* actual_archive_size is the true total size of the archive, which may be smaller than the file's actual size on disk. If zero the entire file is treated as the archive. */ +mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); +mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size); + +/* Read an archive from an already opened FILE, beginning at the current file position. */ +/* The archive is assumed to be archive_size bytes long. If archive_size is < 0, then the entire rest of the file is assumed to contain the archive. */ +/* The FILE will NOT be closed when mz_zip_reader_end() is called. */ +mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 archive_size, mz_uint flags); +#endif + +/* Ends archive reading, freeing all allocations, and closing the input archive file if mz_zip_reader_init_file() was used. */ +mz_bool mz_zip_reader_end(mz_zip_archive *pZip); + +/* -------- ZIP reading or writing */ + +/* Clears a mz_zip_archive struct to all zeros. */ +/* Important: This must be done before passing the struct to any mz_zip functions. */ +void mz_zip_zero_struct(mz_zip_archive *pZip); + +mz_zip_mode mz_zip_get_mode(mz_zip_archive *pZip); +mz_zip_type mz_zip_get_type(mz_zip_archive *pZip); + +/* Returns the total number of files in the archive. */ +mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); + +mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip); +mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip); +MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip); + +/* Reads n bytes of raw archive data, starting at file offset file_ofs, to pBuf. */ +size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +int mz_zip_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +/* Returns MZ_FALSE if the file cannot be found. */ +mz_bool mz_zip_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *pIndex); + +/* All mz_zip funcs set the m_last_error field in the mz_zip_archive struct. These functions retrieve/manipulate this field. */ +/* Note that the m_last_error functionality is not thread safe. */ +mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num); +mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip); +mz_zip_error mz_zip_clear_last_error(mz_zip_archive *pZip); +mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip); +const char *mz_zip_get_error_string(mz_zip_error mz_err); + +/* MZ_TRUE if the archive file entry is a directory entry. */ +mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the file is encrypted/strong encrypted. */ +mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); + +/* MZ_TRUE if the compression method is supported, and the file is not encrypted, and the file is not a compressed patch file. */ +mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index); + +/* Retrieves the filename of an archive file entry. */ +/* Returns the number of bytes written to pFilename, or if filename_buf_size is 0 this function returns the number of bytes needed to fully store the filename. */ +mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); + +/* Attempts to locates a file in the archive's central directory. */ +/* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ +/* Returns -1 if the file cannot be found. */ +int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); +int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); + +/* Returns detailed information about an archive file entry. */ +mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); + +/* MZ_TRUE if the file is in zip64 format. */ +/* A file is considered zip64 if it contained a zip64 end of central directory marker, or if it contained any zip64 extended file information fields in the central directory. */ +mz_bool mz_zip_is_zip64(mz_zip_archive *pZip); + +/* Returns the total central directory size in bytes. */ +/* The current max supported size is <= MZ_UINT32_MAX. */ +size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip); + +/* Extracts a archive file to a memory buffer using no memory allocation. */ +/* There must be at least enough room on the stack to store the inflator's state (~34KB or so). */ +mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); +mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); + +/* Extracts a archive file to a memory buffer. */ +mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); + +/* Extracts a archive file to a dynamically allocated heap buffer. */ +/* The memory will be allocated via the mz_zip_archive's alloc/realloc functions. */ +/* Returns NULL and sets the last error on failure. */ +void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); +void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); + +/* Extracts a archive file using a callback function to output the file's data. */ +mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +/* Extracts a archive file to a disk file and sets its last accessed and modified times. */ +/* This function only extracts files, not archive directory records. */ +mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); + +/* Extracts a archive file starting at the current position in the destination FILE stream. */ +mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, MZ_FILE *File, mz_uint flags); +mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags); +#endif + +#if 0 +/* TODO */ + typedef void *mz_zip_streaming_extract_state_ptr; + mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); + size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); + mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); +#endif + +/* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ +/* It also validates that each file can be successfully uncompressed unless the MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY is specified. */ +mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + +/* Validates an entire archive by calling mz_zip_validate_file() on each file. */ +mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags); + +/* Misc utils/helpers, valid for ZIP reading or writing */ +mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags, mz_zip_error *pErr); +mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zip_error *pErr); + +/* Universal end function - calls either mz_zip_reader_end() or mz_zip_writer_end(). */ +mz_bool mz_zip_end(mz_zip_archive *pZip); + +/* -------- ZIP writing */ + +#ifndef MINIZ_NO_ARCHIVE_WRITING_APIS + +/* Inits a ZIP archive writer. */ +mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); +mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_uint flags); +mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); +mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size, mz_uint flags); + +#ifndef MINIZ_NO_STDIO +mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); +mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning, mz_uint flags); +mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint flags); +#endif + +/* Converts a ZIP archive reader object into a writer object, to allow efficient in-place file appends to occur on an existing archive. */ +/* For archives opened using mz_zip_reader_init_file, pFilename must be the archive's filename so it can be reopened for writing. If the file can't be reopened, mz_zip_reader_end() will be called. */ +/* For archives opened using mz_zip_reader_init_mem, the memory block must be growable using the realloc callback (which defaults to realloc unless you've overridden it). */ +/* Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's user provided m_pWrite function cannot be NULL. */ +/* Note: In-place archive modification is not recommended unless you know what you're doing, because if execution stops or something goes wrong before */ +/* the archive is finalized the file's central directory will be hosed. */ +mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); +mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags); + +/* Adds the contents of a memory buffer to an archive. These functions record the current local time into the archive. */ +/* To add a directory entry, call this method with an archive name ending in a forwardslash with an empty buffer. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_mem(), except you can specify a file comment field, and optionally supply the function with already compressed data. */ +/* uncomp_size/uncomp_crc32 are only used if the MZ_ZIP_FLAG_COMPRESSED_DATA flag is specified. */ +mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); + +mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, + mz_uint64 uncomp_size, mz_uint32 uncomp_crc32, MZ_TIME_T *last_modified, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); + +#ifndef MINIZ_NO_STDIO +/* Adds the contents of a disk file to an archive. This function also records the disk file's modified time into the archive. */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); + +/* Like mz_zip_writer_add_file(), except the file data is read from the specified FILE stream. */ +mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_FILE *pSrc_file, mz_uint64 size_to_add, + const MZ_TIME_T *pFile_time, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, const char *user_extra_data_local, mz_uint user_extra_data_local_len, + const char *user_extra_data_central, mz_uint user_extra_data_central_len); +#endif + +/* Adds a file to an archive by fully cloning the data from another archive. */ +/* This function fully clones the source file's compressed data (no recompression), along with its full filename, extra data (it may add or modify the zip64 local header extra data field), and the optional descriptor following the compressed data. */ +mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint src_file_index); + +/* Finalizes the archive by writing the central directory records followed by the end of central directory record. */ +/* After an archive is finalized, the only valid call on the mz_zip_archive struct is mz_zip_writer_end(). */ +/* An archive must be manually finalized by calling this function for it to be valid. */ +mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); + +/* Finalizes a heap archive, returning a poiner to the heap block and its size. */ +/* The heap block will be allocated using the mz_zip_archive's alloc/realloc callbacks. */ +mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize); + +/* Ends archive writing, freeing all allocations, and closing the output file if mz_zip_writer_init_file() was used. */ +/* Note for the archive to be valid, it *must* have been finalized before ending (this function will not do it for you). */ +mz_bool mz_zip_writer_end(mz_zip_archive *pZip); + +/* -------- Misc. high-level helper functions: */ + +/* mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) appends a memory blob to a ZIP archive. */ +/* Note this is NOT a fully safe operation. If it crashes or dies in some way your archive can be left in a screwed up state (without a central directory). */ +/* level_and_flags - compression level (0-10, see MZ_BEST_SPEED, MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or just set to MZ_DEFAULT_COMPRESSION. */ +/* TODO: Perhaps add an option to leave the existing central dir in place in case the add dies? We could then truncate the file (so the old central dir would be at the end) if something goes wrong. */ +mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); +mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_zip_error *pErr); + +/* Reads a single file from an archive into a heap block. */ +/* If pComment is not NULL, only the file with the specified comment will be extracted. */ +/* Returns NULL on failure. */ +void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags); +void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const char *pArchive_name, const char *pComment, size_t *pSize, mz_uint flags, mz_zip_error *pErr); + +#endif /* #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS */ + +#ifdef __cplusplus +} +#endif From f8226f2d494d9918e23180cb789b837026851445 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Thu, 23 Feb 2017 13:03:47 +0100 Subject: [PATCH 09/67] type cleanup in miniz --- src/miniz/miniz.h | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/miniz/miniz.h b/src/miniz/miniz.h index daa6423c08b..45659d8cf1a 100644 --- a/src/miniz/miniz.h +++ b/src/miniz/miniz.h @@ -176,7 +176,7 @@ -/* Defines to completely disable specific portions of miniz.c: +/* Defines to completely disable specific portions of miniz.c: If all macros here are defined the only functionality remaining will be CRC-32, adler-32, tinfl, and tdefl. */ /* Define MINIZ_NO_STDIO to disable all usage and any functions which rely on stdio for file I/O. */ @@ -199,7 +199,7 @@ /* Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent conflicts against stock zlib. */ /*#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES */ -/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. +/* Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. Note if MINIZ_NO_MALLOC is defined then the user must always provide custom user alloc/free/realloc callbacks to the zlib and archive API's, and a few stand-alone helper API's which don't provide custom user functions (such as tdefl_compress_mem_to_heap() and tinfl_decompress_mem_to_heap()) won't work. */ @@ -523,19 +523,20 @@ typedef void *const voidpc; #include #include #include +#include /* ------------------- Types and macros */ -typedef unsigned char mz_uint8; -typedef signed short mz_int16; -typedef unsigned short mz_uint16; -typedef unsigned int mz_uint32; +typedef uint8_t mz_uint8; +typedef int16_t mz_int16; +typedef uint16_t mz_uint16; +typedef uint32_t mz_uint32; typedef unsigned int mz_uint; typedef int64_t mz_int64; typedef uint64_t mz_uint64; -typedef int mz_bool; +typedef bool mz_bool; -#define MZ_FALSE (0) -#define MZ_TRUE (1) +#define MZ_FALSE false +#define MZ_TRUE true /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ #ifdef _MSC_VER @@ -1195,7 +1196,7 @@ mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, cha /* Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH */ /* Returns -1 if the file cannot be found. */ int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); -int mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); +mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags, mz_uint32 *file_index); /* Returns detailed information about an archive file entry. */ mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); From 122db270ef752c900d42647a6277907f5d297b96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Tue, 14 Feb 2017 12:08:07 +0100 Subject: [PATCH 10/67] update Makefiles / remove all references to libzip/zlib --- src/Makefile | 30 ++------------------ src/cbmc/Makefile | 6 ++-- src/cegis/Makefile | 6 ++-- src/clobber/Makefile | 3 +- src/config.inc | 2 -- src/goto-analyzer/Makefile | 6 ++-- src/goto-cc/Makefile | 6 ++-- src/goto-diff/Makefile | 6 ++-- src/goto-instrument/Makefile | 6 ++-- src/java_bytecode/Makefile | 5 ---- src/java_bytecode/java_bytecode_language.cpp | 6 ---- src/java_bytecode/java_class_loader.cpp | 5 ---- src/miniz/Makefile | 7 ++--- src/symex/Makefile | 6 ++-- 14 files changed, 21 insertions(+), 79 deletions(-) diff --git a/src/Makefile b/src/Makefile index 269ddeda140..704a6754a45 100644 --- a/src/Makefile +++ b/src/Makefile @@ -2,7 +2,7 @@ DIRS = ansi-c big-int cbmc cpp goto-cc goto-instrument goto-programs \ goto-symex langapi pointer-analysis solvers util linking xmllang \ assembler analyses java_bytecode path-symex musketeer \ json cegis goto-analyzer jsil symex goto-diff clobber \ - memory-models + memory-models miniz all: cbmc.dir goto-cc.dir goto-instrument.dir symex.dir goto-analyzer.dir goto-diff.dir @@ -20,7 +20,7 @@ cpp.dir: ansi-c.dir linking.dir languages: util.dir langapi.dir \ cpp.dir ansi-c.dir xmllang.dir assembler.dir java_bytecode.dir \ - jsil.dir + jsil.dir miniz.dir goto-instrument.dir: languages goto-programs.dir pointer-analysis.dir \ goto-symex.dir linking.dir analyses.dir solvers.dir \ @@ -84,28 +84,4 @@ glucose-download: @(cd ../glucose-syrup; patch -p1 < ../scripts/glucose-syrup-patch) @rm glucose-syrup.tgz -zlib-download: - @echo "Downloading zlib 1.2.11" - @lwp-download http://zlib.net/zlib-1.2.11.tar.gz - @tar xfz zlib-1.2.11.tar.gz - @rm -Rf ../zlib - @mv zlib-1.2.11 ../zlib - @rm zlib-1.2.11.tar.gz - -libzip-download: - @echo "Downloading libzip 1.1.2" - # The below wants SSL - #@lwp-download http://www.nih.at/libzip/libzip-1.1.2.tar.gz - @lwp-download http://http.debian.net/debian/pool/main/libz/libzip/libzip_1.1.2.orig.tar.gz - @tar xfz libzip_1.1.2.orig.tar.gz - @rm -Rf ../libzip - @mv libzip-1.1.2 ../libzip - @rm libzip_1.1.2.orig.tar.gz - -libzip-build: - @echo "Building zlib" - @(cd ../zlib; ./configure; make) - @echo "Building libzip" - @(cd ../libzip; BASE=`pwd`; ./configure --with-zlib=$(BASE)/zlib ; make) - -.PHONY: minisat2-download glucose-download zlib-download libzip-download libzip-build +.PHONY: minisat2-download glucose-download diff --git a/src/cbmc/Makefile b/src/cbmc/Makefile index 804030ea69a..79224766188 100644 --- a/src/cbmc/Makefile +++ b/src/cbmc/Makefile @@ -27,7 +27,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../xmllang/xmllang$(LIBEXT) \ ../assembler/assembler$(LIBEXT) \ ../solvers/solvers$(LIBEXT) \ - ../util/util$(LIBEXT) + ../util/util$(LIBEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. @@ -48,9 +49,6 @@ endif ifneq ($(wildcard ../java_bytecode/Makefile),) OBJ += ../java_bytecode/java_bytecode$(LIBEXT) CP_CXXFLAGS += -DHAVE_JAVA_BYTECODE - ifneq ($(wildcard $(LIBZIPINC)),) - LIBS += $(LIBZIPLIB) - endif endif ifneq ($(wildcard ../jsil/Makefile),) diff --git a/src/cegis/Makefile b/src/cegis/Makefile index 27a6880a651..37fe5416953 100644 --- a/src/cegis/Makefile +++ b/src/cegis/Makefile @@ -115,7 +115,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../cbmc/show_vcc$(OBJEXT) \ ../cbmc/cbmc_dimacs$(OBJEXT) ../cbmc/all_properties$(OBJEXT) \ ../cbmc/fault_localization$(OBJEXT) \ - ../cbmc/symex_coverage$(OBJEXT) + ../cbmc/symex_coverage$(OBJEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. @@ -137,9 +138,6 @@ all: cegis$(EXEEXT) ifneq ($(wildcard ../java_bytecode/Makefile),) OBJ += ../java_bytecode/java_bytecode$(LIBEXT) CP_CXXFLAGS += -DHAVE_JAVA_BYTECODE - ifneq ($(wildcard $(LIBZIPINC)),) - LIBS += $(LIBZIPLIB) - endif endif ############################################################################### diff --git a/src/clobber/Makefile b/src/clobber/Makefile index f9c76dda397..ee77d22e33a 100644 --- a/src/clobber/Makefile +++ b/src/clobber/Makefile @@ -15,7 +15,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../goto-symex/rewrite_union$(OBJEXT) \ ../pointer-analysis/dereference$(OBJEXT) \ ../goto-instrument/dump_c$(OBJEXT) \ - ../goto-instrument/goto_program2code$(OBJEXT) + ../goto-instrument/goto_program2code$(OBJEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. diff --git a/src/config.inc b/src/config.inc index 2553a2062d8..e1c1266f683 100644 --- a/src/config.inc +++ b/src/config.inc @@ -24,8 +24,6 @@ BUILD_ENV = AUTO MINISAT2 = ../../minisat-2.2.1 #GLUCOSE = ../../glucose-syrup #SMVSAT = -LIBZIPLIB = ../../libzip/lib/.libs/libzip.a ../../zlib/libz.a -LIBZIPINC = ../../libzip/lib # Signing identity for MacOS Gatekeeper diff --git a/src/goto-analyzer/Makefile b/src/goto-analyzer/Makefile index bfeac69abba..b27b514bf88 100644 --- a/src/goto-analyzer/Makefile +++ b/src/goto-analyzer/Makefile @@ -12,7 +12,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../langapi/langapi$(LIBEXT) \ ../json/json$(LIBEXT) \ ../assembler/assembler$(LIBEXT) \ - ../util/util$(LIBEXT) + ../util/util$(LIBEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. @@ -28,9 +29,6 @@ all: goto-analyzer$(EXEEXT) ifneq ($(wildcard ../java_bytecode/Makefile),) OBJ += ../java_bytecode/java_bytecode$(LIBEXT) CP_CXXFLAGS += -DHAVE_JAVA_BYTECODE - ifneq ($(wildcard $(LIBZIPINC)),) - LIBS += $(LIBZIPLIB) - endif endif ifneq ($(wildcard ../jsil/Makefile),) diff --git a/src/goto-cc/Makefile b/src/goto-cc/Makefile index 727a010fb1d..04261db95f0 100644 --- a/src/goto-cc/Makefile +++ b/src/goto-cc/Makefile @@ -13,7 +13,8 @@ OBJ += ../big-int/big-int$(LIBEXT) \ ../cpp/cpp$(LIBEXT) \ ../xmllang/xmllang$(LIBEXT) \ ../assembler/assembler$(LIBEXT) \ - ../langapi/langapi$(LIBEXT) + ../langapi/langapi$(LIBEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. @@ -31,9 +32,6 @@ all: goto-cc$(EXEEXT) ifneq ($(wildcard ../java_bytecode/Makefile),) OBJ += ../java_bytecode/java_bytecode$(LIBEXT) - ifneq ($(wildcard $(LIBZIPINC)),) - LIBS += $(LIBZIPLIB) - endif endif ifneq ($(wildcard ../jsil/Makefile),) diff --git a/src/goto-diff/Makefile b/src/goto-diff/Makefile index 6f9dd1a893a..c003d0c96b0 100644 --- a/src/goto-diff/Makefile +++ b/src/goto-diff/Makefile @@ -13,7 +13,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../langapi/langapi$(LIBEXT) \ ../xmllang/xmllang$(LIBEXT) \ ../util/util$(LIBEXT) \ - ../solvers/solvers$(LIBEXT) + ../solvers/solvers$(LIBEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. @@ -29,9 +30,6 @@ all: goto-diff$(EXEEXT) ifneq ($(wildcard ../java_bytecode/Makefile),) OBJ += ../java_bytecode/java_bytecode$(LIBEXT) CP_CXXFLAGS += -DHAVE_JAVA_BYTECODE - ifneq ($(wildcard $(LIBZIPINC)),) - LIBS += $(LIBZIPLIB) - endif endif ifneq ($(wildcard ../specc/Makefile),) diff --git a/src/goto-instrument/Makefile b/src/goto-instrument/Makefile index 65cb278a7fc..f79b62d806f 100644 --- a/src/goto-instrument/Makefile +++ b/src/goto-instrument/Makefile @@ -37,7 +37,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../langapi/langapi$(LIBEXT) \ ../xmllang/xmllang$(LIBEXT) \ ../util/util$(LIBEXT) \ - ../solvers/solvers$(LIBEXT) + ../solvers/solvers$(LIBEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. @@ -53,9 +54,6 @@ all: goto-instrument$(EXEEXT) ifneq ($(wildcard ../java_bytecode/Makefile),) OBJ += ../java_bytecode/java_bytecode$(LIBEXT) CP_CXXFLAGS += -DHAVE_JAVA_BYTECODE - ifneq ($(wildcard $(LIBZIPINC)),) - LIBS += $(LIBZIPLIB) - endif endif ifneq ($(LIB_GLPK),) diff --git a/src/java_bytecode/Makefile b/src/java_bytecode/Makefile index e27bc3e038d..20958a3ede3 100644 --- a/src/java_bytecode/Makefile +++ b/src/java_bytecode/Makefile @@ -15,11 +15,6 @@ include ../common CLEANFILES = java_bytecode$(LIBEXT) -ifneq ($(wildcard $(LIBZIPINC)),) - INCLUDES += -I $(LIBZIPINC) - CP_CXXFLAGS += -DHAVE_LIBZIP -endif - all: java_bytecode$(LIBEXT) ############################################################################### diff --git a/src/java_bytecode/java_bytecode_language.cpp b/src/java_bytecode/java_bytecode_language.cpp index e9d5a87186b..d5f2f9eac9d 100644 --- a/src/java_bytecode/java_bytecode_language.cpp +++ b/src/java_bytecode/java_bytecode_language.cpp @@ -137,7 +137,6 @@ bool java_bytecode_languaget::parse( } else if(has_suffix(path, ".jar")) { - #ifdef HAVE_LIBZIP if(config.java.main_class.empty()) { // Does it have a main class set in the manifest? @@ -161,11 +160,6 @@ bool java_bytecode_languaget::parse( } else java_class_loader.add_jar_file(path); - - #else - error() << "No support for reading JAR files" << eom; - return true; - #endif } else assert(false); diff --git a/src/java_bytecode/java_class_loader.cpp b/src/java_bytecode/java_class_loader.cpp index 541faf6828d..dc4330aa00c 100644 --- a/src/java_bytecode/java_class_loader.cpp +++ b/src/java_bytecode/java_class_loader.cpp @@ -212,11 +212,6 @@ void java_class_loadert::read_jar_file(const irep_idt &file) if(jar_map.find(file)!=jar_map.end()) return; - #ifndef HAVE_LIBZIP - error() << "no support for reading JAR files configured" << eom; - return; - #endif - jar_filet &jar_file=jar_pool(id2string(file)); if(!jar_file) diff --git a/src/miniz/Makefile b/src/miniz/Makefile index f2367695802..324c9821b91 100644 --- a/src/miniz/Makefile +++ b/src/miniz/Makefile @@ -5,11 +5,8 @@ INCLUDES= -I .. include ../config.inc include ../common -CLEANFILES = miniz$(LIBEXT) +CLEANFILES = miniz$(OBJEXT) -all: miniz$(LIBEXT) +all: miniz$(OBJEXT) ############################################################################### - -miniz$(LIBEXT): $(OBJ) - $(LINKLIB) diff --git a/src/symex/Makefile b/src/symex/Makefile index 5a66801eec4..f177e91bc07 100644 --- a/src/symex/Makefile +++ b/src/symex/Makefile @@ -16,7 +16,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../goto-symex/rewrite_union$(OBJEXT) \ ../pointer-analysis/dereference$(OBJEXT) \ ../goto-instrument/cover$(OBJEXT) \ - ../path-symex/path-symex$(LIBEXT) + ../path-symex/path-symex$(LIBEXT) \ + ../miniz/miniz$(OBJEXT) INCLUDES= -I .. @@ -37,9 +38,6 @@ endif ifneq ($(wildcard ../java_bytecode/Makefile),) OBJ += ../java_bytecode/java_bytecode$(LIBEXT) CP_CXXFLAGS += -DHAVE_JAVA_BYTECODE - ifneq ($(wildcard $(LIBZIPINC)),) - LIBS += $(LIBZIPLIB) - endif endif ifneq ($(wildcard ../specc/Makefile),) From 1f79d21fb64219c59d3eb596ec911ca441c0ad30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Tue, 14 Feb 2017 11:53:34 +0100 Subject: [PATCH 11/67] regression test with multiple JARs/classpath --- regression/cbmc-java/jar-file3/A.jar | Bin 0 -> 721 bytes regression/cbmc-java/jar-file3/B.jar | Bin 0 -> 721 bytes regression/cbmc-java/jar-file3/C.jar | Bin 0 -> 934 bytes regression/cbmc-java/jar-file3/jarfile3.class | Bin 0 -> 709 bytes regression/cbmc-java/jar-file3/jarfile3.java | 19 ++++++++++++++++++ regression/cbmc-java/jar-file3/test.desc | 8 ++++++++ 6 files changed, 27 insertions(+) create mode 100644 regression/cbmc-java/jar-file3/A.jar create mode 100644 regression/cbmc-java/jar-file3/B.jar create mode 100644 regression/cbmc-java/jar-file3/C.jar create mode 100644 regression/cbmc-java/jar-file3/jarfile3.class create mode 100644 regression/cbmc-java/jar-file3/jarfile3.java create mode 100644 regression/cbmc-java/jar-file3/test.desc diff --git a/regression/cbmc-java/jar-file3/A.jar b/regression/cbmc-java/jar-file3/A.jar new file mode 100644 index 0000000000000000000000000000000000000000..e721e6f32f945341ca9aafca44a794bb16cfeb02 GIT binary patch literal 721 zcmWIWW@Zs#;Nak3$Pf4PVn70%3@i-3t|5-Po_=on|4uP5Ff#;rvvYt{FhP|C;M6Pv zQ~}rQ>*(j{<{BKL=j-;__snS@Z(Y5MyxzK6=gyqp9At3C_`%a6JuhD!Pv48Bt5`TA zUPvC1mXg%U_#v*U_I!z!#dC4dC*rEp7_Mf2D*9N&2zG^l;4&o_pdGG2jBrIdnim9s zvRR2mX_+~x#ww0_$vKI|#jgIo-iI9oYA>t!?p9O#8lCUNZ`vBR!Q6F1Q-DTQz@Ge9 ztE3-^O$zxFE!Xwnp!|b=p>*bhhozrA-fM1bzd!yygPO&wL#{dx7N&33mAAJ0#`)#k z48dDhyY+rAXE8jV@^MLVY1z5E+_@#Co*eA|-%e(4vW~UWax%H@c6Uu&aOj=WCeQnJ zM6c^=-F0mnhxA#E$@xYO>~|TM*coqqsFg9=oA_n@4?Z^oV>i*uG1Hc6ac>E6$vE ze0%0HG0}sPH<+z@1&;seJ8r*CB8U6P#@HjG)}OZV_A!P#r$zWp;kmxxiSXJZv4?-I z=u~tM?3bNZH7EDlG{JALIO}_I-!%OL2i}6vmH++&gC>v>6nKnGA`GZ002aNV6o3lg zQ3^^A=vtBE1Qh=WU<+izwIZbkWD`JfhwLy=+#$eWAQL?%1H4(;Kq{Dla5snnb~gZw CHqIXa literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/jar-file3/B.jar b/regression/cbmc-java/jar-file3/B.jar new file mode 100644 index 0000000000000000000000000000000000000000..d381e413e74f2aa5d1f92381ec7fe608679b7e81 GIT binary patch literal 721 zcmWIWW@Zs#;Nak3C=U1YVn70%3@i-3t|5-Po_=on|4uP5Ff#;rvvYt{FhP|C;M6Pv zQ~}rQ>*(j{<{BKL=j-;__snS@Z(Y5MyxzK6=gyqp9At3C_`%a6JuhD!Pv48Bt5`TA zUPvC1mXg%U_#v*U_I!z!#dC4dC*rEp7_Mf2D*9N&2zG^l;4&o_pdGG2jBrIdnim9s zvRR2mX_+~x#wt#F$vKI|#jgIo-iI9oYA-Lln|61`kH3Y&RVy^NG~E;77i)34*!-wA zIQ*_aut(6x{7Q``_WA~UuQ|Ld{P{Ebzu!Ca=TBWNv&G?s{QMJL*roMui`)>qp?twQ z+3Q7^{^b@9qQIepCtu>P_P*wY%PRA_JeQrmG^OPP=kb~6 z<{#hgne|L`p=|;C7b(TQA9MNs-$>e^E8v)Or~%rTH#=kQTIYU6gN z-;34QWKwO#biP_fuh(^cb4~c4MDz{Dzl@+Lv^lv+>OU}O0vSPp$H*kYfSLke(F;le zr~n?Np!9&Q6**2o@s9wuKqg!(Qffdp0Tg%04g*(j{<{BKL=j-;__snS@Z(Y5MyxzK6=gyqp9At3C_`%a6JuhD!Pv48Bt5`TA zUPvC1mXg%U_#v*U_I!z!#dC4dC*rEp7_Mf2D*9N&2zG^l;4&o_pdGG2jBv&AXjCuo z0cEoii_$W4QjPVJa}tY-eS>2Cg&jp~H{UJWEkD(1={5c%UKd##XPubMqPxOV*iOzs z?ZdWQ_RU-K&c3uq&??>SSR&rJv ziT4i4va`JsduL@3xcy<$LA6U8HoRESQ90Yd{JYGZ_WVRohaAp|w;GeOss)a0?BU$X zqQ$#6(9@#lQF@|G3EQUQXC^u%D)$^p308QnzgNg$d%LZs!B%0nqWmx0l&^aGs(qi~ zxqq$Y(q@$x`)=~yTdKKhiDTmn2TX z?49N|O)EjJ&w%(^$lVXOM%fRp!H`EL8T6;>I$ulW4QyGAB(U1oJpk-#p=bDQs+ zEfkIUd^%kq-b66;T&u{H$5L6(uk`Df?zEFUY@uSi-MVdM^PhX+B7OmpmaVCEP1bH7 zKk$58|Nq4+%{ix6h#3Y=)cQ1M{efd5bEiJM{7`N2YZqII`Y-o)BtCqm^Z(3R?&Ggl z>Lyej`^)#fWzzh_XZsc!SXvaX=RbA$!#pmvXP3U@W;IH&MHjAIYpl2Rs68lU{uE0H zyurx8a1@w41H2iTL>N#LHZ0YG5;iJ;r&LffN7ss+)IiA^0c?RxxK^Y@j%)%bNg_K8 clq3=0Fp!CwKm)v4*+BBlK)4e~UkAGy09`dfUjP6A literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/jar-file3/jarfile3.class b/regression/cbmc-java/jar-file3/jarfile3.class new file mode 100644 index 0000000000000000000000000000000000000000..ececc4cc3057d71a26d614fed6c32b64d2261195 GIT binary patch literal 709 zcmYjPT~8B16g{)ucDo;yLZQ|V#7fZxfttvh1TCmZ6Fwd=Ch)dx2eY+q&Ft3bU*W|^ zpH(7>P4wOWr18w^QXY2Z&bepqIrr}T`t$t*qD`b> zVaY)e3pQaM?mD;!-@>wh*cR~GQ6$yQAc$ib6KV-m8v3A;a2Ul;!#L;+WRIC+fx>1O zg~^sc&R>2hVD1ciQebK~jO704O-HI1noRBqlYU!sN{30%eZ3dFO;dD9g963P?%;nZ z=WsYuUHLrJ7fby>oiKX1-Vfdd9x9j>a5Avb(#XnXWZT0uW<1=-sz6O&Y7Tnodff+LLjpWbZ>m54>t}e>{e9 zM0##-3{waB{Vyn-qOy7h%lrs;jN;Kb?4SS8wKF)EQ7vMmB30xWUxAG&IxEAc!!1VF zh$h>;!i_n;nVT1mH&ScB^o;ur-YF$N!OVR{VNy7AuM6d2cuxcs=TqHV)B-gO Mw&GG-XIyHFzoIF8asU7T literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/jar-file3/jarfile3.java b/regression/cbmc-java/jar-file3/jarfile3.java new file mode 100644 index 00000000000..c9c0cff46d1 --- /dev/null +++ b/regression/cbmc-java/jar-file3/jarfile3.java @@ -0,0 +1,19 @@ +public class jarfile3 +{ + public class A + { + int x=1; + } + public class B + { + int x=1; + } + + void f(int i) + { + A a=new A(); + B b=new B(); + assert(a.x==1); + assert(b.x==1); + } +} diff --git a/regression/cbmc-java/jar-file3/test.desc b/regression/cbmc-java/jar-file3/test.desc new file mode 100644 index 00000000000..8d3b495e1c6 --- /dev/null +++ b/regression/cbmc-java/jar-file3/test.desc @@ -0,0 +1,8 @@ +CORE +C.jar +--function jarfile3.f -classpath A.jar:B.jar +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL +-- +^warning: ignoring From 3d85f48236ad912e69264877e924a043941146f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Thu, 23 Feb 2017 14:05:13 +0100 Subject: [PATCH 12/67] disable unaligned load/store for g++ --- src/miniz/miniz.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miniz/miniz.h b/src/miniz/miniz.h index 45659d8cf1a..6353d3782b2 100644 --- a/src/miniz/miniz.h +++ b/src/miniz/miniz.h @@ -224,7 +224,7 @@ #define MINIZ_LITTLE_ENDIAN 1 #endif -#if MINIZ_X86_OR_X64_CPU +#if defined(MINIZ_X86_OR_X64_CPU) && !defined(__GNUG__) /* Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient integer loads and stores from unaligned addresses. */ #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #endif From 6ae2c79835f2df9b0d2ebfea3ce925d292ee45b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Thu, 23 Feb 2017 14:38:30 +0100 Subject: [PATCH 13/67] auto-fix cpplint errors with generated sed script --- src/miniz/miniz.cpp | 1870 +++++++++++++++++++++---------------------- src/miniz/miniz.h | 18 +- 2 files changed, 944 insertions(+), 944 deletions(-) diff --git a/src/miniz/miniz.cpp b/src/miniz/miniz.cpp index fa5c1903e83..4fff76e87d7 100644 --- a/src/miniz/miniz.cpp +++ b/src/miniz/miniz.cpp @@ -40,11 +40,11 @@ mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; - if (!ptr) + if(!ptr) return MZ_ADLER32_INIT; - while (buf_len) + while(buf_len) { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + for(i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; @@ -55,7 +55,7 @@ mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } - for (; i < block_len; ++i) + for(; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; @@ -64,17 +64,17 @@ mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) return (s2 << 16) + s1; } -/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http://www.geocities.com/malbrain/ */ +/* Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C implementation that balances processor cache usage against speed": http:// www.geocities.com/malbrain/ */ #if 0 mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c }; mz_uint32 crcu32 = (mz_uint32)crc; - if (!ptr) + if(!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; - while (buf_len--) + while(buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; @@ -131,7 +131,7 @@ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) mz_uint32 crc32 = (mz_uint32)crc ^ 0xFFFFFFFF; const mz_uint8 *pByte_buf = (const mz_uint8 *)ptr; - while (buf_len >= 4) + while(buf_len >= 4) { crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[1]) & 0xFF]; @@ -141,7 +141,7 @@ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) buf_len -= 4; } - while (buf_len) + while(buf_len) { crc32 = (crc32 >> 8) ^ s_crc_table[(crc32 ^ pByte_buf[0]) & 0xFF]; ++pByte_buf; @@ -190,9 +190,9 @@ int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); - if (!pStream) + if(!pStream) return MZ_STREAM_ERROR; - if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) + if((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; @@ -201,18 +201,18 @@ int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; - if (!pStream->zalloc) + if(!pStream->zalloc) pStream->zalloc = miniz_def_alloc_func; - if (!pStream->zfree) + if(!pStream->zfree) pStream->zfree = miniz_def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) + if(!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; - if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) + if(tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; @@ -223,7 +223,7 @@ int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mz_deflateReset(mz_streamp pStream) { - if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) + if((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); @@ -236,20 +236,20 @@ int mz_deflate(mz_streamp pStream, int flush) mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; - if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) + if((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; - if (!pStream->avail_out) + if(!pStream->avail_out) return MZ_BUF_ERROR; - if (flush == MZ_PARTIAL_FLUSH) + if(flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; - if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) + if(((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; - for (;;) + for(;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; @@ -265,21 +265,21 @@ int mz_deflate(mz_streamp pStream, int flush) pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; - if (defl_status < 0) + if(defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } - else if (defl_status == TDEFL_STATUS_DONE) + else if(defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } - else if (!pStream->avail_out) + else if(!pStream->avail_out) break; - else if ((!pStream->avail_in) && (flush != MZ_FINISH)) + else if((!pStream->avail_in) && (flush != MZ_FINISH)) { - if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) + if((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; /* Can't make forward progress without some input. */ @@ -290,9 +290,9 @@ int mz_deflate(mz_streamp pStream, int flush) int mz_deflateEnd(mz_streamp pStream) { - if (!pStream) + if(!pStream) return MZ_STREAM_ERROR; - if (pStream->state) + if(pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; @@ -314,7 +314,7 @@ int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char memset(&stream, 0, sizeof(stream)); /* In case mz_ulong is 64-bits (argh I hate longs). */ - if ((source_len | *pDest_len) > 0xFFFFFFFFU) + if((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; @@ -323,11 +323,11 @@ int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char stream.avail_out = (mz_uint32) * pDest_len; status = mz_deflateInit(&stream, level); - if (status != MZ_OK) + if(status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) + if(status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; @@ -359,9 +359,9 @@ typedef struct int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; - if (!pStream) + if(!pStream) return MZ_STREAM_ERROR; - if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) + if((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; @@ -370,13 +370,13 @@ int mz_inflateInit2(mz_streamp pStream, int window_bits) pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; - if (!pStream->zalloc) + if(!pStream->zalloc) pStream->zalloc = miniz_def_alloc_func; - if (!pStream->zfree) + if(!pStream->zfree) pStream->zfree = miniz_def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); - if (!pDecomp) + if(!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; @@ -404,28 +404,28 @@ int mz_inflate(mz_streamp pStream, int flush) size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; - if ((!pStream) || (!pStream->state)) + if((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; - if (flush == MZ_PARTIAL_FLUSH) + if(flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; - if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) + if((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; - if (pState->m_window_bits > 0) + if(pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; - if (pState->m_last_status < 0) + if(pState->m_last_status < 0) return MZ_DATA_ERROR; - if (pState->m_has_flushed && (flush != MZ_FINISH)) + if(pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); - if ((flush == MZ_FINISH) && (first_call)) + if((flush == MZ_FINISH) && (first_call)) { /* MZ_FINISH on the first call implies that the input and output buffers are large enough to hold the entire compressed/decompressed file. */ decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; @@ -441,9 +441,9 @@ int mz_inflate(mz_streamp pStream, int flush) pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; - if (status < 0) + if(status < 0) return MZ_DATA_ERROR; - else if (status != TINFL_STATUS_DONE) + else if(status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; @@ -451,10 +451,10 @@ int mz_inflate(mz_streamp pStream, int flush) return MZ_STREAM_END; } /* flush != MZ_FINISH then we must assume there's more input. */ - if (flush != MZ_FINISH) + if(flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; - if (pState->m_dict_avail) + if(pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); @@ -466,7 +466,7 @@ int mz_inflate(mz_streamp pStream, int flush) return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } - for (;;) + for(;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; @@ -489,20 +489,20 @@ int mz_inflate(mz_streamp pStream, int flush) pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); - if (status < 0) + if(status < 0) return MZ_DATA_ERROR; /* Stream is corrupted (there could be some uncompressed data left in the output dictionary - oh well). */ - else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) + else if((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; /* Signal caller that we can't make forward progress without supplying more input or by setting flush to MZ_FINISH. */ - else if (flush == MZ_FINISH) + else if(flush == MZ_FINISH) { /* The output buffer MUST be large to hold the remaining uncompressed data when flush==MZ_FINISH. */ - if (status == TINFL_STATUS_DONE) + if(status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; /* status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's at least 1 more byte on the way. If there's no more room left in the output buffer then something is wrong. */ - else if (!pStream->avail_out) + else if(!pStream->avail_out) return MZ_BUF_ERROR; } - else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) + else if((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } @@ -511,9 +511,9 @@ int mz_inflate(mz_streamp pStream, int flush) int mz_inflateEnd(mz_streamp pStream) { - if (!pStream) + if(!pStream) return MZ_STREAM_ERROR; - if (pStream->state) + if(pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; @@ -528,7 +528,7 @@ int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char memset(&stream, 0, sizeof(stream)); /* In case mz_ulong is 64-bits (argh I hate longs). */ - if ((source_len | *pDest_len) > 0xFFFFFFFFU) + if((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; @@ -537,11 +537,11 @@ int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char stream.avail_out = (mz_uint32) * pDest_len; status = mz_inflateInit(&stream); - if (status != MZ_OK) + if(status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); - if (status != MZ_STREAM_END) + if(status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; @@ -563,8 +563,8 @@ const char *mz_error(int err) { MZ_DATA_ERROR, "data error" }, { MZ_MEM_ERROR, "out of memory" }, { MZ_BUF_ERROR, "buf error" }, { MZ_VERSION_ERROR, "version error" }, { MZ_PARAM_ERROR, "parameter error" } }; mz_uint i; - for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) - if (s_error_descs[i].m_err == err) + for(i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) + if(s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } @@ -709,24 +709,24 @@ static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *p mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); - for (i = 0; i < num_syms; i++) + for(i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } - while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) + while((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; - for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) + for(pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; - for (i = 0; i < 256; i++) + for(i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } - for (i = 0; i < num_syms; i++) + for(i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; @@ -741,9 +741,9 @@ static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *p static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; - if (n == 0) + if(n == 0) return; - else if (n == 1) + else if(n == 1) { A[0].m_key = 1; return; @@ -751,16 +751,16 @@ static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) A[0].m_key += A[1].m_key; root = 0; leaf = 2; - for (next = 1; next < n - 1; next++) + for(next = 1; next < n - 1; next++) { - if (leaf >= n || A[root].m_key < A[leaf].m_key) + if(leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; - if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) + if(leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; @@ -769,20 +769,20 @@ static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; - for (next = n - 3; next >= 0; next--) + for(next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; - while (avbl > 0) + while(avbl > 0) { - while (root >= 0 && (int)A[root].m_key == dpth) + while(root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } - while (avbl > used) + while(avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; @@ -802,17 +802,17 @@ static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_l { int i; mz_uint32 total = 0; - if (code_list_len <= 1) + if(code_list_len <= 1) return; - for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) + for(i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; - for (i = max_code_size; i > 0; i--) + for(i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); - while (total != (1UL << max_code_size)) + while(total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; - for (i = max_code_size - 1; i > 0; i--) - if (pNum_codes[i]) + for(i = max_code_size - 1; i > 0; i--) + if(pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; @@ -827,9 +827,9 @@ static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); - if (static_table) + if(static_table) { - for (i = 0; i < table_len; i++) + for(i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else @@ -837,8 +837,8 @@ static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; - for (i = 0; i < table_len; i++) - if (pSym_count[i]) + for(i = 0; i < table_len; i++) + if(pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; @@ -847,29 +847,29 @@ static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); - for (i = 0; i < num_used_syms; i++) + for(i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); - for (i = 1, j = num_used_syms; i <= code_size_limit; i++) - for (l = num_codes[i]; l > 0; l--) + for(i = 1, j = num_used_syms; i <= code_size_limit; i++) + for(l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; - for (j = 0, i = 2; i <= code_size_limit; i++) + for(j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); - for (i = 0; i < table_len; i++) + for(i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; - if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) + if((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; - for (l = code_size; l > 0; l--, code >>= 1) + for(l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } @@ -883,9 +883,9 @@ static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ - while (d->m_bits_in >= 8) \ + while(d->m_bits_in >= 8) \ { \ - if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ + if(d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ @@ -895,12 +895,12 @@ static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ - if (rle_repeat_count) \ + if(rle_repeat_count) \ { \ - if (rle_repeat_count < 3) \ + if(rle_repeat_count < 3) \ { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)(d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ - while (rle_repeat_count--) \ + while(rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } \ else \ @@ -915,15 +915,15 @@ static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ - if (rle_z_count) \ + if(rle_z_count) \ { \ - if (rle_z_count < 3) \ + if(rle_z_count < 3) \ { \ d->m_huff_count[2][0] = (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ - while (rle_z_count--) \ + while(rle_z_count--) \ packed_code_sizes[num_packed_code_sizes++] = 0; \ } \ - else if (rle_z_count <= 10) \ + else if(rle_z_count <= 10) \ { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ @@ -952,11 +952,11 @@ static void tdefl_start_dynamic_block(tdefl_compressor *d) tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); - for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) - if (d->m_huff_code_sizes[0][num_lit_codes - 1]) + for(num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) + if(d->m_huff_code_sizes[0][num_lit_codes - 1]) break; - for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) - if (d->m_huff_code_sizes[1][num_dist_codes - 1]) + for(num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) + if(d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); @@ -967,13 +967,13 @@ static void tdefl_start_dynamic_block(tdefl_compressor *d) rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); - for (i = 0; i < total_code_sizes_to_pack; i++) + for(i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; - if (!code_size) + if(!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); - if (++rle_z_count == 138) + if(++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } @@ -981,20 +981,20 @@ static void tdefl_start_dynamic_block(tdefl_compressor *d) else { TDEFL_RLE_ZERO_CODE_SIZE(); - if (code_size != prev_code_size) + if(code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } - else if (++rle_repeat_count == 6) + else if(++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } - if (rle_repeat_count) + if(rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } @@ -1010,20 +1010,20 @@ static void tdefl_start_dynamic_block(tdefl_compressor *d) TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); - for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) - if (d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) + for(num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) + if(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); - for (i = 0; (int)i < num_bit_lengths; i++) + for(i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS(d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); - for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) + for(packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); - if (code >= 16) + if(code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } @@ -1033,13 +1033,13 @@ static void tdefl_start_static_block(tdefl_compressor *d) mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; - for (i = 0; i <= 143; ++i) + for(i = 0; i <= 143; ++i) *p++ = 8; - for (; i <= 255; ++i) + for(; i <= 255; ++i) *p++ = 9; - for (; i <= 279; ++i) + for(; i <= 279; ++i) *p++ = 7; - for (; i <= 287; ++i) + for(; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); @@ -1069,12 +1069,12 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) } flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) + for(pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { - if (flags == 1) + if(flags == 1) flags = *pLZ_codes++ | 0x100; - if (flags & 1) + if(flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); @@ -1102,14 +1102,14 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + if(((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); - if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) + if(((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; @@ -1119,7 +1119,7 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) } } - if (pOutput_buf >= d->m_pOutput_buf_end) + if(pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; @@ -1134,7 +1134,7 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) d->m_bits_in = 0; d->m_bit_buffer = 0; - while (bits_in) + while(bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); @@ -1153,11 +1153,11 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) mz_uint8 *pLZ_codes; flags = 1; - for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) + for(pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { - if (flags == 1) + if(flags == 1) flags = *pLZ_codes++ | 0x100; - if (flags & 1) + if(flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); @@ -1167,7 +1167,7 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); - if (match_dist < 512) + if(match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; @@ -1197,7 +1197,7 @@ static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { - if (static_block) + if(static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); @@ -1222,7 +1222,7 @@ static int tdefl_flush_block(tdefl_compressor *d, int flush) *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); - if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) + if((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); @@ -1234,50 +1234,50 @@ static int tdefl_flush_block(tdefl_compressor *d, int flush) saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; - if (!use_raw_block) + if(!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); /* If the block gets expanded, forget the current contents of the output buffer and send a raw block instead. */ - if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && + if(((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); - if (d->m_bits_in) + if(d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } - for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) + for(i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } - for (i = 0; i < d->m_total_lz_bytes; ++i) + for(i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS(d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } /* Check for the extremely unlikely (if not impossible) case of the compressed block not fitting into the output buffer when using dynamic codes. */ - else if (!comp_block_succeeded) + else if(!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } - if (flush) + if(flush) { - if (flush == TDEFL_FINISH) + if(flush == TDEFL_FINISH) { - if (d->m_bits_in) + if(d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } - if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) + if(d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; - for (i = 0; i < 4; i++) + for(i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; @@ -1288,11 +1288,11 @@ static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); - if (d->m_bits_in) + if(d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } - for (i = 2; i; --i, z ^= 0xFFFF) + for(i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } @@ -1311,20 +1311,20 @@ static int tdefl_flush_block(tdefl_compressor *d, int flush) d->m_total_lz_bytes = 0; d->m_block_index++; - if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) + if((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { - if (d->m_pPut_buf_func) + if(d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; - if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) + if(!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } - else if (pOutput_buf_start == d->m_output_buf) + else if(pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN((size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; - if ((n -= bytes_to_copy) != 0) + if((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; @@ -1348,46 +1348,46 @@ static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahe const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) + if(max_match_len <= match_len) return; - for (;;) + for(;;) { - for (;;) + for(;;) { - if (--num_probes_left == 0) + if(--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + if((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ + if(TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } - if (!dist) + if(!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); - if (TDEFL_READ_UNALIGNED_WORD(q) != s01) + if(TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { - } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + } while((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); - if (!probe_len) + if(!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, (mz_uint)TDEFL_MAX_MATCH_LEN); break; } - else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) + else if((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; - if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) + if((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } @@ -1401,36 +1401,36 @@ static MZ_FORCEINLINE void tdefl_find_match(tdefl_compressor *d, mz_uint lookahe const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); - if (max_match_len <= match_len) + if(max_match_len <= match_len) return; - for (;;) + for(;;) { - for (;;) + for(;;) { - if (--num_probes_left == 0) + if(--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ - if ((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ + if((!next_probe_pos) || ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ - if ((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ + if((d->m_dict[probe_pos + match_len] == c0) && (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } - if (!dist) + if(!dist) break; p = s; q = d->m_dict + probe_pos; - for (probe_len = 0; probe_len < max_match_len; probe_len++) - if (*p++ != *q++) + for(probe_len = 0; probe_len < max_match_len; probe_len++) + if(*p++ != *q++) break; - if (probe_len > match_len) + if(probe_len > match_len) { *pMatch_dist = dist; - if ((*pMatch_len = match_len = probe_len) == max_match_len) + if((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; @@ -1447,7 +1447,7 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) + while((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; @@ -1455,11 +1455,11 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; - while (num_bytes_to_process) + while(num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + if(dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; @@ -1467,10 +1467,10 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); - if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) + if((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; - while (lookahead_size >= 4) + while(lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; @@ -1479,20 +1479,20 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; - if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) + if(((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { - } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && + } while((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); - if (!probe_len) + if(!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; - if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) + if((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; @@ -1527,7 +1527,7 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) d->m_huff_count[0][(mz_uint8)first_trigram]++; } - if (--num_flags_left == 0) + if(--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; @@ -1540,7 +1540,7 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + if(pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; @@ -1550,7 +1550,7 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) + if((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; @@ -1559,14 +1559,14 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) } } - while (lookahead_size) + while(lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); - if (--num_flags_left == 0) + if(--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; @@ -1579,7 +1579,7 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; - if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) + if(pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; @@ -1589,7 +1589,7 @@ static mz_bool tdefl_compress_fast(tdefl_compressor *d) d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; - if ((n = tdefl_flush_block(d, 0)) != 0) + if((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; @@ -1615,7 +1615,7 @@ static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 li d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); - if (--d->m_num_flags_left == 0) + if(--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; @@ -1639,7 +1639,7 @@ static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); - if (--d->m_num_flags_left == 0) + if(--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; @@ -1649,7 +1649,7 @@ static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; - if (match_len >= TDEFL_MIN_MATCH_LEN) + if(match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } @@ -1659,11 +1659,11 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; - while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) + while((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; /* Update dictionary and hash chains. Keeps the lookahead size equal to TDEFL_MAX_MATCH_LEN. */ - if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) + if((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; @@ -1671,11 +1671,11 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; - while (pSrc != pSrc_end) + while(pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + if(dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; @@ -1686,15 +1686,15 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) } else { - while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + while((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; - if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) + if(dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; - if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) + if((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); @@ -1704,7 +1704,7 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); - if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) + if((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; /* Simple lazy/greedy parsing state machine. */ @@ -1712,19 +1712,19 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; - if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) + if(d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { - if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) + if((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; - while (cur_match_len < d->m_lookahead_size) + while(cur_match_len < d->m_lookahead_size) { - if (d->m_dict[cur_pos + cur_match_len] != c) + if(d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } - if (cur_match_len < TDEFL_MIN_MATCH_LEN) + if(cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; @@ -1734,16 +1734,16 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } - if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) + if(((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } - if (d->m_saved_match_len) + if(d->m_saved_match_len) { - if (cur_match_len > d->m_saved_match_len) + if(cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); - if (cur_match_len >= 128) + if(cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; @@ -1763,9 +1763,9 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) d->m_saved_match_len = 0; } } - else if (!cur_match_dist) + else if(!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); - else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) + else if((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; @@ -1782,13 +1782,13 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); /* Check if it's time to flush the current LZ codes to the internal output buffer. */ - if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || + if((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; - if ((n = tdefl_flush_block(d, 0)) != 0) + if((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } @@ -1800,12 +1800,12 @@ static mz_bool tdefl_compress_normal(tdefl_compressor *d) static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { - if (d->m_pIn_buf_size) + if(d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } - if (d->m_pOut_buf_size) + if(d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); @@ -1821,11 +1821,11 @@ static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { - if (!d) + if(!d) { - if (pIn_buf_size) + if(pIn_buf_size) *pIn_buf_size = 0; - if (pOut_buf_size) + if(pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } @@ -1839,44 +1839,44 @@ tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pI d->m_out_buf_ofs = 0; d->m_flush = flush; - if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || + if(((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { - if (pIn_buf_size) + if(pIn_buf_size) *pIn_buf_size = 0; - if (pOut_buf_size) + if(pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); - if ((d->m_output_flush_remaining) || (d->m_finished)) + if((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES &&MINIZ_LITTLE_ENDIAN - if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && + if(((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { - if (!tdefl_compress_fast(d)) + if(!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif /* #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN */ { - if (!tdefl_compress_normal(d)) + if(!tdefl_compress_normal(d)) return d->m_prev_return_status; } - if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) + if((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); - if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) + if((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { - if (tdefl_flush_block(d, flush) < 0) + if(tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); - if (flush == TDEFL_FULL_FLUSH) + if(flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); @@ -1901,7 +1901,7 @@ tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_fun d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; - if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) + if(!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; @@ -1940,10 +1940,10 @@ mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put { tdefl_compressor *pComp; mz_bool succeeded; - if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) + if(((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); - if (!pComp) + if(!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); @@ -1962,18 +1962,18 @@ static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; - if (new_size > p->m_capacity) + if(new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; - if (!p->m_expandable) + if(!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); - } while (new_size > new_capacity); + } while(new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); - if (!pNew_buf) + if(!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; @@ -1987,12 +1987,12 @@ void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_ { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); - if (!pOut_len) + if(!pOut_len) return nullptr; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + if(!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; @@ -2002,11 +2002,11 @@ size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); - if (!pOut_buf) + if(!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; - if (!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) + if(!tdefl_compress_mem_to_output(pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } @@ -2018,18 +2018,18 @@ static const mz_uint s_tdefl_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 5 mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); - if (window_bits > 0) + if(window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; - if (!level) + if(!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; - else if (strategy == MZ_FILTERED) + else if(strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; - else if (strategy == MZ_HUFFMAN_ONLY) + else if(strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; - else if (strategy == MZ_FIXED) + else if(strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; - else if (strategy == MZ_RLE) + else if(strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; @@ -2053,27 +2053,27 @@ void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; - if (!pComp) + if(!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); - if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) + if(NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } /* write dummy header */ - for (z = 41; z; --z) + for(z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); /* compress image data */ tdefl_init(pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); - for (y = 0; y < h; ++y) + for(y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } - if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) + if(tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); @@ -2087,12 +2087,12 @@ void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8) * pLen_out, 0x49, 0x44, 0x41, 0x54 }; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); - for (i = 0; i < 4; ++i, c <<= 8) + for(i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } /* write footer (IDAT CRC-32, followed by IEND chunk) */ - if (!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) + if(!tdefl_output_buffer_putter("\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); @@ -2100,7 +2100,7 @@ void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); - for (i = 0; i < 4; ++i, c <<= 8) + for(i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); /* compute final size of file, grab compressed data buffer and return */ *pLen_out += 57; @@ -2171,7 +2171,7 @@ extern "C" { #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ - switch (r->m_state) \ + switch(r->m_state) \ { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ @@ -2187,7 +2187,7 @@ extern "C" { #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do \ { \ - for (;;) \ + for(;;) \ { \ TINFL_CR_RETURN(state_index, result); \ } \ @@ -2198,7 +2198,7 @@ extern "C" { #define TINFL_GET_BYTE(state_index, c) \ do \ { \ - while (pIn_buf_cur >= pIn_buf_end) \ + while(pIn_buf_cur >= pIn_buf_end) \ { \ TINFL_CR_RETURN(state_index, (decomp_flags &TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); \ } \ @@ -2213,11 +2213,11 @@ extern "C" { TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ - } while (num_bits < (mz_uint)(n)) + } while(num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do \ { \ - if (num_bits < (mz_uint)(n)) \ + if(num_bits < (mz_uint)(n)) \ { \ TINFL_NEED_BITS(state_index, n); \ } \ @@ -2228,7 +2228,7 @@ extern "C" { #define TINFL_GET_BITS(state_index, b, n) \ do \ { \ - if (num_bits < (mz_uint)(n)) \ + if(num_bits < (mz_uint)(n)) \ { \ TINFL_NEED_BITS(state_index, n); \ } \ @@ -2246,26 +2246,26 @@ extern "C" { do \ { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ - if (temp >= 0) \ + if(temp >= 0) \ { \ code_len = temp >> 9; \ - if ((code_len) && (num_bits >= code_len)) \ + if((code_len) && (num_bits >= code_len)) \ break; \ } \ - else if (num_bits > TINFL_FAST_LOOKUP_BITS) \ + else if(num_bits > TINFL_FAST_LOOKUP_BITS) \ { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do \ { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while ((temp < 0) && (num_bits >= (code_len + 1))); \ - if (temp >= 0) \ + } while((temp < 0) && (num_bits >= (code_len + 1))); \ + if(temp >= 0) \ break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ - } while (num_bits < 15); + } while(num_bits < 15); /* TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex than you would initially expect because the zlib API expects the decompressor to never read */ /* beyond the final byte of the deflate stream. (In other words, when this macro wants to read another byte from the input, it REALLY needs another byte in order to fully */ @@ -2278,9 +2278,9 @@ extern "C" { { \ int temp; \ mz_uint code_len, c; \ - if (num_bits < 15) \ + if(num_bits < 15) \ { \ - if ((pIn_buf_end - pIn_buf_cur) < 2) \ + if((pIn_buf_end - pIn_buf_cur) < 2) \ { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } \ @@ -2291,7 +2291,7 @@ extern "C" { num_bits += 16; \ } \ } \ - if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ + if((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) \ code_len = temp >> 9, temp &= 511; \ else \ { \ @@ -2299,7 +2299,7 @@ extern "C" { do \ { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ - } while (temp < 0); \ + } while(temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ @@ -2324,7 +2324,7 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t) - 1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; /* Ensure the output buffer's size is a power of 2, unless the output buffer is large enough to hold the entire output file (in which case it doesn't matter). */ - if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) + if(((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; @@ -2340,14 +2340,14 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + if(decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); - if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + if(!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1U << (8U + (r->m_zhdr0 >> 4))))); - if (counter) + if(counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } @@ -2357,38 +2357,38 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; - if (r->m_type == 0) + if(r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); - for (counter = 0; counter < 4; ++counter) + for(counter = 0; counter < 4; ++counter) { - if (num_bits) + if(num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } - if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) + if((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } - while ((counter) && (num_bits)) + while((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); - while (pOut_buf_cur >= pOut_buf_end) + while(pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } - while (counter) + while(counter) { size_t n; - while (pOut_buf_cur >= pOut_buf_end) + while(pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } - while (pIn_buf_cur >= pIn_buf_end) + while(pIn_buf_cur >= pIn_buf_end) { TINFL_CR_RETURN(38, (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) ? TINFL_STATUS_NEEDS_MORE_INPUT : TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS); } @@ -2399,37 +2399,37 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex counter -= (mz_uint)n; } } - else if (r->m_type == 3) + else if(r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { - if (r->m_type == 1) + if(r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); - for (i = 0; i <= 143; ++i) + for(i = 0; i <= 143; ++i) *p++ = 8; - for (; i <= 255; ++i) + for(; i <= 255; ++i) *p++ = 9; - for (; i <= 279; ++i) + for(; i <= 279; ++i) *p++ = 7; - for (; i <= 287; ++i) + for(; i <= 287; ++i) *p++ = 8; } else { - for (counter = 0; counter < 3; counter++) + for(counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); - for (counter = 0; counter < r->m_table_sizes[2]; counter++) + for(counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); @@ -2437,7 +2437,7 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex } r->m_table_sizes[2] = 19; } - for (; (int)r->m_type >= 0; r->m_type--) + for(; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; @@ -2446,48 +2446,48 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); - for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) + for(i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; - for (i = 1; i <= 15; ++i) + for(i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } - if ((65536 != total) && (used_syms > 1)) + if((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } - for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) + for(tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; - if (!code_size) + if(!code_size) continue; cur_code = next_code[code_size]++; - for (l = code_size; l > 0; l--, cur_code >>= 1) + for(l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); - if (code_size <= TINFL_FAST_LOOKUP_BITS) + if(code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); - while (rev_code < TINFL_FAST_LOOKUP_SIZE) + while(rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } - if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) + if(0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); - for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) + for(j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); - if (!pTable->m_tree[-tree_cur - 1]) + if(!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; @@ -2499,18 +2499,18 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } - if (r->m_type == 2) + if(r->m_type == 2) { - for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) + for(counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); - if (dist < 16) + if(dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } - if ((dist == 16) && (!counter)) + if((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } @@ -2520,7 +2520,7 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } - if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) + if((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } @@ -2528,17 +2528,17 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } - for (;;) + for(;;) { mz_uint8 *pSrc; - for (;;) + for(;;) { - if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) + if(((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); - if (counter >= 256) + if(counter >= 256) break; - while (pOut_buf_cur >= pOut_buf_end) + while(pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } @@ -2549,21 +2549,21 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF - if (num_bits < 30) + if(num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else - if (num_bits < 15) + if(num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + if((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { @@ -2571,23 +2571,23 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; - } while (sym2 < 0); + } while(sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; - if (counter & 256) + if(counter & 256) break; #if !TINFL_USE_64BIT_BITBUF - if (num_bits < 15) + if(num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif - if ((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) + if((sym2 = r->m_tables[0].m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { @@ -2595,13 +2595,13 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex do { sym2 = r->m_tables[0].m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; - } while (sym2 < 0); + } while(sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; - if (sym2 & 256) + if(sym2 & 256) { pOut_buf_cur++; counter = sym2; @@ -2611,12 +2611,12 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex pOut_buf_cur += 2; } } - if ((counter &= 511) == 256) + if((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; - if (num_extra) + if(num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); @@ -2626,7 +2626,7 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; - if (num_extra) + if(num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); @@ -2634,18 +2634,18 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; - if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) + if((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); - if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) + if((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { - while (counter--) + while(counter--) { - while (pOut_buf_cur >= pOut_buf_end) + while(pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } @@ -2654,7 +2654,7 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES - else if ((counter >= 9) && (counter <= dist)) + else if((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do @@ -2662,13 +2662,13 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; - } while ((pSrc += 8) < pSrc_end); - if ((counter &= 7) < 3) + } while((pSrc += 8) < pSrc_end); + if((counter &= 7) < 3) { - if (counter) + if(counter) { pOut_buf_cur[0] = pSrc[0]; - if (counter > 1) + if(counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } @@ -2683,22 +2683,22 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; - } while ((int)(counter -= 3) > 2); - if ((int)counter > 0) + } while((int)(counter -= 3) > 2); + if((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; - if ((int)counter > 1) + if((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } - } while (!(r->m_final & 1)); + } while(!(r->m_final & 1)); /* Ensure byte alignment and put back any bytes from the bitbuf if we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ /* I'm being super conservative here. A number of simplifications can be made to the byte alignment part, and the Adler32 check shouldn't ever need to worry about reading from the bitbuf now. */ TINFL_SKIP_BITS(32, num_bits & 7); - while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + while((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { --pIn_buf_cur; num_bits -= 8; @@ -2706,12 +2706,12 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex bit_buf &= (tinfl_bit_buf_t)((1ULL << num_bits) - 1ULL); MZ_ASSERT(!num_bits); /* if this assert fires then we've read beyond the end of non-deflate/zlib streams with following data (such as gzip streams). */ - if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) + if(decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { - for (counter = 0; counter < 4; ++counter) + for(counter = 0; counter < 4; ++counter) { mz_uint s; - if (num_bits) + if(num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); @@ -2726,9 +2726,9 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex /* As long as we aren't telling the caller that we NEED more input to make forward progress: */ /* Put back any bytes from the bitbuf in case we've looked ahead too far on gzip, or other Deflate streams followed by arbitrary data. */ /* We need to be very careful here to NOT push back any bytes we definitely know we need to make forward progress, though, or we'll lock the caller up into an inf loop. */ - if ((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) + if((status != TINFL_STATUS_NEEDS_MORE_INPUT) && (status != TINFL_STATUS_FAILED_CANNOT_MAKE_PROGRESS)) { - while ((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) + while((pIn_buf_cur > pIn_buf_next) && (num_bits >= 8)) { --pIn_buf_cur; num_bits -= 8; @@ -2742,15 +2742,15 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; - if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) + if((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; - while (buf_len) + while(buf_len) { - for (i = 0; i + 7 < block_len; i += 8, ptr += 8) + for(i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; @@ -2761,14 +2761,14 @@ tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_nex s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } - for (; i < block_len; ++i) + for(; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; - if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) + if((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; @@ -2782,12 +2782,12 @@ void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, siz size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); - for (;;) + for(;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); - if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) + if((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; @@ -2795,13 +2795,13 @@ void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, siz } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; - if (status == TINFL_STATUS_DONE) + if(status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; - if (new_out_buf_capacity < 128) + if(new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); - if (!pNew_buf) + if(!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; @@ -2828,18 +2828,18 @@ int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; - if (!pDict) + if(!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); - for (;;) + for(;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; - if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) + if((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; - if (status != TINFL_STATUS_HAS_MORE_OUTPUT) + if(status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; @@ -2854,7 +2854,7 @@ int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_decompressor *tinfl_decompressor_alloc() { tinfl_decompressor *pDecomp = (tinfl_decompressor *)MZ_MALLOC(sizeof(tinfl_decompressor)); - if (pDecomp) + if(pDecomp) tinfl_init(pDecomp); return pDecomp; } @@ -2916,7 +2916,7 @@ static FILE *mz_fopen(const char *pFilename, const char *pMode) static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; - if (freopen_s(&pFile, pPath, pMode, pStream)) + if(freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } @@ -3167,15 +3167,15 @@ static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array * void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); - if (pArray->m_capacity >= min_new_capacity) + if(pArray->m_capacity >= min_new_capacity) return MZ_TRUE; - if (growing) + if(growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); - while (new_capacity < min_new_capacity) + while(new_capacity < min_new_capacity) new_capacity *= 2; } - if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) + if(NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; @@ -3184,9 +3184,9 @@ static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array * static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { - if (new_capacity > pArray->m_capacity) + if(new_capacity > pArray->m_capacity) { - if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) + if(!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; @@ -3194,9 +3194,9 @@ static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_ static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { - if (new_size > pArray->m_capacity) + if(new_size > pArray->m_capacity) { - if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) + if(!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; @@ -3211,7 +3211,7 @@ static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_ static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; - if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) + if(!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; @@ -3238,7 +3238,7 @@ static void mz_zip_time_t_to_dos_time(MZ_TIME_T time, mz_uint16 *pDOS_time, mz_u struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); - if (err) + if(err) { *pDOS_date = 0; *pDOS_time = 0; @@ -3258,7 +3258,7 @@ static mz_bool mz_zip_get_file_modified_time(const char *pFilename, MZ_TIME_T *p struct MZ_FILE_STAT_STRUCT file_stat; /* On Linux with x86 glibc, this call will fail on large files (I think >= 0x80000000 bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. */ - if (MZ_FILE_STAT(pFilename, &file_stat) != 0) + if(MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; *pTime = file_stat.st_mtime; @@ -3281,7 +3281,7 @@ static mz_bool mz_zip_set_file_times(const char *pFilename, MZ_TIME_T access_tim static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_error err_num) { - if (pZip) + if(pZip) pZip->m_last_error = err_num; return MZ_FALSE; } @@ -3289,14 +3289,14 @@ static MZ_FORCEINLINE mz_bool mz_zip_set_error(mz_zip_archive *pZip, mz_zip_erro static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) { (void)flags; - if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + if((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (!pZip->m_pAlloc) + if(!pZip->m_pAlloc) pZip->m_pAlloc = miniz_def_alloc_func; - if (!pZip->m_pFree) + if(!pZip->m_pFree) pZip->m_pFree = miniz_def_free_func; - if (!pZip->m_pRealloc) + if(!pZip->m_pRealloc) pZip->m_pRealloc = miniz_def_realloc_func; pZip->m_archive_size = 0; @@ -3304,7 +3304,7 @@ static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint flags) pZip->m_total_files = 0; pZip->m_last_error = MZ_ZIP_NO_ERROR; - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + if(NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); @@ -3329,9 +3329,9 @@ static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pC pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) + while(pL < pE) { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + if((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; @@ -3358,41 +3358,41 @@ static void mz_zip_reader_sort_central_dir_offsets_by_filename(mz_zip_archive *p mz_uint32 start, end; const mz_uint32 size = pZip->m_total_files; - if (size <= 1U) + if(size <= 1U) return; pIndices = &MZ_ZIP_ARRAY_ELEMENT(&pState->m_sorted_central_dir_offsets, mz_uint32, 0); start = (size - 2U) >> 1U; - for (;;) + for(;;) { mz_uint64 child, root = start; - for (;;) + for(;;) { - if ((child = (root << 1U) + 1U) >= size) + if((child = (root << 1U) + 1U) >= size) break; child += (((child + 1U) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U]))); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + if(!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } - if (!start) + if(!start) break; start--; } end = size - 1; - while (end > 0) + while(end > 0) { mz_uint64 child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); - for (;;) + for(;;) { - if ((child = (root << 1U) + 1U) >= end) + if((child = (root << 1U) + 1U) >= end) break; child += (((child + 1U) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1U])); - if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) + if(!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; @@ -3408,36 +3408,36 @@ static mz_bool mz_zip_reader_locate_header_sig(mz_zip_archive *pZip, mz_uint32 r mz_uint8 *pBuf = (mz_uint8 *)buf_u32; /* Basic sanity checks - reject files which are too small */ - if (pZip->m_archive_size < record_size) + if(pZip->m_archive_size < record_size) return MZ_FALSE; /* Find the record by scanning the file from the end towards the beginning. */ cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); - for (;;) + for(;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; - for (i = n - 4; i >= 0; --i) + for(i = n - 4; i >= 0; --i) { mz_uint s = MZ_READ_LE32(pBuf + i); - if (s == record_sig) + if(s == record_sig) { - if ((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) + if((pZip->m_archive_size - (cur_file_ofs + i)) >= record_size) break; } } - if (i >= 0) + if(i >= 0) { cur_file_ofs += i; break; } /* Give up if we've searched the entire file, or we've gone back "too far" (~64kb) */ - if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) + if((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (MZ_UINT16_MAX + record_size))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); @@ -3466,32 +3466,32 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag mz_uint64 zip64_end_of_central_dir_ofs = 0; /* Basic sanity checks - reject files which are too small, and check the first 4 bytes of the file to make sure a local header is there. */ - if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - if (!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) + if(!mz_zip_reader_locate_header_sig(pZip, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE, &cur_file_ofs)) return mz_zip_set_error(pZip, MZ_ZIP_FAILED_FINDING_CENTRAL_DIR); /* Read and verify the end of central directory record. */ - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - if (MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) + if(MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - if (cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + if(cur_file_ofs >= (MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE + MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) { - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs - MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE, pZip64_locator, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) { - if (MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) + if(MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG) { zip64_end_of_central_dir_ofs = MZ_READ_LE64(pZip64_locator + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS); - if (zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) + if(zip64_end_of_central_dir_ofs > (pZip->m_archive_size - MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE)) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - if (pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(pZip->m_pRead(pZip->m_pIO_opaque, zip64_end_of_central_dir_ofs, pZip64_end_of_central_dir, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) { - if (MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) + if(MZ_READ_LE32(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIG_OFS) == MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIG) { pZip->m_pState->m_zip64 = MZ_TRUE; } @@ -3507,7 +3507,7 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS); cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); - if (pZip->m_pState->m_zip64) + if(pZip->m_pState->m_zip64) { mz_uint32 zip64_total_num_of_disks = MZ_READ_LE32(pZip64_locator + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS); mz_uint64 zip64_cdir_total_entries = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS); @@ -3515,25 +3515,25 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag mz_uint64 zip64_size_of_end_of_central_dir_record = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_SIZE_OF_RECORD_OFS); mz_uint64 zip64_size_of_central_directory = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_SIZE_OFS); - if (zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) + if(zip64_size_of_end_of_central_dir_record < (MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE - 12)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if (zip64_total_num_of_disks != 1U) + if(zip64_total_num_of_disks != 1U) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); /* Check for miniz's practical limits */ - if (zip64_cdir_total_entries > MZ_UINT32_MAX) + if(zip64_cdir_total_entries > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); pZip->m_total_files = (mz_uint32)zip64_cdir_total_entries; - if (zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) + if(zip64_cdir_total_entries_on_this_disk > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); cdir_entries_on_this_disk = (mz_uint32)zip64_cdir_total_entries_on_this_disk; /* Check for miniz's current practical limits (sorry, this should be enough for millions of files) */ - if (zip64_size_of_central_directory > MZ_UINT32_MAX) + if(zip64_size_of_central_directory > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); cdir_size = (mz_uint32)zip64_size_of_central_directory; @@ -3545,50 +3545,50 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag cdir_ofs = MZ_READ_LE64(pZip64_end_of_central_dir + MZ_ZIP64_ECDH_CDIR_OFS_OFS); } - if (pZip->m_total_files != cdir_entries_on_this_disk) + if(pZip->m_total_files != cdir_entries_on_this_disk) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) + if(((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - if (cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) + if(cdir_size < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) + if((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pZip->m_central_directory_file_ofs = cdir_ofs; - if (pZip->m_total_files) + if(pZip->m_total_files) { mz_uint i, n; /* Read the entire central directory into a heap block, and allocate another heap block to hold the unsorted central dir file record offsets, and possibly another to hold the sorted indices. */ - if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || + if((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - if (sort_central_dir) + if(sort_central_dir) { - if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) + if(!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) + if(pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); /* Now create an index into the central directory file records, do some basic sanity checking on each record */ p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; - for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) + for(n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, disk_index, bit_flags, filename_size, ext_data_size; mz_uint64 comp_size, decomp_size, local_header_ofs; - if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) + if((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); - if (sort_central_dir) + if(sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); @@ -3597,29 +3597,29 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag filename_size = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); ext_data_size = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); - if ((!pZip->m_pState->m_zip64_has_extended_info_fields) && + if((!pZip->m_pState->m_zip64_has_extended_info_fields) && (ext_data_size) && (MZ_MAX(MZ_MAX(comp_size, decomp_size), local_header_ofs) == MZ_UINT32_MAX)) { /* Attempt to find zip64 extended information field in the entry's extra data */ mz_uint32 extra_size_remaining = ext_data_size; - if (extra_size_remaining) + if(extra_size_remaining) { const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size; do { - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + if(extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); mz_uint32 field_id = MZ_READ_LE16(pExtra_data); mz_uint32 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + if((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + if(field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { /* Ok, the archive didn't have any zip64 headers but it uses a zip64 extended information field so mark it as zip64 anyway (this can occur with infozip's zip util when it reads compresses files from stdin). */ pZip->m_pState->m_zip64 = MZ_TRUE; @@ -3629,32 +3629,32 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; - } while (extra_size_remaining); + } while(extra_size_remaining); } } /* I've seen archives that aren't marked as zip64 that uses zip64 ext data, argh */ - if ((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) + if((comp_size != MZ_UINT32_MAX) && (decomp_size != MZ_UINT32_MAX)) { - if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) + if(((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); - if ((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) + if((disk_index == MZ_UINT16_MAX) || ((disk_index != num_this_disk) && (disk_index != 1))) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_MULTIDISK); - if (comp_size != MZ_UINT32_MAX) + if(comp_size != MZ_UINT32_MAX) { - if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) + if(((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } bit_flags = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - if (bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) + if(bit_flags & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_LOCAL_DIR_IS_MASKED) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); - if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) + if((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); n -= total_header_size; @@ -3662,7 +3662,7 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag } } - if (sort_central_dir) + if(sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; @@ -3670,7 +3670,7 @@ static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint flag void mz_zip_zero_struct(mz_zip_archive *pZip) { - if (pZip) + if(pZip) MZ_CLEAR_OBJ(*pZip); } @@ -3678,18 +3678,18 @@ static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last { mz_bool status = MZ_TRUE; - if (!pZip) + if(!pZip) return MZ_FALSE; - if ((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + if((!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) { - if (set_last_error) + if(set_last_error) pZip->m_last_error = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } - if (pZip->m_pState) + if(pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; @@ -3699,13 +3699,13 @@ static mz_bool mz_zip_reader_end_internal(mz_zip_archive *pZip, mz_bool set_last mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO - if (pState->m_pFile) + if(pState->m_pFile) { - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + if(pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { - if (MZ_FCLOSE(pState->m_pFile) == EOF) + if(MZ_FCLOSE(pState->m_pFile) == EOF) { - if (set_last_error) + if(set_last_error) pZip->m_last_error = MZ_ZIP_FILE_CLOSE_FAILED; status = MZ_FALSE; } @@ -3727,16 +3727,16 @@ mz_bool mz_zip_reader_end(mz_zip_archive *pZip) } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint flags) { - if ((!pZip) || (!pZip->m_pRead)) + if((!pZip) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (!mz_zip_reader_init_internal(pZip, flags)) + if(!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_USER; pZip->m_archive_size = size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) + if(!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; @@ -3755,13 +3755,13 @@ static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint flags) { - if (!pMem) + if(!pMem) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - if (!mz_zip_reader_init_internal(pZip, flags)) + if(!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_MEMORY; @@ -3777,7 +3777,7 @@ mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t si pZip->m_pState->m_mem_size = size; - if (!mz_zip_reader_read_central_dir(pZip, flags)) + if(!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; @@ -3794,7 +3794,7 @@ static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBu file_ofs += pZip->m_pState->m_file_archive_start_ofs; - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + if(((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); @@ -3807,18 +3807,18 @@ mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_ mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, mz_uint flags, mz_uint64 file_start_ofs, mz_uint64 archive_size) { - if ((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) + if((!pZip) || (!pFilename) || ((archive_size) && (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); - if (!pFile) + if(!pFile) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); file_size = archive_size; - if (!file_size) + if(!file_size) { - if (MZ_FSEEK64(pFile, 0, SEEK_END)) + if(MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); @@ -3829,10 +3829,10 @@ mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, /* TODO: Better sanity check archive_size and the # of actual remaining bytes */ - if (file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(file_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); - if (!mz_zip_reader_init_internal(pZip, flags)) + if(!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; @@ -3845,7 +3845,7 @@ mz_bool mz_zip_reader_init_file_v2(mz_zip_archive *pZip, const char *pFilename, pZip->m_archive_size = file_size; pZip->m_pState->m_file_archive_start_ofs = file_start_ofs; - if (!mz_zip_reader_read_central_dir(pZip, flags)) + if(!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; @@ -3858,23 +3858,23 @@ mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 { mz_uint64 cur_file_ofs; - if ((!pZip) || (!pFile)) + if((!pZip) || (!pFile)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); cur_file_ofs = MZ_FTELL64(pFile); - if (!archive_size) + if(!archive_size) { - if (MZ_FSEEK64(pFile, 0, SEEK_END)) + if(MZ_FSEEK64(pFile, 0, SEEK_END)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); archive_size = MZ_FTELL64(pFile) - cur_file_ofs; - if (archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_NOT_AN_ARCHIVE); } - if (!mz_zip_reader_init_internal(pZip, flags)) + if(!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_CFILE; @@ -3885,7 +3885,7 @@ mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 pZip->m_archive_size = archive_size; pZip->m_pState->m_file_archive_start_ofs = cur_file_ofs; - if (!mz_zip_reader_read_central_dir(pZip, flags)) + if(!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end_internal(pZip, MZ_FALSE); return MZ_FALSE; @@ -3898,7 +3898,7 @@ mz_bool mz_zip_reader_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint64 static MZ_FORCEINLINE const mz_uint8 *mz_zip_get_cdh(mz_zip_archive *pZip, mz_uint file_index) { - if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) + if((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } @@ -3907,7 +3907,7 @@ mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) + if(!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; @@ -3923,7 +3923,7 @@ mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index mz_uint method; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) + if(!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; @@ -3932,19 +3932,19 @@ mz_bool mz_zip_reader_is_file_supported(mz_zip_archive *pZip, mz_uint file_index method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); - if ((method != 0) && (method != MZ_DEFLATED)) + if((method != 0) && (method != MZ_DEFLATED)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); return MZ_FALSE; } - if (bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) + if(bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION)) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); return MZ_FALSE; } - if (bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) + if(bit_flag & MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG) { mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); return MZ_FALSE; @@ -3957,16 +3957,16 @@ mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_ind { mz_uint filename_len, attribute_mapping_id, external_attr; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) + if(!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_len) + if(filename_len) { - if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') + if(*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } @@ -3977,7 +3977,7 @@ mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_ind (void)attribute_mapping_id; external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); - if ((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) + if((external_attr & MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG) != 0) { return MZ_TRUE; } @@ -3990,10 +3990,10 @@ static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_inde mz_uint n; const mz_uint8 *p = pCentral_dir_header; - if (pFound_zip64_extra_data) + if(pFound_zip64_extra_data) *pFound_zip64_extra_data = MZ_FALSE; - if ((!p) || (!pStat)) + if((!p) || (!pStat)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Extract fields from the central directory record. */ @@ -4032,37 +4032,37 @@ static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_inde /* See if we need to read any zip64 extended information fields. */ /* Confusingly, these zip64 fields can be present even on non-zip64 archives (Debian zip on a huge files from stdin piped to stdout creates them). */ - if (MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) + if(MZ_MAX(MZ_MAX(pStat->m_comp_size, pStat->m_uncomp_size), pStat->m_local_header_ofs) == MZ_UINT32_MAX) { /* Attempt to find zip64 extended information field in the entry's extra data */ mz_uint32 extra_size_remaining = MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS); - if (extra_size_remaining) + if(extra_size_remaining) { const mz_uint8 *pExtra_data = p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); do { - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + if(extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); mz_uint32 field_id = MZ_READ_LE16(pExtra_data); mz_uint32 field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); - if ((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) + if((field_data_size + sizeof(mz_uint16) * 2) > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + if(field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { const mz_uint8 *pField_data = pExtra_data + sizeof(mz_uint16) * 2; mz_uint32 field_data_remaining = field_data_size; - if (pFound_zip64_extra_data) + if(pFound_zip64_extra_data) *pFound_zip64_extra_data = MZ_TRUE; - if (pStat->m_uncomp_size == MZ_UINT32_MAX) + if(pStat->m_uncomp_size == MZ_UINT32_MAX) { - if (field_data_remaining < sizeof(mz_uint64)) + if(field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_uncomp_size = MZ_READ_LE64(pField_data); @@ -4070,9 +4070,9 @@ static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_inde field_data_remaining -= sizeof(mz_uint64); } - if (pStat->m_comp_size == MZ_UINT32_MAX) + if(pStat->m_comp_size == MZ_UINT32_MAX) { - if (field_data_remaining < sizeof(mz_uint64)) + if(field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_comp_size = MZ_READ_LE64(pField_data); @@ -4080,9 +4080,9 @@ static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_inde field_data_remaining -= sizeof(mz_uint64); } - if (pStat->m_local_header_ofs == MZ_UINT32_MAX) + if(pStat->m_local_header_ofs == MZ_UINT32_MAX) { - if (field_data_remaining < sizeof(mz_uint64)) + if(field_data_remaining < sizeof(mz_uint64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); pStat->m_local_header_ofs = MZ_READ_LE64(pField_data); @@ -4095,7 +4095,7 @@ static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_inde pExtra_data += sizeof(mz_uint16) * 2 + field_data_size; extra_size_remaining = extra_size_remaining - sizeof(mz_uint16) * 2 - field_data_size; - } while (extra_size_remaining); + } while(extra_size_remaining); } } @@ -4105,10 +4105,10 @@ static mz_bool mz_zip_file_stat_internal(mz_zip_archive *pZip, mz_uint file_inde static MZ_FORCEINLINE mz_bool mz_zip_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; - if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) + if(flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); - for (i = 0; i < len; ++i) - if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) + for(i = 0; i < len; ++i) + if(MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } @@ -4120,9 +4120,9 @@ static MZ_FORCEINLINE int mz_zip_filename_compare(const mz_zip_array *pCentral_d mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); - while (pL < pE) + while(pL < pE) { - if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) + if((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; @@ -4139,28 +4139,28 @@ static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char const uint32_t size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); - if (pIndex) + if(pIndex) *pIndex = 0; - if (size) + if(size) { /* yes I could use uint32_t's, but then we would have to add some special case checks in the loop, argh, and */ /* honestly the major expense here on 32-bit CPU's will still be the filename compare */ mz_int64 l = 0, h = (mz_int64)size - 1; - while (l <= h) + while(l <= h) { mz_int64 m = l + ((h - l) >> 1); uint32_t file_index = pIndices[(uint32_t)m]; int comp = mz_zip_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); - if (!comp) + if(!comp) { - if (pIndex) + if(pIndex) *pIndex = file_index; return MZ_TRUE; } - else if (comp < 0) + else if(comp < 0) l = m + 1; else h = m - 1; @@ -4173,7 +4173,7 @@ static mz_bool mz_zip_locate_file_binary_search(mz_zip_archive *pZip, const char int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint32 index; - if (!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) + if(!mz_zip_reader_locate_file_v2(pZip, pName, pComment, flags, &index)) return -1; else return (int)index; @@ -4184,14 +4184,14 @@ mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, co mz_uint file_index; size_t name_len, comment_len; - if (pIndex) + if(pIndex) *pIndex = 0; - if ((!pZip) || (!pZip->m_pState) || (!pName)) + if((!pZip) || (!pZip->m_pState) || (!pName)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* See if we can use a binary search */ - if (((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && + if(((pZip->m_pState->m_init_flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0) && (pZip->m_zip_mode == MZ_ZIP_MODE_READING) && ((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) { @@ -4200,42 +4200,42 @@ mz_bool mz_zip_reader_locate_file_v2(mz_zip_archive *pZip, const char *pName, co /* Locate the entry by scanning the entire central directory */ name_len = strlen(pName); - if (name_len > MZ_UINT16_MAX) + if(name_len > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); comment_len = pComment ? strlen(pComment) : 0; - if (comment_len > MZ_UINT16_MAX) + if(comment_len > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - for (file_index = 0; file_index < pZip->m_total_files; file_index++) + for(file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; - if (filename_len < name_len) + if(filename_len < name_len) continue; - if (comment_len) + if(comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; - if ((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) + if((file_comment_len != comment_len) || (!mz_zip_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } - if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) + if((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { - if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) + if((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; - } while (--ofs >= 0); + } while(--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } - if ((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) + if((filename_len == name_len) && (mz_zip_string_equal(pName, pFilename, filename_len, flags))) { - if (pIndex) + if(pIndex) *pIndex = file_index; return MZ_TRUE; } @@ -4254,51 +4254,51 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; - if ((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) + if((!pZip) || (!pZip->m_pState) || ((buf_size) && (!pBuf)) || ((user_read_buf_size) && (!pUser_read_buf)) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + if(!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; /* A directory or zero length file */ - if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + if((file_stat.m_is_directory) || (!file_stat.m_comp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ - if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + if(file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + if((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); /* Ensure supplied output buffer is large enough. */ needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; - if (buf_size < needed_size) + if(buf_size < needed_size) return mz_zip_set_error(pZip, MZ_ZIP_BUF_TOO_SMALL); /* Read and parse the local directory entry. */ cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + if(MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + if((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + if((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { /* The file is stored or the caller has requested the compressed data. */ - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) + if((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) == 0) { - if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + if(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) return mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); } #endif @@ -4309,17 +4309,17 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file /* Decompress the file either directly from memory or from a file input buffer. */ tinfl_init(&inflator); - if (pZip->m_pState->m_pMem) + if(pZip->m_pState->m_pMem) { /* Read directly from the archive in memory. */ pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } - else if (pUser_read_buf) + else if(pUser_read_buf) { /* Use a user provided read buffer. */ - if (!user_read_buf_size) + if(!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; @@ -4330,10 +4330,10 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file { /* Temporarily allocate a read buffer. */ read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) + if(((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + if(NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); read_buf_avail = 0; @@ -4344,10 +4344,10 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file { /* The size_t cast here should be OK because we've verified that the output buffer is >= file_stat.m_uncomp_size above */ size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + if((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); @@ -4362,18 +4362,18 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; - } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); + } while(status == TINFL_STATUS_NEEDS_MORE_INPUT); - if (status == TINFL_STATUS_DONE) + if(status == TINFL_STATUS_DONE) { /* Make sure the entire file was decompressed, and check its CRC. */ - if (out_buf_ofs != file_stat.m_uncomp_size) + if(out_buf_ofs != file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); status = TINFL_STATUS_FAILED; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) + else if(mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_CRC_CHECK_FAILED); status = TINFL_STATUS_FAILED; @@ -4381,7 +4381,7 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file #endif } - if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) + if((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; @@ -4390,7 +4390,7 @@ mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file mz_bool mz_zip_reader_extract_file_to_mem_no_alloc(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + if(!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } @@ -4411,10 +4411,10 @@ void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, si const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); void *pBuf; - if (pSize) + if(pSize) *pSize = 0; - if (!p) + if(!p) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return NULL; @@ -4424,25 +4424,25 @@ void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, si uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; - if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) + if(((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) { mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); return NULL; } - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) + if(NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); return NULL; } - if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) + if(!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } - if (pSize) + if(pSize) *pSize = (size_t)alloc_size; return pBuf; } @@ -4450,9 +4450,9 @@ void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, si void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + if(!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) { - if (pSize) + if(pSize) *pSize = 0; return nullptr; } @@ -4470,38 +4470,38 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; - if ((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) + if((!pZip) || (!pZip->m_pState) || (!pCallback) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + if(!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; /* A directory or zero length file */ - if ((file_stat.m_is_directory) || (!file_stat.m_comp_size)) + if((file_stat.m_is_directory) || (!file_stat.m_comp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ - if (file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) + if(file_stat.m_bit_flag & (MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_IS_ENCRYPTED | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_USES_STRONG_ENCRYPTION | MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_COMPRESSED_PATCH_FLAG)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports decompressing stored and deflate. */ - if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + if((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); /* Read and do some minimal validation of the local directory entry (this doesn't crack the zip64 stuff, which we already have from the central dir) */ cur_file_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + if(MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); - if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) + if((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); /* Decompress the file either directly from memory or from a file input buffer. */ - if (pZip->m_pState->m_pMem) + if(pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; @@ -4510,27 +4510,27 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); - if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) + if(NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } - if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) + if((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { /* The file is stored or the caller has requested the compressed data. */ - if (pZip->m_pState->m_pMem) + if(pZip->m_pState->m_pMem) { - if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) + if(((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) + if(pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; } - else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + else if(!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); @@ -4543,10 +4543,10 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind } else { - while (comp_remaining) + while(comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); status = TINFL_STATUS_FAILED; @@ -4554,13 +4554,13 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + if(!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); } #endif - if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + if(pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; @@ -4578,7 +4578,7 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind tinfl_decompressor inflator; tinfl_init(&inflator); - if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) + if(NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); status = TINFL_STATUS_FAILED; @@ -4589,10 +4589,10 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); - if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) + if((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); - if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) + if(pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); status = TINFL_STATUS_FAILED; @@ -4608,9 +4608,9 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; - if (out_buf_size) + if(out_buf_size) { - if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) + if(pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { mz_zip_set_error(pZip, MZ_ZIP_WRITE_CALLBACK_FAILED); status = TINFL_STATUS_FAILED; @@ -4620,27 +4620,27 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); #endif - if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) + if((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); status = TINFL_STATUS_FAILED; break; } } - } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); + } while((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } - if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + if((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { /* Make sure the entire file was decompressed, and check its CRC. */ - if (out_buf_ofs != file_stat.m_uncomp_size) + if(out_buf_ofs != file_stat.m_uncomp_size) { mz_zip_set_error(pZip, MZ_ZIP_UNEXPECTED_DECOMPRESSED_SIZE); status = TINFL_STATUS_FAILED; } #ifndef MINIZ_DISABLE_ZIP_READER_CRC32_CHECKS - else if (file_crc32 != file_stat.m_crc32) + else if(file_crc32 != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_DECOMPRESSION_FAILED); status = TINFL_STATUS_FAILED; @@ -4648,10 +4648,10 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind #endif } - if (!pZip->m_pState->m_pMem) + if(!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); - if (pWrite_buf) + if(pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; @@ -4660,7 +4660,7 @@ mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_ind mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) + if(!mz_zip_reader_locate_file_v2(pZip, pFilename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); @@ -4680,28 +4680,28 @@ mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + if(!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; - if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + if((file_stat.m_is_directory) || (!file_stat.m_is_supported)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); pFile = MZ_FOPEN(pDst_filename, "wb"); - if (!pFile) + if(!pFile) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); status = mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); - if (MZ_FCLOSE(pFile) == EOF) + if(MZ_FCLOSE(pFile) == EOF) { - if (status) + if(status) mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); status = MZ_FALSE; } #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) - if (status) + if(status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif @@ -4711,7 +4711,7 @@ mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + if(!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); @@ -4721,10 +4721,10 @@ mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, { mz_zip_archive_file_stat file_stat; - if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) + if(!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; - if ((file_stat.m_is_directory) || (!file_stat.m_is_supported)) + if((file_stat.m_is_directory) || (!file_stat.m_is_supported)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); return mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_file_write_callback, pFile, flags); @@ -4733,7 +4733,7 @@ mz_bool mz_zip_reader_extract_to_cfile(mz_zip_archive *pZip, mz_uint file_index, mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pArchive_filename, MZ_FILE *pFile, mz_uint flags) { mz_uint32 file_index; - if (!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) + if(!mz_zip_reader_locate_file_v2(pZip, pArchive_filename, NULL, flags, &file_index)) return MZ_FALSE; return mz_zip_reader_extract_to_cfile(pZip, file_index, pFile, flags); @@ -4767,40 +4767,40 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f mz_zip_array file_data_array; mz_zip_array_init(&file_data_array, 1); - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + if((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (file_index > pZip->m_total_files) + if(file_index > pZip->m_total_files) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; pCentral_dir_header = mz_zip_get_cdh(pZip, file_index); - if (!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) + if(!mz_zip_file_stat_internal(pZip, file_index, pCentral_dir_header, &file_stat, &found_zip64_ext_data_in_cdir)) return MZ_FALSE; /* A directory or zero length file */ - if ((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) + if((file_stat.m_is_directory) || (!file_stat.m_uncomp_size)) return MZ_TRUE; /* Encryption and patch files are not supported. */ - if (file_stat.m_is_encrypted) + if(file_stat.m_is_encrypted) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_ENCRYPTION); /* This function only supports stored and deflate. */ - if ((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) + if((file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_METHOD); - if (!file_stat.m_is_supported) + if(!file_stat.m_is_supported) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_FEATURE); /* Read and parse the local directory entry. */ local_header_ofs = file_stat.m_local_header_ofs; - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if(pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + if(MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); local_header_filename_len = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS); @@ -4811,34 +4811,34 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f local_header_bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); has_data_descriptor = (local_header_bit_flags & 8) != 0; - if (local_header_filename_len != strlen(file_stat.m_filename)) + if(local_header_filename_len != strlen(file_stat.m_filename)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if ((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) + if((local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size) > pZip->m_archive_size) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if (!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) + if(!mz_zip_array_resize(pZip, &file_data_array, MZ_MAX(local_header_filename_len, local_header_extra_len), MZ_FALSE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - if (local_header_filename_len) + if(local_header_filename_len) { - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) + if(pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE, file_data_array.m_p, local_header_filename_len) != local_header_filename_len) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); goto handle_failure; } /* I've seen 1 archive that had the same pathname, but used backslashes in the local dir and forward slashes in the central dir. Do we care about this? For now, this case will fail validation. */ - if (memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) + if(memcmp(file_stat.m_filename, file_data_array.m_p, local_header_filename_len) != 0) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); goto handle_failure; } } - if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + if((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) { - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + if(pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); goto handle_failure; @@ -4851,21 +4851,21 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f { mz_uint32 field_id, field_data_size, field_total_size; - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + if(extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); field_total_size = field_data_size + sizeof(mz_uint16) * 2; - if (field_total_size > extra_size_remaining) + if(field_total_size > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + if(field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); - if (field_data_size < sizeof(mz_uint64) * 2) + if(field_data_size < sizeof(mz_uint64) * 2) { mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); goto handle_failure; @@ -4880,18 +4880,18 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f pExtra_data += field_total_size; extra_size_remaining -= field_total_size; - } while (extra_size_remaining); + } while(extra_size_remaining); } /* TODO: parse local header extra data when local_header_comp_size is 0xFFFFFFFF! (big_descriptor.zip) */ /* I've seen zips in the wild with the data descriptor bit set, but proper local header values and bogus data descriptors */ - if ((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) + if((has_data_descriptor) && (!local_header_comp_size) && (!local_header_crc32)) { mz_uint8 descriptor_buf[32]; mz_uint32 num_descriptor_uint32s = ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) ? 6 : 4; - if (pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) + if(pZip->m_pRead(pZip->m_pIO_opaque, local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_len + local_header_extra_len + file_stat.m_comp_size, descriptor_buf, sizeof(mz_uint32) * num_descriptor_uint32s) != (sizeof(mz_uint32) * num_descriptor_uint32s)) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); goto handle_failure; @@ -4903,7 +4903,7 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f mz_uint32 file_crc32 = MZ_READ_LE32(pSrc); mz_uint64 comp_size = 0, uncomp_size = 0; - if ((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + if((pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { comp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32)); uncomp_size = MZ_READ_LE64(pSrc + sizeof(mz_uint32) + sizeof(mz_uint64)); @@ -4914,7 +4914,7 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f uncomp_size = MZ_READ_LE32(pSrc + sizeof(mz_uint32) + sizeof(mz_uint32)); } - if ((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) + if((file_crc32 != file_stat.m_crc32) || (comp_size != file_stat.m_comp_size) || (uncomp_size != file_stat.m_uncomp_size)) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); goto handle_failure; @@ -4922,7 +4922,7 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f } else { - if ((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) + if((local_header_crc32 != file_stat.m_crc32) || (local_header_comp_size != file_stat.m_comp_size) || (local_header_uncomp_size != file_stat.m_uncomp_size)) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); goto handle_failure; @@ -4931,13 +4931,13 @@ mz_bool mz_zip_validate_file(mz_zip_archive *pZip, mz_uint file_index, mz_uint f mz_zip_array_clear(pZip, &file_data_array); - if ((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) + if((flags & MZ_ZIP_FLAG_VALIDATE_HEADERS_ONLY) == 0) { - if (!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) + if(!mz_zip_reader_extract_to_callback(pZip, file_index, mz_zip_compute_crc32_callback, &uncomp_crc32, 0)) return MZ_FALSE; /* 1 more check to be sure, although the extract checks too. */ - if (uncomp_crc32 != file_stat.m_crc32) + if(uncomp_crc32 != file_stat.m_crc32) { mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); return MZ_FALSE; @@ -4956,48 +4956,48 @@ mz_bool mz_zip_validate_archive(mz_zip_archive *pZip, mz_uint flags) mz_zip_internal_state *pState; uint32_t i; - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) + if((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; /* Basic sanity checks */ - if (!pState->m_zip64) + if(!pState->m_zip64) { - if (pZip->m_total_files > MZ_UINT16_MAX) + if(pZip->m_total_files > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (pZip->m_archive_size > MZ_UINT32_MAX) + if(pZip->m_archive_size > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); } else { - if (pZip->m_total_files >= MZ_UINT32_MAX) + if(pZip->m_total_files >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + if(pState->m_central_dir.m_size >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); } - for (i = 0; i < pZip->m_total_files; i++) + for(i = 0; i < pZip->m_total_files; i++) { - if (MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) + if(MZ_ZIP_FLAG_VALIDATE_LOCATE_FILE_FLAG & flags) { mz_uint32 found_index; mz_zip_archive_file_stat stat; - if (!mz_zip_reader_file_stat(pZip, i, &stat)) + if(!mz_zip_reader_file_stat(pZip, i, &stat)) return MZ_FALSE; - if (!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) + if(!mz_zip_reader_locate_file_v2(pZip, stat.m_filename, NULL, 0, &found_index)) return MZ_FALSE; /* This check can fail if there are duplicate filenames in the archive (which we don't check for when writing - that's up to the user) */ - if (found_index != i) + if(found_index != i) return mz_zip_set_error(pZip, MZ_ZIP_VALIDATION_FAILED); } - if (!mz_zip_validate_file(pZip, i, flags)) + if(!mz_zip_validate_file(pZip, i, flags)) return MZ_FALSE; } @@ -5010,36 +5010,36 @@ mz_bool mz_zip_validate_mem_archive(const void *pMem, size_t size, mz_uint flags mz_zip_archive zip; mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - if ((!pMem) || (!size)) + if((!pMem) || (!size)) { - if (pErr) + if(pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } mz_zip_zero_struct(&zip); - if (!mz_zip_reader_init_mem(&zip, pMem, size, flags)) + if(!mz_zip_reader_init_mem(&zip, pMem, size, flags)) { - if (pErr) + if(pErr) *pErr = zip.m_last_error; return MZ_FALSE; } - if (!mz_zip_validate_archive(&zip, flags)) + if(!mz_zip_validate_archive(&zip, flags)) { actual_err = zip.m_last_error; success = MZ_FALSE; } - if (!mz_zip_reader_end_internal(&zip, success)) + if(!mz_zip_reader_end_internal(&zip, success)) { - if (!actual_err) + if(!actual_err) actual_err = zip.m_last_error; success = MZ_FALSE; } - if (pErr) + if(pErr) *pErr = actual_err; return success; @@ -5052,36 +5052,36 @@ mz_bool mz_zip_validate_file_archive(const char *pFilename, mz_uint flags, mz_zi mz_zip_archive zip; mz_zip_error actual_err = MZ_ZIP_NO_ERROR; - if (!pFilename) + if(!pFilename) { - if (pErr) + if(pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } mz_zip_zero_struct(&zip); - if (!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) + if(!mz_zip_reader_init_file_v2(&zip, pFilename, flags, 0, 0)) { - if (pErr) + if(pErr) *pErr = zip.m_last_error; return MZ_FALSE; } - if (!mz_zip_validate_archive(&zip, flags)) + if(!mz_zip_validate_archive(&zip, flags)) { actual_err = zip.m_last_error; success = MZ_FALSE; } - if (!mz_zip_reader_end_internal(&zip, success)) + if(!mz_zip_reader_end_internal(&zip, success)) { - if (!actual_err) + if(!actual_err) actual_err = zip.m_last_error; success = MZ_FALSE; } - if (pErr) + if(pErr) *pErr = actual_err; return success; @@ -5120,25 +5120,25 @@ static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const vo mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); - if (!n) + if(!n) return 0; /* An allocation this big is likely to just fail on 32-bit systems, so don't even go there. */ - if ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) + if((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF)) { mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); return 0; } - if (new_size > pState->m_mem_capacity) + if(new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); - while (new_capacity < new_size) + while(new_capacity < new_size) new_capacity *= 2; - if (NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) + if(NULL == (pNew_block = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) { mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); return 0; @@ -5157,9 +5157,9 @@ static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; - if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) + if((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) { - if (set_last_error) + if(set_last_error) mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return MZ_FALSE; } @@ -5171,13 +5171,13 @@ static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO - if (pState->m_pFile) + if(pState->m_pFile) { - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + if(pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { - if (MZ_FCLOSE(pState->m_pFile) == EOF) + if(MZ_FCLOSE(pState->m_pFile) == EOF) { - if (set_last_error) + if(set_last_error) mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); status = MZ_FALSE; } @@ -5187,7 +5187,7 @@ static mz_bool mz_zip_writer_end_internal(mz_zip_archive *pZip, mz_bool set_last } #endif /* #ifndef MINIZ_NO_STDIO */ - if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) + if((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; @@ -5202,34 +5202,34 @@ mz_bool mz_zip_writer_init_v2(mz_zip_archive *pZip, mz_uint64 existing_size, mz_ { mz_bool zip64 = (flags & MZ_ZIP_FLAG_WRITE_ZIP64) != 0; - if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) + if((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + if(flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) { - if (!pZip->m_pRead) + if(!pZip->m_pRead) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } - if (pZip->m_file_offset_alignment) + if(pZip->m_file_offset_alignment) { /* Ensure user specified file offset alignment is a power of 2. */ - if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) + if(pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } - if (!pZip->m_pAlloc) + if(!pZip->m_pAlloc) pZip->m_pAlloc = miniz_def_alloc_func; - if (!pZip->m_pFree) + if(!pZip->m_pFree) pZip->m_pFree = miniz_def_free_func; - if (!pZip->m_pRealloc) + if(!pZip->m_pRealloc) pZip->m_pRealloc = miniz_def_realloc_func; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; - if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) + if(NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); @@ -5256,19 +5256,19 @@ mz_bool mz_zip_writer_init_heap_v2(mz_zip_archive *pZip, size_t size_to_reserve_ { pZip->m_pWrite = mz_zip_heap_write_func; - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + if(flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; - if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + if(!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) return MZ_FALSE; pZip->m_zip_type = MZ_ZIP_TYPE_HEAP; - if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) + if(0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { - if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) + if(NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end_internal(pZip, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); @@ -5292,7 +5292,7 @@ static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const vo file_ofs += pZip->m_pState->m_file_archive_start_ofs; - if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) + if(((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) { mz_zip_set_error(pZip, MZ_ZIP_FILE_SEEK_FAILED); return 0; @@ -5312,15 +5312,15 @@ mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, pZip->m_pWrite = mz_zip_file_write_func; - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + if(flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; - if (!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) + if(!mz_zip_writer_init_v2(pZip, size_to_reserve_at_beginning, flags)) return MZ_FALSE; - if (NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) + if(NULL == (pFile = MZ_FOPEN(pFilename, (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) ? "w+b" : "wb"))) { mz_zip_writer_end(pZip); return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); @@ -5329,7 +5329,7 @@ mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, pZip->m_pState->m_pFile = pFile; pZip->m_zip_type = MZ_ZIP_TYPE_FILE; - if (size_to_reserve_at_beginning) + if(size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; @@ -5339,14 +5339,14 @@ mz_bool mz_zip_writer_init_file_v2(mz_zip_archive *pZip, const char *pFilename, do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_ofs += n; size_to_reserve_at_beginning -= n; - } while (size_to_reserve_at_beginning); + } while(size_to_reserve_at_beginning); } return MZ_TRUE; @@ -5356,12 +5356,12 @@ mz_bool mz_zip_writer_init_cfile(mz_zip_archive *pZip, MZ_FILE *pFile, mz_uint f { pZip->m_pWrite = mz_zip_file_write_func; - if (flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) + if(flags & MZ_ZIP_FLAG_WRITE_ALLOW_READING) pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; - if (!mz_zip_writer_init_v2(pZip, 0, flags)) + if(!mz_zip_writer_init_v2(pZip, 0, flags)) return MZ_FALSE; pZip->m_pState->m_pFile = pFile; @@ -5376,49 +5376,49 @@ mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFil { mz_zip_internal_state *pState; - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) + if((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (flags & MZ_ZIP_FLAG_WRITE_ZIP64) + if(flags & MZ_ZIP_FLAG_WRITE_ZIP64) { /* We don't support converting a non-zip64 file to zip64 - this seems like more trouble than it's worth. (What about the existing 32-bit data descriptors that could follow the compressed data?) */ - if (!pZip->m_pState->m_zip64) + if(!pZip->m_pState->m_zip64) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } /* No sense in trying to write to an archive that's already at the support max size */ - if (pZip->m_pState->m_zip64) + if(pZip->m_pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT32_MAX) + if(pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { - if (pZip->m_total_files == MZ_UINT16_MAX) + if(pZip->m_total_files == MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); - if ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) + if((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); } pState = pZip->m_pState; - if (pState->m_pFile) + if(pState->m_pFile) { #ifdef MINIZ_NO_STDIO (void)pFilename; return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); #else - if (pZip->m_pIO_opaque != pZip) + if(pZip->m_pIO_opaque != pZip) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (pZip->m_zip_type == MZ_ZIP_TYPE_FILE) + if(pZip->m_zip_type == MZ_ZIP_TYPE_FILE) { - if (!pFilename) + if(!pFilename) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Archive is being read from stdio and was originally opened only for reading. Try to reopen as writable. */ - if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) + if(NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { /* The mz_zip_archive is now in a bogus state because pState->m_pFile is NULL, so just close it. */ mz_zip_reader_end_internal(pZip, MZ_FALSE); @@ -5429,17 +5429,17 @@ mz_bool mz_zip_writer_init_from_reader_v2(mz_zip_archive *pZip, const char *pFil pZip->m_pWrite = mz_zip_file_write_func; #endif /* #ifdef MINIZ_NO_STDIO */ } - else if (pState->m_pMem) + else if(pState->m_pMem) { /* Archive lives in a memory block. Assume it's from the heap that we can resize using the realloc callback. */ - if (pZip->m_pIO_opaque != pZip) + if(pZip->m_pIO_opaque != pZip) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } /* Archive is being read via a user provided read function - make sure the user has specified a write function too. */ - else if (!pZip->m_pWrite) + else if(!pZip->m_pWrite) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Start writing new files at the archive's current central directory location. */ @@ -5478,7 +5478,7 @@ typedef struct static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; - if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) + if((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; @@ -5498,21 +5498,21 @@ static mz_uint32 mz_zip_writer_create_zip64_extra_data(mz_uint8 *pBuf, mz_uint64 mz_uint32 field_size = 0; - if (pUncomp_size) + if(pUncomp_size) { MZ_WRITE_LE64(pDst, *pUncomp_size); pDst += sizeof(mz_uint64); field_size += sizeof(mz_uint64); } - if (pComp_size) + if(pComp_size) { MZ_WRITE_LE64(pDst, *pComp_size); pDst += sizeof(mz_uint64); field_size += sizeof(mz_uint64); } - if (pLocal_header_ofs) + if(pLocal_header_ofs) { MZ_WRITE_LE64(pDst, *pLocal_header_ofs); pDst += sizeof(mz_uint64); @@ -5579,20 +5579,20 @@ static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; - if (!pZip->m_pState->m_zip64) + if(!pZip->m_pState->m_zip64) { - if (local_header_ofs > 0xFFFFFFFF) + if(local_header_ofs > 0xFFFFFFFF) return mz_zip_set_error(pZip, MZ_ZIP_FILE_TOO_LARGE); } /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) + if(((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + user_extra_data_len + comment_size) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - if (!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size + user_extra_data_len, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) + if(!mz_zip_writer_create_central_dir_header(pZip, central_dir_header, filename_size, extra_size + user_extra_data_len, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || + if((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, user_extra_data, user_extra_data_len)) || @@ -5610,12 +5610,12 @@ static mz_bool mz_zip_writer_add_to_central_dir(mz_zip_archive *pZip, const char static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { /* Basic ZIP archive filename validity checks: Valid filenames cannot start with a forward slash, cannot contain a drive letter, and cannot use DOS-style backward slashes. */ - if (*pArchive_name == '/') + if(*pArchive_name == '/') return MZ_FALSE; - while (*pArchive_name) + while(*pArchive_name) { - if ((*pArchive_name == '\\') || (*pArchive_name == ':')) + if((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; @@ -5627,7 +5627,7 @@ static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment(mz_zip_archive *pZip) { mz_uint32 n; - if (!pZip->m_file_offset_alignment) + if(!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (mz_uint)((pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1)); @@ -5637,10 +5637,10 @@ static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_fil { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); - while (n) + while(n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_file_ofs += s; @@ -5672,48 +5672,48 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; mz_uint16 bit_flags = 0; - if (uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) + if(uncomp_size || (buf_size && !(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) bit_flags |= MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR; - if (level_and_flags & MZ_ZIP_FLAG_UTF8_FILENAME) + if(level_and_flags & MZ_ZIP_FLAG_UTF8_FILENAME) bit_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; - if ((int)level_and_flags < 0) + if((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + if((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; - if (pState->m_zip64) + if(pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT32_MAX) + if(pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { - if (pZip->m_total_files == MZ_UINT16_MAX) + if(pZip->m_total_files == MZ_UINT16_MAX) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ } - if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) + if((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ } } - if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) + if((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (!mz_zip_writer_validate_archive_name(pArchive_name)) + if(!mz_zip_writer_validate_archive_name(pArchive_name)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - if (last_modified != NULL) + if(last_modified != NULL) { mz_zip_time_t_to_dos_time(*last_modified, &dos_time, &dos_date); } @@ -5729,53 +5729,53 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n } archive_name_size = strlen(pArchive_name); - if (archive_name_size > MZ_UINT16_MAX) + if(archive_name_size > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + if(((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - if (!pState->m_zip64) + if(!pState->m_zip64) { /* Bail early if the archive would obviously become too large */ - if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF) + if((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ } } - if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) + if((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { /* Set DOS Subdirectory attribute bit. */ ext_attributes |= MZ_ZIP_DOS_DIR_ATTRIBUTE_BITFLAG; /* Subdirectories cannot contain data. */ - if ((buf_size) || (uncomp_size)) + if((buf_size) || (uncomp_size)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); } /* Try to do any allocations before writing to the archive, so if an allocation fails the file remains unmodified. (A good idea if we're doing an in-place modification.) */ - if ((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) + if((!mz_zip_array_ensure_room(pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + (pState->m_zip64 ? MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE : 0))) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - if ((!store_data_uncompressed) && (buf_size)) + if((!store_data_uncompressed) && (buf_size)) { - if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) + if(NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + if(!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; - if (pZip->m_file_offset_alignment) + if(pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } @@ -5783,38 +5783,38 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n MZ_CLEAR_OBJ(local_dir_header); - if (!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + if(!store_data_uncompressed || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { method = MZ_DEFLATED; } - if (pState->m_zip64) + if(pState->m_zip64) { - if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + if(uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { pExtra_data = extra_data; extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + if(!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + if(pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += archive_name_size; - if (pExtra_data != NULL) + if(pExtra_data != NULL) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += extra_size; @@ -5822,17 +5822,17 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n } else { - if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + if((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) + if(!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, bit_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + if(pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); @@ -5840,28 +5840,28 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n cur_archive_file_ofs += archive_name_size; } - if (user_extra_data_len > 0) + if(user_extra_data_len > 0) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += user_extra_data_len; } - if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) + if(!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; - if (uncomp_size <= 3) + if(uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } - if (store_data_uncompressed) + if(store_data_uncompressed) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); @@ -5870,7 +5870,7 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n cur_archive_file_ofs += buf_size; comp_size = buf_size; } - else if (buf_size) + else if(buf_size) { mz_zip_writer_add_state state; @@ -5878,7 +5878,7 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; - if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || + if((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); @@ -5892,7 +5892,7 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; - if (uncomp_size) + if(uncomp_size) { MZ_ASSERT(bit_flags & MZ_ZIP_LDH_BIT_FLAG_HAS_LOCATOR); @@ -5901,9 +5901,9 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); - if (pExtra_data == NULL) + if(pExtra_data == NULL) { - if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + if((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); MZ_WRITE_LE32(local_dir_footer + 8, comp_size); @@ -5916,19 +5916,19 @@ mz_bool mz_zip_writer_add_mem_ex_v2(mz_zip_archive *pZip, const char *pArchive_n local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; } - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) return MZ_FALSE; cur_archive_file_ofs += local_dir_footer_size; } - if (pExtra_data != NULL) + if(pExtra_data != NULL) { extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, + if(!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, user_extra_data_central, user_extra_data_central_len)) return MZ_FALSE; @@ -5954,20 +5954,20 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, mz_uint8 extra_data[MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE]; mz_zip_internal_state *pState; - if (level_and_flags & MZ_ZIP_FLAG_UTF8_FILENAME) + if(level_and_flags & MZ_ZIP_FLAG_UTF8_FILENAME) gen_flags |= MZ_ZIP_GENERAL_PURPOSE_BIT_FLAG_UTF8; - if ((int)level_and_flags < 0) + if((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; /* Sanity checks */ - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) + if((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; - if ((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX)) + if((!pState->m_zip64) && (uncomp_size > MZ_UINT32_MAX)) { /* Source file is too large for non-zip64 */ /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ @@ -5975,20 +5975,20 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, } /* We could support this, but why? */ - if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) + if(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (!mz_zip_writer_validate_archive_name(pArchive_name)) + if(!mz_zip_writer_validate_archive_name(pArchive_name)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); - if (pState->m_zip64) + if(pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT32_MAX) + if(pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { - if (pZip->m_total_files == MZ_UINT16_MAX) + if(pZip->m_total_files == MZ_UINT16_MAX) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); */ @@ -5996,19 +5996,19 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, } archive_name_size = strlen(pArchive_name); - if (archive_name_size > MZ_UINT16_MAX) + if(archive_name_size > MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_FILENAME); num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); /* miniz doesn't support central dirs >= MZ_UINT32_MAX bytes yet */ - if (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) + if(((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP64_MAX_CENTRAL_EXTRA_FIELD_SIZE + comment_size) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); - if (!pState->m_zip64) + if(!pState->m_zip64) { /* Bail early if the archive would obviously become too large */ - if ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024) > 0xFFFFFFFF) + if((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + archive_name_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 1024) > 0xFFFFFFFF) { pState->m_zip64 = MZ_TRUE; /*return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); */ @@ -6016,16 +6016,16 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, } #ifndef MINIZ_NO_TIME - if (pFile_time) + if(pFile_time) { mz_zip_time_t_to_dos_time(*pFile_time, &dos_time, &dos_date); } #endif - if (uncomp_size <= 3) + if(uncomp_size <= 3) level = 0; - if (!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) + if(!mz_zip_writer_write_zeros(pZip, cur_archive_file_ofs, num_alignment_padding_bytes)) { return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } @@ -6033,59 +6033,59 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, cur_archive_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_archive_file_ofs; - if (pZip->m_file_offset_alignment) + if(pZip->m_file_offset_alignment) { MZ_ASSERT((cur_archive_file_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } - if (uncomp_size && level) + if(uncomp_size && level) { method = MZ_DEFLATED; } MZ_CLEAR_OBJ(local_dir_header); - if (pState->m_zip64) + if(pState->m_zip64) { - if (uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) + if(uncomp_size >= MZ_UINT32_MAX || local_dir_header_ofs >= MZ_UINT32_MAX) { pExtra_data = extra_data; extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + if(!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, extra_size + user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } cur_archive_file_ofs += archive_name_size; - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, extra_data, extra_size) != extra_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += extra_size; } else { - if ((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) + if((comp_size > MZ_UINT32_MAX) || (cur_archive_file_ofs > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) + if(!mz_zip_writer_create_local_dir_header(pZip, local_dir_header, (mz_uint16)archive_name_size, user_extra_data_len, 0, 0, 0, method, gen_flags, dos_time, dos_date)) return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += sizeof(local_dir_header); - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); } @@ -6093,29 +6093,29 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, cur_archive_file_ofs += archive_name_size; } - if (user_extra_data_len > 0) + if(user_extra_data_len > 0) { - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, user_extra_data, user_extra_data_len) != user_extra_data_len) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_archive_file_ofs += user_extra_data_len; } - if (uncomp_size) + if(uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); - if (!pRead_buf) + if(!pRead_buf) { return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if (!level) + if(!level) { - while (uncomp_remaining) + while(uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); - if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) + if((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); @@ -6131,7 +6131,7 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); - if (!pComp) + if(!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); @@ -6141,19 +6141,19 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; - if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) + if(tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params(level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return mz_zip_set_error(pZip, MZ_ZIP_INTERNAL_ERROR); } - for (;;) + for(;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; - if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) + if(MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) { mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); break; @@ -6163,12 +6163,12 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer(pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); - if (status == TDEFL_STATUS_DONE) + if(status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } - else if (status != TDEFL_STATUS_OKAY) + else if(status != TDEFL_STATUS_OKAY) { mz_zip_set_error(pZip, MZ_ZIP_COMPRESSION_FAILED); break; @@ -6177,7 +6177,7 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); - if (!result) + if(!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return MZ_FALSE; @@ -6195,9 +6195,9 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, MZ_WRITE_LE32(local_dir_footer + 0, MZ_ZIP_DATA_DESCRIPTOR_ID); MZ_WRITE_LE32(local_dir_footer + 4, uncomp_crc32); - if (pExtra_data == NULL) + if(pExtra_data == NULL) { - if (comp_size > MZ_UINT32_MAX) + if(comp_size > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); MZ_WRITE_LE32(local_dir_footer + 8, comp_size); @@ -6210,18 +6210,18 @@ mz_bool mz_zip_writer_add_cfile(mz_zip_archive *pZip, const char *pArchive_name, local_dir_footer_size = MZ_ZIP_DATA_DESCRIPTER_SIZE64; } - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, local_dir_footer, local_dir_footer_size) != local_dir_footer_size) return MZ_FALSE; cur_archive_file_ofs += local_dir_footer_size; - if (pExtra_data != NULL) + if(pExtra_data != NULL) { extra_size = mz_zip_writer_create_zip64_extra_data(extra_data, (uncomp_size >= MZ_UINT32_MAX) ? &uncomp_size : NULL, (uncomp_size >= MZ_UINT32_MAX) ? &comp_size : NULL, (local_dir_header_ofs >= MZ_UINT32_MAX) ? &local_dir_header_ofs : NULL); } - if (!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, comment_size, + if(!mz_zip_writer_add_to_central_dir(pZip, pArchive_name, (mz_uint16)archive_name_size, pExtra_data, extra_size, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, gen_flags, dos_time, dos_date, local_dir_header_ofs, ext_attributes, user_extra_data_central, user_extra_data_central_len)) return MZ_FALSE; @@ -6243,12 +6243,12 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_STDIO) pFile_time = &file_modified_time; - if (!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) + if(!mz_zip_get_file_modified_time(pSrc_filename, &file_modified_time)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_STAT_FAILED); #endif pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); - if (!pSrc_file) + if(!pSrc_file) return mz_zip_set_error(pZip, MZ_ZIP_FILE_OPEN_FAILED); MZ_FSEEK64(pSrc_file, 0, SEEK_END); @@ -6266,12 +6266,12 @@ mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext, mz_zip_archive *pZip, const mz_uint8 *pExt, uint32_t ext_len, mz_uint64 *pComp_size, mz_uint64 *pUncomp_size, mz_uint64 *pLocal_header_ofs, mz_uint32 *pDisk_start) { /* + 64 should be enough for any new zip64 data */ - if (!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) + if(!mz_zip_array_reserve(pZip, pNew_ext, ext_len + 64, MZ_FALSE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); mz_zip_array_resize(pZip, pNew_ext, 0, MZ_FALSE); - if ((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) + if((pUncomp_size) || (pComp_size) || (pLocal_header_ofs) || (pDisk_start)) { mz_uint8 new_ext_block[64]; mz_uint8 *pDst = new_ext_block; @@ -6279,25 +6279,25 @@ static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext mz_write_le16(pDst + sizeof(mz_uint16), 0); pDst += sizeof(mz_uint16) * 2; - if (pUncomp_size) + if(pUncomp_size) { mz_write_le64(pDst, *pUncomp_size); pDst += sizeof(mz_uint64); } - if (pComp_size) + if(pComp_size) { mz_write_le64(pDst, *pComp_size); pDst += sizeof(mz_uint64); } - if (pLocal_header_ofs) + if(pLocal_header_ofs) { mz_write_le64(pDst, *pLocal_header_ofs); pDst += sizeof(mz_uint64); } - if (pDisk_start) + if(pDisk_start) { mz_write_le32(pDst, *pDisk_start); pDst += sizeof(mz_uint32); @@ -6305,11 +6305,11 @@ static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext mz_write_le16(new_ext_block + sizeof(mz_uint16), (mz_uint16)((pDst - new_ext_block) - sizeof(mz_uint16) * 2)); - if (!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) + if(!mz_zip_array_push_back(pZip, pNew_ext, new_ext_block, pDst - new_ext_block)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if ((pExt) && (ext_len)) + if((pExt) && (ext_len)) { mz_uint32 extra_size_remaining = ext_len; const mz_uint8 *pExtra_data = pExt; @@ -6318,25 +6318,25 @@ static mz_bool mz_zip_writer_update_zip64_extension_block(mz_zip_array *pNew_ext { mz_uint32 field_id, field_data_size, field_total_size; - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + if(extra_size_remaining < (sizeof(mz_uint16) * 2)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); field_id = MZ_READ_LE16(pExtra_data); field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); field_total_size = field_data_size + sizeof(mz_uint16) * 2; - if (field_total_size > extra_size_remaining) + if(field_total_size > extra_size_remaining) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); - if (field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + if(field_id != MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { - if (!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) + if(!mz_zip_array_push_back(pZip, pNew_ext, pExtra_data, field_total_size)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } pExtra_data += field_total_size; extra_size_remaining -= field_total_size; - } while (extra_size_remaining); + } while(extra_size_remaining); } return MZ_TRUE; @@ -6362,20 +6362,20 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * mz_bool found_zip64_ext_data_in_ldir = MZ_FALSE; /* Sanity checks */ - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) + if((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pSource_zip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; /* Don't support copying files from zip64 archives to non-zip64, even though in some cases this is possible */ - if ((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) + if((pSource_zip->m_pState->m_zip64) && (!pZip->m_pState->m_zip64)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); /* Get pointer to the source central dir header and crack it */ - if (NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) + if(NULL == (pSrc_central_header = mz_zip_get_cdh(pSource_zip, src_file_index))) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) + if(MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_SIG_OFS) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); src_filename_len = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS); @@ -6384,34 +6384,34 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * src_central_dir_following_data_size = src_filename_len + src_ext_len + src_comment_len; /* TODO: We don't support central dir's >= MZ_UINT32_MAX bytes right now (+32 fudge factor in case we need to add more extra data) */ - if ((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) + if((pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + 32) >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_UNSUPPORTED_CDIR_SIZE); num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); - if (!pState->m_zip64) + if(!pState->m_zip64) { - if (pZip->m_total_files == MZ_UINT16_MAX) + if(pZip->m_total_files == MZ_UINT16_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { /* TODO: Our zip64 support still has some 32-bit limits that may not be worth fixing. */ - if (pZip->m_total_files == MZ_UINT32_MAX) + if(pZip->m_total_files == MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } - if (!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) + if(!mz_zip_file_stat_internal(pSource_zip, src_file_index, pSrc_central_header, &src_file_stat, NULL)) return MZ_FALSE; cur_src_file_ofs = src_file_stat.m_local_header_ofs; cur_dst_file_ofs = pZip->m_archive_size; /* Read the source archive's local dir header */ - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if(pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); - if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) + if(MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; @@ -6424,16 +6424,16 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * src_archive_bytes_remaining = local_header_filename_size + local_header_extra_len + src_file_stat.m_comp_size; /* Try to find a zip64 extended information field */ - if ((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) + if((local_header_extra_len) && ((local_header_comp_size == MZ_UINT32_MAX) || (local_header_uncomp_size == MZ_UINT32_MAX))) { mz_zip_array file_data_array; mz_zip_array_init(&file_data_array, 1); - if (!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) + if(!mz_zip_array_resize(pZip, &file_data_array, local_header_extra_len, MZ_FALSE)) { return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) + if(pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, src_file_stat.m_local_header_ofs + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + local_header_filename_size, file_data_array.m_p, local_header_extra_len) != local_header_extra_len) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); @@ -6446,7 +6446,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * { mz_uint32 field_id, field_data_size, field_total_size; - if (extra_size_remaining < (sizeof(mz_uint16) * 2)) + if(extra_size_remaining < (sizeof(mz_uint16) * 2)) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); @@ -6456,17 +6456,17 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * field_data_size = MZ_READ_LE16(pExtra_data + sizeof(mz_uint16)); field_total_size = field_data_size + sizeof(mz_uint16) * 2; - if (field_total_size > extra_size_remaining) + if(field_total_size > extra_size_remaining) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); } - if (field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) + if(field_id == MZ_ZIP64_EXTENDED_INFORMATION_FIELD_HEADER_ID) { const mz_uint8 *pSrc_field_data = pExtra_data + sizeof(mz_uint32); - if (field_data_size < sizeof(mz_uint64) * 2) + if(field_data_size < sizeof(mz_uint64) * 2) { mz_zip_array_clear(pZip, &file_data_array); return mz_zip_set_error(pZip, MZ_ZIP_INVALID_HEADER_OR_CORRUPTED); @@ -6481,55 +6481,55 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * pExtra_data += field_total_size; extra_size_remaining -= field_total_size; - } while (extra_size_remaining); + } while(extra_size_remaining); mz_zip_array_clear(pZip, &file_data_array); } - if (!pState->m_zip64) + if(!pState->m_zip64) { /* Try to detect if the new archive will most likely wind up too big and bail early (+(sizeof(mz_uint32) * 4) is for the optional descriptor which could be present, +64 is a fudge factor). */ /* We also check when the archive is finalized so this doesn't need to be perfect. */ mz_uint64 approx_new_archive_size = cur_dst_file_ofs + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + src_archive_bytes_remaining + (sizeof(mz_uint32) * 4) + pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_central_dir_following_data_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE + 64; - if (approx_new_archive_size >= MZ_UINT32_MAX) + if(approx_new_archive_size >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); } /* Write dest archive padding */ - if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) + if(!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; - if (pZip->m_file_offset_alignment) + if(pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } /* The original zip's local header+ext block doesn't change, even with zip64, so we can just copy it over to the dest zip */ - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; /* Copy over the source archive bytes to the dest archive, also ensure we have enough buf space to handle optional data descriptor */ - if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) + if(NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(32U, MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining))))) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - while (src_archive_bytes_remaining) + while(src_archive_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint64)MZ_ZIP_MAX_IO_BUF_SIZE, src_archive_bytes_remaining); - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) + if(pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); } cur_src_file_ofs += n; - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); @@ -6541,19 +6541,19 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * /* Now deal with the optional data descriptor */ bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); - if (bit_flags & 8) + if(bit_flags & 8) { /* Copy data descriptor */ - if ((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) + if((pSource_zip->m_pState->m_zip64) || (found_zip64_ext_data_in_ldir)) { /* src is zip64, dest must be zip64 */ - /* name uint32_t's */ - /* id 1 (optional in zip64?) */ - /* crc 1 */ - /* comp_size 2 */ + /* name uint32_t's */ + /* id 1 (optional in zip64?) */ + /* crc 1 */ + /* comp_size 2 */ /* uncomp_size 2 */ - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) + if(pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, (sizeof(mz_uint32) * 6)) != (sizeof(mz_uint32) * 6)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); @@ -6566,7 +6566,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * /* src is NOT zip64 */ mz_bool has_id; - if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) + if(pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_READ_FAILED); @@ -6574,7 +6574,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * has_id = (MZ_READ_LE32(pBuf) == MZ_ZIP_DATA_DESCRIPTOR_ID); - if (pZip->m_pState->m_zip64) + if(pZip->m_pState->m_zip64) { /* dest is zip64, so upgrade the data descriptor */ const mz_uint32 *pSrc_descriptor = (const mz_uint32 *)((const mz_uint8 *)pBuf + (has_id ? sizeof(mz_uint32) : 0)); @@ -6596,7 +6596,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * } } - if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) + if(pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); @@ -6612,7 +6612,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * memcpy(new_central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); - if (pState->m_zip64) + if(pState->m_zip64) { /* This is the painful part: We need to write a new central dir header + ext block with updated zip64 fields, and ensure the old fields (if any) are not included. */ const mz_uint8 *pSrc_ext = pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len; @@ -6624,7 +6624,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, MZ_UINT32_MAX); MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, MZ_UINT32_MAX); - if (!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) + if(!mz_zip_writer_update_zip64_extension_block(&new_ext_block, pZip, pSrc_ext, src_ext_len, &src_file_stat.m_comp_size, &src_file_stat.m_uncomp_size, &local_dir_header_ofs, NULL)) { mz_zip_array_clear(pZip, &new_ext_block); return MZ_FALSE; @@ -6632,27 +6632,27 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * MZ_WRITE_LE16(new_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS, new_ext_block.m_size); - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + if(!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) { mz_zip_array_clear(pZip, &new_ext_block); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) + if(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_filename_len)) { mz_zip_array_clear(pZip, &new_ext_block); mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) + if(!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_ext_block.m_p, new_ext_block.m_size)) { mz_zip_array_clear(pZip, &new_ext_block); mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); } - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) + if(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + src_filename_len + src_ext_len, src_comment_len)) { mz_zip_array_clear(pZip, &new_ext_block); mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); @@ -6664,18 +6664,18 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * else { /* sanity checks */ - if (cur_dst_file_ofs > MZ_UINT32_MAX) + if(cur_dst_file_ofs > MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); - if (local_dir_header_ofs >= MZ_UINT32_MAX) + if(local_dir_header_ofs >= MZ_UINT32_MAX) return mz_zip_set_error(pZip, MZ_ZIP_ARCHIVE_TOO_LARGE); MZ_WRITE_LE32(new_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) + if(!mz_zip_array_push_back(pZip, &pState->m_central_dir, new_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) + if(!mz_zip_array_push_back(pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, src_central_dir_following_data_size)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); @@ -6683,7 +6683,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * } /* This shouldn't trigger unless we screwed up during the initial sanity checks */ - if (pState->m_central_dir.m_size >= MZ_UINT32_MAX) + if(pState->m_central_dir.m_size >= MZ_UINT32_MAX) { /* TODO: Support central dirs >= 32-bits in size */ mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); @@ -6691,7 +6691,7 @@ mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive * } n = (mz_uint32)orig_central_dir_size; - if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) + if(!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return mz_zip_set_error(pZip, MZ_ZIP_ALLOC_FAILED); @@ -6709,37 +6709,37 @@ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[256]; - if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) + if((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); pState = pZip->m_pState; - if (pState->m_zip64) + if(pState->m_zip64) { - if ((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) + if((pZip->m_total_files > MZ_UINT32_MAX) || (pState->m_central_dir.m_size >= MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } else { - if ((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) + if((pZip->m_total_files > MZ_UINT16_MAX) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > MZ_UINT32_MAX)) return mz_zip_set_error(pZip, MZ_ZIP_TOO_MANY_FILES); } central_dir_ofs = 0; central_dir_size = 0; - if (pZip->m_total_files) + if(pZip->m_total_files) { /* Write central directory */ central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; - if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) + if(pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); pZip->m_archive_size += central_dir_size; } - if (pState->m_zip64) + if(pState->m_zip64) { /* Write zip64 end of central directory header */ mz_uint64 rel_ofs_to_zip64_ecdr = pZip->m_archive_size; @@ -6753,7 +6753,7 @@ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDH_CDIR_OFS_OFS, central_dir_ofs); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_HEADER_SIZE; @@ -6763,7 +6763,7 @@ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_SIG_OFS, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIG); MZ_WRITE_LE64(hdr + MZ_ZIP64_ECDL_REL_OFS_TO_ZIP64_ECDR_OFS, rel_ofs_to_zip64_ecdr); MZ_WRITE_LE32(hdr + MZ_ZIP64_ECDL_TOTAL_NUMBER_OF_DISKS_OFS, 1); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) + if(pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) != MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); pZip->m_archive_size += MZ_ZIP64_END_OF_CENTRAL_DIR_LOCATOR_SIZE; @@ -6777,11 +6777,11 @@ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_size)); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, MZ_MIN(MZ_UINT32_MAX, central_dir_ofs)); - if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) + if(pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return mz_zip_set_error(pZip, MZ_ZIP_FILE_WRITE_FAILED); #ifndef MINIZ_NO_STDIO - if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) + if((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return mz_zip_set_error(pZip, MZ_ZIP_FILE_CLOSE_FAILED); #endif /* #ifndef MINIZ_NO_STDIO */ @@ -6793,19 +6793,19 @@ mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **ppBuf, size_t *pSize) { - if ((!ppBuf) || (!pSize)) + if((!ppBuf) || (!pSize)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); *ppBuf = NULL; *pSize = 0; - if ((!pZip) || (!pZip->m_pState)) + if((!pZip) || (!pZip->m_pState)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (pZip->m_pWrite != mz_zip_heap_write_func) + if(pZip->m_pWrite != mz_zip_heap_write_func) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); - if (!mz_zip_writer_finalize_archive(pZip)) + if(!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *ppBuf = pZip->m_pState->m_pMem; @@ -6835,31 +6835,31 @@ mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, co mz_zip_error actual_err = MZ_ZIP_NO_ERROR; mz_zip_zero_struct(&zip_archive); - if ((int)level_and_flags < 0) + if((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; - if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) + if((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) { - if (pErr) + if(pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return MZ_FALSE; } - if (!mz_zip_writer_validate_archive_name(pArchive_name)) + if(!mz_zip_writer_validate_archive_name(pArchive_name)) { - if (pErr) + if(pErr) *pErr = MZ_ZIP_INVALID_FILENAME; return MZ_FALSE; } /* Important: The regular non-64 bit version of stat() can fail here if the file is very large, which could cause the archive to be overwritten. */ /* So be sure to compile with _LARGEFILE64_SOURCE 1 */ - if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) + if(MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { /* Create a new archive. */ - if (!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) + if(!mz_zip_writer_init_file_v2(&zip_archive, pZip_filename, 0, level_and_flags)) { - if (pErr) + if(pErr) *pErr = zip_archive.m_last_error; return MZ_FALSE; } @@ -6869,16 +6869,16 @@ mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, co else { /* Append to an existing archive. */ - if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + if(!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { - if (pErr) + if(pErr) *pErr = zip_archive.m_last_error; return MZ_FALSE; } - if (!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) + if(!mz_zip_writer_init_from_reader_v2(&zip_archive, pZip_filename, level_and_flags)) { - if (pErr) + if(pErr) *pErr = zip_archive.m_last_error; mz_zip_reader_end_internal(&zip_archive, MZ_FALSE); @@ -6891,30 +6891,30 @@ mz_bool mz_zip_add_mem_to_archive_file_in_place_v2(const char *pZip_filename, co actual_err = zip_archive.m_last_error; /* Always finalize, even if adding failed for some reason, so we have a valid central directory. (This may not always succeed, but we can try.) */ - if (!mz_zip_writer_finalize_archive(&zip_archive)) + if(!mz_zip_writer_finalize_archive(&zip_archive)) { - if (!actual_err) + if(!actual_err) actual_err = zip_archive.m_last_error; status = MZ_FALSE; } - if (!mz_zip_writer_end_internal(&zip_archive, status)) + if(!mz_zip_writer_end_internal(&zip_archive, status)) { - if (!actual_err) + if(!actual_err) actual_err = zip_archive.m_last_error; status = MZ_FALSE; } - if ((!status) && (created_new_archive)) + if((!status) && (created_new_archive)) { /* It's a new archive and something went wrong, so just delete it. */ int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } - if (pErr) + if(pErr) *pErr = actual_err; return status; @@ -6926,34 +6926,34 @@ void *mz_zip_extract_archive_file_to_heap_v2(const char *pZip_filename, const ch mz_zip_archive zip_archive; void *p = NULL; - if (pSize) + if(pSize) *pSize = 0; - if ((!pZip_filename) || (!pArchive_name)) + if((!pZip_filename) || (!pArchive_name)) { - if (pErr) + if(pErr) *pErr = MZ_ZIP_INVALID_PARAMETER; return NULL; } mz_zip_zero_struct(&zip_archive); - if (!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) + if(!mz_zip_reader_init_file_v2(&zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY, 0, 0)) { - if (pErr) + if(pErr) *pErr = zip_archive.m_last_error; return NULL; } - if (mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) + if(mz_zip_reader_locate_file_v2(&zip_archive, pArchive_name, pComment, flags, &file_index)) { p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); } mz_zip_reader_end_internal(&zip_archive, p != NULL); - if (pErr) + if(pErr) *pErr = zip_archive.m_last_error; return p; @@ -6984,7 +6984,7 @@ mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) { mz_zip_error prev_err; - if (!pZip) + if(!pZip) return MZ_ZIP_INVALID_PARAMETER; prev_err = pZip->m_last_error; @@ -6995,7 +6995,7 @@ mz_zip_error mz_zip_set_last_error(mz_zip_archive *pZip, mz_zip_error err_num) mz_zip_error mz_zip_peek_last_error(mz_zip_archive *pZip) { - if (!pZip) + if(!pZip) return MZ_ZIP_INVALID_PARAMETER; return pZip->m_last_error; @@ -7010,7 +7010,7 @@ mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) { mz_zip_error prev_err; - if (!pZip) + if(!pZip) return MZ_ZIP_INVALID_PARAMETER; prev_err = pZip->m_last_error; @@ -7021,7 +7021,7 @@ mz_zip_error mz_zip_get_last_error(mz_zip_archive *pZip) const char *mz_zip_get_error_string(mz_zip_error mz_err) { - switch (mz_err) + switch(mz_err) { case MZ_ZIP_NO_ERROR: return "no error"; @@ -7097,7 +7097,7 @@ const char *mz_zip_get_error_string(mz_zip_error mz_err) /* Note: Just because the archive is not zip64 doesn't necessarily mean it doesn't have Zip64 extended information extra field, argh. */ mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) + if((!pZip) || (!pZip->m_pState)) return MZ_FALSE; return pZip->m_pState->m_zip64; @@ -7105,7 +7105,7 @@ mz_bool mz_zip_is_zip64(mz_zip_archive *pZip) size_t mz_zip_get_central_dir_size(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) + if((!pZip) || (!pZip->m_pState)) return 0; return pZip->m_pState->m_central_dir.m_size; @@ -7118,28 +7118,28 @@ mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) mz_uint64 mz_zip_get_archive_size(mz_zip_archive *pZip) { - if (!pZip) + if(!pZip) return 0; return pZip->m_archive_size; } mz_uint64 mz_zip_get_archive_file_start_offset(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) + if((!pZip) || (!pZip->m_pState)) return 0; return pZip->m_pState->m_file_archive_start_ofs; } MZ_FILE *mz_zip_get_cfile(mz_zip_archive *pZip) { - if ((!pZip) || (!pZip->m_pState)) + if((!pZip) || (!pZip->m_pState)) return 0; return pZip->m_pState->m_pFile; } size_t mz_zip_read_archive_data(mz_zip_archive *pZip, mz_uint64 file_ofs, void *pBuf, size_t n) { - if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) + if((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pZip->m_pRead)) return mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return pZip->m_pRead(pZip->m_pIO_opaque, file_ofs, pBuf, n); @@ -7149,15 +7149,15 @@ mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, cha { mz_uint n; const mz_uint8 *p = mz_zip_get_cdh(pZip, file_index); - if (!p) + if(!p) { - if (filename_buf_size) + if(filename_buf_size) pFilename[0] = '\0'; mz_zip_set_error(pZip, MZ_ZIP_INVALID_PARAMETER); return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); - if (filename_buf_size) + if(filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); @@ -7173,12 +7173,12 @@ mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip mz_bool mz_zip_end(mz_zip_archive *pZip) { - if (!pZip) + if(!pZip) return MZ_FALSE; - if (pZip->m_zip_mode == MZ_ZIP_MODE_READING) + if(pZip->m_zip_mode == MZ_ZIP_MODE_READING) return mz_zip_reader_end(pZip); - else if ((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) + else if((pZip->m_zip_mode == MZ_ZIP_MODE_WRITING) || (pZip->m_zip_mode == MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED)) return mz_zip_writer_end(pZip); return MZ_FALSE; diff --git a/src/miniz/miniz.h b/src/miniz/miniz.h index 6353d3782b2..0f75976248f 100644 --- a/src/miniz/miniz.h +++ b/src/miniz/miniz.h @@ -540,9 +540,9 @@ typedef bool mz_bool; /* Works around MSVC's spammy "warning C4127: conditional expression is constant" message. */ #ifdef _MSC_VER -#define MZ_MACRO_END while (0, 0) +#define MZ_MACRO_END while(0, 0) #else -#define MZ_MACRO_END while (0) +#define MZ_MACRO_END while(0) #endif #ifdef MINIZ_NO_STDIO @@ -1241,13 +1241,13 @@ mz_bool mz_zip_reader_extract_file_to_cfile(mz_zip_archive *pZip, const char *pA #if 0 /* TODO */ - typedef void *mz_zip_streaming_extract_state_ptr; - mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); - uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); - uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); - mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); - size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); - mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + typedef void *mz_zip_streaming_extract_state_ptr; + mz_zip_streaming_extract_state_ptr mz_zip_streaming_extract_begin(mz_zip_archive *pZip, mz_uint file_index, mz_uint flags); + uint64_t mz_zip_streaming_extract_get_size(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + uint64_t mz_zip_streaming_extract_get_cur_ofs(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); + mz_bool mz_zip_streaming_extract_seek(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, uint64_t new_ofs); + size_t mz_zip_streaming_extract_read(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState, void *pBuf, size_t buf_size); + mz_bool mz_zip_streaming_extract_end(mz_zip_archive *pZip, mz_zip_streaming_extract_state_ptr pState); #endif /* This function compares the archive's local headers, the optional local zip64 extended information block, and the optional descriptor following the compressed data vs. the data in the central directory. */ From ac41f93895200d2532a5889dfd3deea81cddb1ed Mon Sep 17 00:00:00 2001 From: Chris Smowton Date: Wed, 14 Dec 2016 11:22:40 +0000 Subject: [PATCH 14/67] Use remove_instanceof in driver programs This adds a remove_instanceof call wherever there was an existing remove_virtual_functions call. --- src/cbmc/cbmc_parse_options.cpp | 2 +- src/goto-analyzer/goto_analyzer_parse_options.cpp | 2 +- src/symex/symex_parse_options.cpp | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/cbmc/cbmc_parse_options.cpp b/src/cbmc/cbmc_parse_options.cpp index 7364752d093..842b0b26f70 100644 --- a/src/cbmc/cbmc_parse_options.cpp +++ b/src/cbmc/cbmc_parse_options.cpp @@ -894,7 +894,7 @@ bool cbmc_parse_optionst::process_goto_program( cmdline.isset("pointer-check")); // Java virtual functions -> explicit dispatch tables: remove_virtual_functions(symbol_table, goto_functions); - // Java instanceof -> clsid comparison: + // Similar removal of RTTI inspection: remove_instanceof(symbol_table, goto_functions); // full slice? diff --git a/src/goto-analyzer/goto_analyzer_parse_options.cpp b/src/goto-analyzer/goto_analyzer_parse_options.cpp index 68e28755041..89d3d56731c 100644 --- a/src/goto-analyzer/goto_analyzer_parse_options.cpp +++ b/src/goto-analyzer/goto_analyzer_parse_options.cpp @@ -387,7 +387,7 @@ bool goto_analyzer_parse_optionst::process_goto_program( remove_function_pointers(goto_model, cmdline.isset("pointer-check")); // Java virtual functions -> explicit dispatch tables: remove_virtual_functions(goto_model); - // Java instanceof -> clsid comparison: + // remove rtti remove_instanceof(goto_model); // do partial inlining diff --git a/src/symex/symex_parse_options.cpp b/src/symex/symex_parse_options.cpp index 518e64a2ecd..2ed3fedc518 100644 --- a/src/symex/symex_parse_options.cpp +++ b/src/symex/symex_parse_options.cpp @@ -369,7 +369,6 @@ bool symex_parse_optionst::process_goto_program(const optionst &options) remove_vector(goto_model); // Java virtual functions -> explicit dispatch tables: remove_virtual_functions(goto_model); - // Java instanceof -> clsid comparison: remove_instanceof(goto_model); rewrite_union(goto_model); adjust_float_expressions(goto_model); From ddb4f420d8e1c45b1b4c6829fc318dca2eea4d22 Mon Sep 17 00:00:00 2001 From: Cristina Date: Wed, 8 Feb 2017 17:16:06 +0000 Subject: [PATCH 15/67] Added a side effect expr that pushes/pops Java try-catch handlers + irep ids for Java exception handling These are used to recreate Java try-catch contructs from bytecode. --- src/util/irep_ids.txt | 4 +++- src/util/std_code.h | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/src/util/irep_ids.txt b/src/util/irep_ids.txt index 9bcb7807671..666556d4b78 100644 --- a/src/util/irep_ids.txt +++ b/src/util/irep_ids.txt @@ -738,6 +738,8 @@ java_bytecode_index java_instanceof java_super_method_call java_enum_static_unwind +push_catch +handler string_constraint string_not_contains_constraint cprover_char_literal_func @@ -800,4 +802,4 @@ cprover_string_to_char_array_func cprover_string_to_lower_case_func cprover_string_to_upper_case_func cprover_string_trim_func -cprover_string_value_of_func \ No newline at end of file +cprover_string_value_of_func diff --git a/src/util/std_code.h b/src/util/std_code.h index 08aec694e9e..ed1f8f28b74 100644 --- a/src/util/std_code.h +++ b/src/util/std_code.h @@ -1122,6 +1122,36 @@ inline const side_effect_expr_throwt &to_side_effect_expr_throw( assert(expr.get(ID_statement)==ID_throw); return static_cast(expr); } +/*! \brief A side effect that pushes/pops a catch handler +*/ +class side_effect_expr_catcht:public side_effect_exprt +{ +public: + inline side_effect_expr_catcht():side_effect_exprt(ID_push_catch) + { + } + // TODO: change to ID_catch + inline explicit side_effect_expr_catcht(const irept &exception_list): + side_effect_exprt(ID_push_catch) + { + set(ID_exception_list, exception_list); + } +}; + +static inline side_effect_expr_catcht &to_side_effect_expr_catch(exprt &expr) +{ + assert(expr.id()==ID_side_effect); + assert(expr.get(ID_statement)==ID_push_catch); + return static_cast(expr); +} + +static inline const side_effect_expr_catcht &to_side_effect_expr_catch( + const exprt &expr) +{ + assert(expr.id()==ID_side_effect); + assert(expr.get(ID_statement)==ID_push_catch); + return static_cast(expr); +} /*! \brief A try/catch block */ From a805db9832a575078ce05088e419a6bbf0cb1442 Mon Sep 17 00:00:00 2001 From: Cristina Date: Thu, 15 Dec 2016 09:42:25 +0000 Subject: [PATCH 16/67] Regression tests for exception handling --- regression/exceptions/Makefile | 14 +++++++ regression/exceptions/exceptions1/A.class | Bin 0 -> 234 bytes regression/exceptions/exceptions1/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions1/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions1/D.class | Bin 0 -> 216 bytes regression/exceptions/exceptions1/test.class | Bin 0 -> 1025 bytes regression/exceptions/exceptions1/test.desc | 10 +++++ regression/exceptions/exceptions1/test.java | 30 ++++++++++++++ regression/exceptions/exceptions10/A.class | Bin 0 -> 241 bytes regression/exceptions/exceptions10/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions10/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions10/test.class | Bin 0 -> 875 bytes regression/exceptions/exceptions10/test.desc | 9 ++++ regression/exceptions/exceptions10/test.java | 25 +++++++++++ regression/exceptions/exceptions11/A.class | Bin 0 -> 276 bytes regression/exceptions/exceptions11/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions11/test.class | Bin 0 -> 976 bytes regression/exceptions/exceptions11/test.desc | 9 ++++ regression/exceptions/exceptions11/test.java | 39 ++++++++++++++++++ regression/exceptions/exceptions12/A.class | Bin 0 -> 241 bytes regression/exceptions/exceptions12/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions12/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions12/F.class | Bin 0 -> 641 bytes regression/exceptions/exceptions12/test.class | Bin 0 -> 740 bytes regression/exceptions/exceptions12/test.desc | 9 ++++ regression/exceptions/exceptions12/test.java | 27 ++++++++++++ regression/exceptions/exceptions13/A.class | Bin 0 -> 241 bytes regression/exceptions/exceptions13/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions13/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions13/F.class | Bin 0 -> 405 bytes regression/exceptions/exceptions13/test.class | Bin 0 -> 740 bytes regression/exceptions/exceptions13/test.desc | 9 ++++ regression/exceptions/exceptions13/test.java | 28 +++++++++++++ regression/exceptions/exceptions14/A.class | Bin 0 -> 241 bytes regression/exceptions/exceptions14/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions14/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions14/test.class | Bin 0 -> 858 bytes regression/exceptions/exceptions14/test.desc | 8 ++++ regression/exceptions/exceptions14/test.java | 24 +++++++++++ regression/exceptions/exceptions2/A.class | Bin 0 -> 234 bytes regression/exceptions/exceptions2/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions2/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions2/test.class | Bin 0 -> 771 bytes regression/exceptions/exceptions2/test.desc | 10 +++++ regression/exceptions/exceptions2/test.java | 18 ++++++++ regression/exceptions/exceptions3/A.class | Bin 0 -> 234 bytes regression/exceptions/exceptions3/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions3/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions3/test.class | Bin 0 -> 751 bytes regression/exceptions/exceptions3/test.desc | 9 ++++ regression/exceptions/exceptions3/test.java | 17 ++++++++ regression/exceptions/exceptions4/A.class | Bin 0 -> 234 bytes regression/exceptions/exceptions4/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions4/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions4/test.class | Bin 0 -> 743 bytes regression/exceptions/exceptions4/test.desc | 8 ++++ regression/exceptions/exceptions4/test.java | 19 +++++++++ regression/exceptions/exceptions5/A.class | Bin 0 -> 234 bytes regression/exceptions/exceptions5/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions5/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions5/D.class | Bin 0 -> 216 bytes regression/exceptions/exceptions5/test.class | Bin 0 -> 997 bytes regression/exceptions/exceptions5/test.desc | 8 ++++ regression/exceptions/exceptions5/test.java | 27 ++++++++++++ regression/exceptions/exceptions6/A.class | Bin 0 -> 280 bytes regression/exceptions/exceptions6/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions6/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions6/D.class | Bin 0 -> 216 bytes regression/exceptions/exceptions6/test.class | Bin 0 -> 806 bytes regression/exceptions/exceptions6/test.desc | 9 ++++ regression/exceptions/exceptions6/test.java | 26 ++++++++++++ regression/exceptions/exceptions7/A.class | Bin 0 -> 241 bytes regression/exceptions/exceptions7/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions7/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions7/test.class | Bin 0 -> 871 bytes regression/exceptions/exceptions7/test.desc | 9 ++++ regression/exceptions/exceptions7/test.java | 25 +++++++++++ regression/exceptions/exceptions8/A.class | Bin 0 -> 241 bytes regression/exceptions/exceptions8/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions8/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions8/test.class | Bin 0 -> 935 bytes regression/exceptions/exceptions8/test.desc | 9 ++++ regression/exceptions/exceptions8/test.java | 29 +++++++++++++ regression/exceptions/exceptions9/A.class | Bin 0 -> 276 bytes regression/exceptions/exceptions9/B.class | Bin 0 -> 216 bytes regression/exceptions/exceptions9/C.class | Bin 0 -> 216 bytes regression/exceptions/exceptions9/test.class | Bin 0 -> 976 bytes regression/exceptions/exceptions9/test.desc | 8 ++++ regression/exceptions/exceptions9/test.java | 39 ++++++++++++++++++ 89 files changed, 511 insertions(+) create mode 100644 regression/exceptions/Makefile create mode 100644 regression/exceptions/exceptions1/A.class create mode 100644 regression/exceptions/exceptions1/B.class create mode 100644 regression/exceptions/exceptions1/C.class create mode 100644 regression/exceptions/exceptions1/D.class create mode 100644 regression/exceptions/exceptions1/test.class create mode 100644 regression/exceptions/exceptions1/test.desc create mode 100644 regression/exceptions/exceptions1/test.java create mode 100644 regression/exceptions/exceptions10/A.class create mode 100644 regression/exceptions/exceptions10/B.class create mode 100644 regression/exceptions/exceptions10/C.class create mode 100644 regression/exceptions/exceptions10/test.class create mode 100644 regression/exceptions/exceptions10/test.desc create mode 100644 regression/exceptions/exceptions10/test.java create mode 100644 regression/exceptions/exceptions11/A.class create mode 100644 regression/exceptions/exceptions11/B.class create mode 100644 regression/exceptions/exceptions11/test.class create mode 100644 regression/exceptions/exceptions11/test.desc create mode 100644 regression/exceptions/exceptions11/test.java create mode 100644 regression/exceptions/exceptions12/A.class create mode 100644 regression/exceptions/exceptions12/B.class create mode 100644 regression/exceptions/exceptions12/C.class create mode 100644 regression/exceptions/exceptions12/F.class create mode 100644 regression/exceptions/exceptions12/test.class create mode 100644 regression/exceptions/exceptions12/test.desc create mode 100644 regression/exceptions/exceptions12/test.java create mode 100644 regression/exceptions/exceptions13/A.class create mode 100644 regression/exceptions/exceptions13/B.class create mode 100644 regression/exceptions/exceptions13/C.class create mode 100644 regression/exceptions/exceptions13/F.class create mode 100644 regression/exceptions/exceptions13/test.class create mode 100644 regression/exceptions/exceptions13/test.desc create mode 100644 regression/exceptions/exceptions13/test.java create mode 100644 regression/exceptions/exceptions14/A.class create mode 100644 regression/exceptions/exceptions14/B.class create mode 100644 regression/exceptions/exceptions14/C.class create mode 100644 regression/exceptions/exceptions14/test.class create mode 100644 regression/exceptions/exceptions14/test.desc create mode 100644 regression/exceptions/exceptions14/test.java create mode 100644 regression/exceptions/exceptions2/A.class create mode 100644 regression/exceptions/exceptions2/B.class create mode 100644 regression/exceptions/exceptions2/C.class create mode 100644 regression/exceptions/exceptions2/test.class create mode 100644 regression/exceptions/exceptions2/test.desc create mode 100644 regression/exceptions/exceptions2/test.java create mode 100644 regression/exceptions/exceptions3/A.class create mode 100644 regression/exceptions/exceptions3/B.class create mode 100644 regression/exceptions/exceptions3/C.class create mode 100644 regression/exceptions/exceptions3/test.class create mode 100644 regression/exceptions/exceptions3/test.desc create mode 100644 regression/exceptions/exceptions3/test.java create mode 100644 regression/exceptions/exceptions4/A.class create mode 100644 regression/exceptions/exceptions4/B.class create mode 100644 regression/exceptions/exceptions4/C.class create mode 100644 regression/exceptions/exceptions4/test.class create mode 100644 regression/exceptions/exceptions4/test.desc create mode 100644 regression/exceptions/exceptions4/test.java create mode 100644 regression/exceptions/exceptions5/A.class create mode 100644 regression/exceptions/exceptions5/B.class create mode 100644 regression/exceptions/exceptions5/C.class create mode 100644 regression/exceptions/exceptions5/D.class create mode 100644 regression/exceptions/exceptions5/test.class create mode 100644 regression/exceptions/exceptions5/test.desc create mode 100644 regression/exceptions/exceptions5/test.java create mode 100644 regression/exceptions/exceptions6/A.class create mode 100644 regression/exceptions/exceptions6/B.class create mode 100644 regression/exceptions/exceptions6/C.class create mode 100644 regression/exceptions/exceptions6/D.class create mode 100644 regression/exceptions/exceptions6/test.class create mode 100644 regression/exceptions/exceptions6/test.desc create mode 100644 regression/exceptions/exceptions6/test.java create mode 100644 regression/exceptions/exceptions7/A.class create mode 100644 regression/exceptions/exceptions7/B.class create mode 100644 regression/exceptions/exceptions7/C.class create mode 100644 regression/exceptions/exceptions7/test.class create mode 100644 regression/exceptions/exceptions7/test.desc create mode 100644 regression/exceptions/exceptions7/test.java create mode 100644 regression/exceptions/exceptions8/A.class create mode 100644 regression/exceptions/exceptions8/B.class create mode 100644 regression/exceptions/exceptions8/C.class create mode 100644 regression/exceptions/exceptions8/test.class create mode 100644 regression/exceptions/exceptions8/test.desc create mode 100644 regression/exceptions/exceptions8/test.java create mode 100644 regression/exceptions/exceptions9/A.class create mode 100644 regression/exceptions/exceptions9/B.class create mode 100644 regression/exceptions/exceptions9/C.class create mode 100644 regression/exceptions/exceptions9/test.class create mode 100644 regression/exceptions/exceptions9/test.desc create mode 100644 regression/exceptions/exceptions9/test.java diff --git a/regression/exceptions/Makefile b/regression/exceptions/Makefile new file mode 100644 index 00000000000..5ac5a21995e --- /dev/null +++ b/regression/exceptions/Makefile @@ -0,0 +1,14 @@ +default: tests.log + +test: + @../test.pl -c ../../../src/cbmc/cbmc + +tests.log: ../test.pl + @../test.pl -c ../../../src/cbmc/cbmc + +show: + @for dir in *; do \ + if [ -d "$$dir" ]; then \ + vim -o "$$dir/*.java" "$$dir/*.out"; \ + fi; \ + done; diff --git a/regression/exceptions/exceptions1/A.class b/regression/exceptions/exceptions1/A.class new file mode 100644 index 0000000000000000000000000000000000000000..eb19ef6be2b4b0dc315cdfd2ae091ecc67882efd GIT binary patch literal 234 zcmXX=%MQU%5IsX5TBX7dSYn|YJ0fW$R*em@zv_l7)h5;QT~-ncAK;_J+%n0`dF0Gw z-k;|Szyuu^b+l}>ZTJLhrczbR3H8BnOE4DMUK0FBrE*oCcQW6IUBXT`%3_ghMXt2| zn?`X|7ha9RDZyQ5Wgg3=(s8GdmtuSpSK+~cNuZF>(>h2*dI&bhJiF;j=%dE}=pt^; iGFr?6M(voR2k6eE2Aii7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|N0ia<-WNlvOJ0;V`m%{smNkcs&?*7 zqdu#OPor>6a1TXOrgEp+xKqojUR=aYcraiRC}aefK;!Ri5ra3(7ON$5>zMNg=*~ie V&E4u^J=Weo00%Blg#It(eE}M}B0B&8 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions1/test.class b/regression/exceptions/exceptions1/test.class new file mode 100644 index 0000000000000000000000000000000000000000..c76687b1bc7a0547086d763afd30f531210e3b7a GIT binary patch literal 1025 zcmZuvZBNr+6g|({ty|ZPF%&@&5kWUp<_m&uXoR7Oro#^y5+Q+fTZQ82Ok0eORw}P5==E;f zRp_%l-(B9@ZMwl*NmeM@-Imi?bplWPlb{}Ldm($+ksC%eR_{8VuP|6zw|AURPNn1c zTa}e4@cgZsbXOdz*-Ok+EkSibO+kx-96<|$I8bvxOO6w4asB`FQ^>7EPU}O%`513Q zai|L=p&AP5`BvwIn7Pv33tH|=PiSOh(`i}GLJ#!;P(Z)J(AoA2e|38i z1l@oXrGbH}g&O7+3TK&bnmcYQqIPGYdWW)8kG30nf!jXq#l@pN{z1*xaGkH#$5&Q` zA(>93fqG+r_XT(nJgW;RQ;<1aL6vgU$mkWZP0kH+T_@fk z*G;nB#Yn8gd-h3VjQ@;Kfdczo#VEHBX|FM^vAe-D&W$GN-5^SGN*)t&MJ-07tZl?- zjA%1P<3!YvRX1sG@eCrpZJ?B2G*FgnO0L^^&cAc|cr$So&|l1bLw+BIegIwj3iJF! RO3Ne?)^mC8yL1wm{teh!r=|b^ literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions1/test.desc b/regression/exceptions/exceptions1/test.desc new file mode 100644 index 00000000000..baf72e7da81 --- /dev/null +++ b/regression/exceptions/exceptions1/test.desc @@ -0,0 +1,10 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 26 function.*: FAILURE$ +\*\* 1 of 35 failed (2 iterations)$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions1/test.java b/regression/exceptions/exceptions1/test.java new file mode 100644 index 00000000000..bc925b32d65 --- /dev/null +++ b/regression/exceptions/exceptions1/test.java @@ -0,0 +1,30 @@ +class A extends Throwable {} +class B extends A {} +class C extends B {} +class D extends C {} + +public class test { + public static void main (String arg[]) { + try { + D d = new D(); + C c = new C(); + B b = new B(); + A a = new A(); + A e = a; + throw e; + } + catch(D exc) { + assert false; + } + catch(C exc) { + assert false; + } + catch(B exc) { + assert false; + } + catch(A exc) { + assert false; + } + } +} + diff --git a/regression/exceptions/exceptions10/A.class b/regression/exceptions/exceptions10/A.class new file mode 100644 index 0000000000000000000000000000000000000000..963ae156be051ca07ea2d602053e012a3d27a7a4 GIT binary patch literal 241 zcmXX=O;5r=5PbuswY3W2=*gpUuorF+lg8kw;Q*%hZQaP2c5B)#@o#xD@!${OM-gX{ zNoL+h-b?0i{P_hi$0WiKR{^dAj0ygd4ckY;@a{e*cu&o%CX6#SdfnHBZeLVUi8IZb zQdPNX+3BSuQG(CW@UysN#6;bBCelyKv8QYrJ6YoqP1btzNpmRpEZ_t;J0Rp-H$s}9|kN*P*5s4yPo>K82_(?21 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions10/B.class b/regression/exceptions/exceptions10/B.class new file mode 100644 index 0000000000000000000000000000000000000000..47ae8f218e49b4ac942425d72a88b21c2772b518 GIT binary patch literal 216 zcmXX7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|NGzlS}mmtic&3AsXFXn91H3~A};DMBd*dk)?i7TBz61){t5m7 zYjj2&nUTFe%JJM-=|UEHxgY1Ad+vSj*Y6)c0j%Mni6R;XZkf=~D4>Ab2AU?aXqa?X z473c~F>x3746G_tmYq2EqQnn__=z7oy`k4vPp=^h)Gu(9|U;J@UPu}@4IqbxXlXY^u4MWoQXxSa{y-%*fR5x+l_b;3e zX%$7Y&4J?w3f1Ntd*Au!w1-YGXm^vy4+iTZLpegRNebPG25eEe0LUQ~@*D1OJb~E_ zN0IA2^F?n#B&`a$g=x%?vSY!*ltOLNvGZ>!PopS|EL={3o9rsp2HFh9BU|a6SQy`qZi{yAdYb>Xb+ut;YQFpJD&;ExO}pLPUgJ5 zs~2-yJ(_tz(#y)+6f;w~rr$ypUfhz_Y;-Nq4`p5DcIuk-B-mxRcs1`PMU34PJ81LZ zNO01?L1Fy!;J)_3E$rkYw{O9f9;f_J@nd1ou&wAPN!VQ>+RSwS8`4)_h(1XpXl6}q ToQk@~D*fN2?r-=3bA-+x##1h8 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions11/B.class b/regression/exceptions/exceptions11/B.class new file mode 100644 index 0000000000000000000000000000000000000000..3af09687e1afeb9c7dd88272ec5fde0e48c3b12d GIT binary patch literal 216 zcmXX7D18_mM(%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN#-1 z8r4~qd>RHzf_up8B9S}Q#GOi()$Af}!h->mKmlWe5j6hZ6fth>=A0{wU*lk3vm!G4I`v^Ugi@-psGxKYjvOz#R)IR1C~o(ByqNi2+3dBm~bpd_V zZ@B`4b+6+-?(Q_);F$yqWb1y@X|FqhC;eVfk6wErIqH!cMvLTl<@@9))yg%pI}Fs9 z85Rv%?z^V+SERqqkBHP-OE2qN&ReJ2b~>BYwJ7j9n~O@H z6Kt|#?mubHMZjEYwtEd(YkoIqx(_`mKPeT?NlF_T46*()zZDy44BEJXQGr6g;PT0^ z9t43O*f@s*rAZ0{H*MU)ZGlW5{-m+xHY4(RoLoP=+UC&NOUn(tz-^t9vg@eJ1Sh_M zaV{*y?TSo6YN4frRa{Ci0>jd`xOcO0|pLZ5MmzbpA=<*L^@)s-~@?5tvc1psij#U z&rE^khIv*|RAMSb*ep6spS{yMudHF(Be^7l6ndy%qXE_#F@k#3zf}` zD4{@^sA=^U{H3&~24?bvUOL^$f+_|KWe2{&-i4v>L63bw{NMeIktYt#z9+X>qNAbw E2bxcsM*si- literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions11/test.desc b/regression/exceptions/exceptions11/test.desc new file mode 100644 index 00000000000..cb92a091217 --- /dev/null +++ b/regression/exceptions/exceptions11/test.desc @@ -0,0 +1,9 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 36 function.*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions11/test.java b/regression/exceptions/exceptions11/test.java new file mode 100644 index 00000000000..032af621fc3 --- /dev/null +++ b/regression/exceptions/exceptions11/test.java @@ -0,0 +1,39 @@ +class A extends RuntimeException { + int i=1; +}; + +class B extends A { +}; + +public class test { + static int foo(int k) { + try { + if(k==0) + { + A a = new A(); + throw a; + } + else + { + A b = new A(); + throw b; + } + + } + catch(B exc) { + assert exc.i==1; + } + return 1; + } + + + public static void main (String args[]) { + try { + A a = new A(); + foo(6); + } + catch(A exc) { + assert exc.i==2; + } + } +} diff --git a/regression/exceptions/exceptions12/A.class b/regression/exceptions/exceptions12/A.class new file mode 100644 index 0000000000000000000000000000000000000000..963ae156be051ca07ea2d602053e012a3d27a7a4 GIT binary patch literal 241 zcmXX=O;5r=5PbuswY3W2=*gpUuorF+lg8kw;Q*%hZQaP2c5B)#@o#xD@!${OM-gX{ zNoL+h-b?0i{P_hi$0WiKR{^dAj0ygd4ckY;@a{e*cu&o%CX6#SdfnHBZeLVUi8IZb zQdPNX+3BSuQG(CW@UysN#6;bBCelyKv8QYrJ6YoqP1btzNpmRpEZ_t;J0Rp-H$s}9|kN*P*5s4yPo>K82_(?21 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions12/B.class b/regression/exceptions/exceptions12/B.class new file mode 100644 index 0000000000000000000000000000000000000000..47ae8f218e49b4ac942425d72a88b21c2772b518 GIT binary patch literal 216 zcmXX7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|Nukq z=Ym8fD$zS1g?Q_R^nk40ee?8Y-pu&-pP#<~Y~oIc0ILdDLU>pWpm0^;T8OG6yCJUQ zhQdw3(wfe5lNB}{=TB^|hlv>pWM5F*vSV936jatX_5}V;Ix>QVfgPI{lMh3ay>enf zYmmk|+0&VI@s#w7cQ$A0p#OmPn>1z3p^LX&Y(B?=x!pp?@1N_BWePhL)VJbfY8vjQ zlPorU>nwu8{?EwbJZ3YoZDdyMbVysK;0MR_`7| zjtD#~@UESaXc9+LyoeSfU}={8g=&w?$_c#J$6V9B)4@0RhiIIjN}_gpROW`X_Gs)X zxA`xDI=`T7sKNTnY{fZssi{+W0T-FqAlohx9dPD;i7Ex}nL=lt(&bqzo23!3*it`G bKZNqX!moUX|Nl&`MipN4$W6Y&z{BOgR*PqV literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions12/test.class b/regression/exceptions/exceptions12/test.class new file mode 100644 index 0000000000000000000000000000000000000000..a4350fcd81d62534433b034e2f9d88328d74c8b8 GIT binary patch literal 740 zcmZuu%Tg0T6g@q8OfnhrRE($u5H)}j7wn)c1qnOJ^-AHff} zMysGos&wy1S)Lw|EOgP`_ufADoYS{|{`&SEzy=;Ws9?#)T?ZDH%(iUfUKwTFxADM% zZ7#bGR6=*PUJ99BLQ(BP~6g?PM-+mx-0tv`JHH_1ZtiR)vL+z zP{n%&EYS2KUk3X!)+WC!=F_)2A%~Z$B;929vDBf!Z1;_KBtOVrAj5HQkj6S3ZyI)S zNFA?FWKMnbO}uToWIQHI>px8bGlNw6?_SFHnIs=6P}=f?OViFEn#8{9Yh$r&T&x>m z7gf|K*LU$S3$|Ujm=S1CZ9V%tkQZ?r#dKl1Z9HuSq<}#KJ5x3cUhs%bwYh%7jXy@ud8yO5} fG|OjjPGHkeKKB*He;;Q!3b5R#W&{gNEG+&8z8Qep literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions12/test.desc b/regression/exceptions/exceptions12/test.desc new file mode 100644 index 00000000000..4654e88cbb6 --- /dev/null +++ b/regression/exceptions/exceptions12/test.desc @@ -0,0 +1,9 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 12 function.*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions12/test.java b/regression/exceptions/exceptions12/test.java new file mode 100644 index 00000000000..5828419fac6 --- /dev/null +++ b/regression/exceptions/exceptions12/test.java @@ -0,0 +1,27 @@ +class A extends RuntimeException {} +class B extends A {} +class C extends B {} + +class F { + void foo() { + try { + B b = new B(); + throw b; + } + catch(B exc) { + assert false; + } + } +} + +public class test { + public static void main (String args[]) { + try { + F f = new F(); + f.foo(); + } + catch(B exc) { + assert false; + } + } +} diff --git a/regression/exceptions/exceptions13/A.class b/regression/exceptions/exceptions13/A.class new file mode 100644 index 0000000000000000000000000000000000000000..963ae156be051ca07ea2d602053e012a3d27a7a4 GIT binary patch literal 241 zcmXX=O;5r=5PbuswY3W2=*gpUuorF+lg8kw;Q*%hZQaP2c5B)#@o#xD@!${OM-gX{ zNoL+h-b?0i{P_hi$0WiKR{^dAj0ygd4ckY;@a{e*cu&o%CX6#SdfnHBZeLVUi8IZb zQdPNX+3BSuQG(CW@UysN#6;bBCelyKv8QYrJ6YoqP1btzNpmRpEZ_t;J0Rp-H$s}9|kN*P*5s4yPo>K82_(?21 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions13/B.class b/regression/exceptions/exceptions13/B.class new file mode 100644 index 0000000000000000000000000000000000000000..47ae8f218e49b4ac942425d72a88b21c2772b518 GIT binary patch literal 216 zcmXX7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|N~W_5d{6*B%>=cEi9Za@cY?f zme?@W+*)qu`SH-amqnOJ^-AHff} zMysGos&wy1S)Lw|EOgP`_ufADoYS{|{`&SEzy=;Ws9?#)T?ZDH%(iUfUKwTFxADM% zZ7#bGR6=*PUJ99BLQ(BP~6g?PM-+mx-0tv`JHH_1ZtiR)vL+z zP{n%&EYS2KUk3X!)+WC!=F_)2A%~Z$B;929vDBf!Z1;_KBtOVrAj5HQkj6S3ZyI)S zNFA?FWKMnbO}uToWIQHI>px8bGlNw6?_SFHnIs=6P}=f?OViFEn#8{9Yh$r&T&x>m z7gf|K*LU$S3$|Ujm=S1CZ9V%tkQZ?r#dKl1Z9HuSq<}#KJ5x3cUhs%bwYh%7jXy@ud8yO5} fG|OjjPGHkeKKB*He;;Q!3b5R#W&{gNEG+&8z8Qep literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions13/test.desc b/regression/exceptions/exceptions13/test.desc new file mode 100644 index 00000000000..cb7c1b81341 --- /dev/null +++ b/regression/exceptions/exceptions13/test.desc @@ -0,0 +1,9 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 25 function.*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions13/test.java b/regression/exceptions/exceptions13/test.java new file mode 100644 index 00000000000..56d763f68d3 --- /dev/null +++ b/regression/exceptions/exceptions13/test.java @@ -0,0 +1,28 @@ +class A extends RuntimeException {} +class B extends A {} +class C extends B {} + +class F { + void foo() { + try { + B b = new B(); + throw b; + } + catch(B exc) { + throw exc; + } + } +} + +public class test { + + public static void main (String args[]) { + try { + F f = new F(); + f.foo(); + } + catch(B exc) { + assert false; + } + } +} diff --git a/regression/exceptions/exceptions14/A.class b/regression/exceptions/exceptions14/A.class new file mode 100644 index 0000000000000000000000000000000000000000..963ae156be051ca07ea2d602053e012a3d27a7a4 GIT binary patch literal 241 zcmXX=O;5r=5PbuswY3W2=*gpUuorF+lg8kw;Q*%hZQaP2c5B)#@o#xD@!${OM-gX{ zNoL+h-b?0i{P_hi$0WiKR{^dAj0ygd4ckY;@a{e*cu&o%CX6#SdfnHBZeLVUi8IZb zQdPNX+3BSuQG(CW@UysN#6;bBCelyKv8QYrJ6YoqP1btzNpmRpEZ_t;J0Rp-H$s}9|kN*P*5s4yPo>K82_(?21 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions14/B.class b/regression/exceptions/exceptions14/B.class new file mode 100644 index 0000000000000000000000000000000000000000..47ae8f218e49b4ac942425d72a88b21c2772b518 GIT binary patch literal 216 zcmXX7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|NKQjnAn#E;R9?=Y8JyydTf=o__!NT6@^@1Qu*R z@ScxOx?cEFCJW^4q3a9|ozR#5G^oXI{D?j5*o)$AR-ZV2Ah1+>Z67=Do%+BD`t?p6 z`ayqNb{8(^*llL2-iHLYB(|Hf)(QLURrp7#zCjx5%nH_g96<~CR zqtNyCd`UMe8LdkaCKh0Ebemt(#5{5Wr5U^CpS|pc;V@)Qi&SK>j)x{5VMD;0Wxwbi zdv47A%tGw}S4+)3FY-gLchQfG;}I{o*CQ| zcl=-EENNzOsKTZeDjX(%yG{OOYC>xx(UL`msw`3{&@WQg3UP(1s*E;BbCWk)yxAjF zDWQQBYceR|3aJ;lhpP#yCg>VtTM4?JNZrQ`++@`)ev3$VbllFhbS%qbCC4^*F4osb h3YeBRK4b0_x;BQUenR^1RmyHDDCSeS@G>0*m0$24k%|BS literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions14/test.desc b/regression/exceptions/exceptions14/test.desc new file mode 100644 index 00000000000..dc5ca4fa5cb --- /dev/null +++ b/regression/exceptions/exceptions14/test.desc @@ -0,0 +1,8 @@ +CORE +test.class + +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions14/test.java b/regression/exceptions/exceptions14/test.java new file mode 100644 index 00000000000..24f44a5d3d9 --- /dev/null +++ b/regression/exceptions/exceptions14/test.java @@ -0,0 +1,24 @@ +class A extends RuntimeException {} +class B extends A {} +class C extends B {} + +public class test { + public static void main (String args[]) { + try { + try { + C c = new C(); + A a = new A(); + } + catch(C exc) { + assert false; + } + catch(B exc) { + assert false; + } + } + catch(A exc) { + assert false; + } + + } +} diff --git a/regression/exceptions/exceptions2/A.class b/regression/exceptions/exceptions2/A.class new file mode 100644 index 0000000000000000000000000000000000000000..eb19ef6be2b4b0dc315cdfd2ae091ecc67882efd GIT binary patch literal 234 zcmXX=%MQU%5IsX5TBX7dSYn|YJ0fW$R*em@zv_l7)h5;QT~-ncAK;_J+%n0`dF0Gw z-k;|Szyuu^b+l}>ZTJLhrczbR3H8BnOE4DMUK0FBrE*oCcQW6IUBXT`%3_ghMXt2| zn?`X|7ha9RDZyQ5Wgg3=(s8GdmtuSpSK+~cNuZF>(>h2*dI&bhJiF;j=%dE}=pt^; iGFr?6M(voR2k6eE2Aii7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|Nfgc6r6RO*m2x6O`rrwftCVkQkqL|tq>%@0U0<1Rid0W&MIti9b`L*-_k$O zbBjbJD$zSX3Naf(BLs)_``9;c=DqcgpWnU%*v6Iz4{HwYda#ULFT%w=2lqV`O#Hw@ z6B`a%0=0FSrYgzwI8LAHR1P9F6cGCYg=9%t&31@BlsXnzZoUf+3-?PC)U1uFB(*MkEUW?acU)r+`IjyY7RPSo(S z7o}zsUT~HBSmk4Qd?!(<8+Lj*a2%BRU1Zdu6}0)*8N>-43l)9~zmr&^@6Y@yYK)4w zf~(9J@F}Y;+RbxVZ_l{L_C;`t{1Hm$C@|q%9P`Eg&YVmU=AW^N^w40On{uvEDtKIS zcob{oUgu4NVpqu5rW&KCMWjpAGOkfaiMMsu3Dy|Tn|0k`U}5za)c=H& literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions2/test.desc b/regression/exceptions/exceptions2/test.desc new file mode 100644 index 00000000000..eb7fa309bea --- /dev/null +++ b/regression/exceptions/exceptions2/test.desc @@ -0,0 +1,10 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 15 function.*: FAILURE$ +^\*\* 1 of 20 failed (2 iterations)$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions2/test.java b/regression/exceptions/exceptions2/test.java new file mode 100644 index 00000000000..420b50219c1 --- /dev/null +++ b/regression/exceptions/exceptions2/test.java @@ -0,0 +1,18 @@ +class A extends Throwable {} +class B extends A {} +class C extends B {} + +public class test { + public static void main (String args[]) { + try { + B b = new B(); + throw b; + } + catch(C exc) { + assert false; + } + catch(B exc) { + assert false; + } + } +} diff --git a/regression/exceptions/exceptions3/A.class b/regression/exceptions/exceptions3/A.class new file mode 100644 index 0000000000000000000000000000000000000000..eb19ef6be2b4b0dc315cdfd2ae091ecc67882efd GIT binary patch literal 234 zcmXX=%MQU%5IsX5TBX7dSYn|YJ0fW$R*em@zv_l7)h5;QT~-ncAK;_J+%n0`dF0Gw z-k;|Szyuu^b+l}>ZTJLhrczbR3H8BnOE4DMUK0FBrE*oCcQW6IUBXT`%3_ghMXt2| zn?`X|7ha9RDZyQ5Wgg3=(s8GdmtuSpSK+~cNuZF>(>h2*dI&bhJiF;j=%dE}=pt^; iGFr?6M(voR2k6eE2Aii7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|Nfgc5PfSqaqPNjnm`BzN(%*&@R3Vztq>%DI2d{eszf<$oK@J8I>>eqzokbm zJr^V@QHkF9QHZxDG(vFLoq4lwX5P&H`1$QSfKA-@;bYy!4Ih@VH$9ZF;o_E$qQSR) z+(FYtOQ5zP(^Msyp2X=Boyx&j4F$xWKyh2gI(sN!H(R>`PH!?)0!yKe)ywI@KqapX zS)dwDB01ibi8go^bh5WPWsNXXX|~1e1F2(ydh<=VFF(l6SjMAHKTC8x+A`H`^)ccd z_QO!6dq92e^xS0+l&)XRxoLjO&<(dSh;qBMw!n6E!@q zMXA}84_xCO*7*@W|439CraL_w90z6IOGF)7L0f2_KpfMtP~lzt9mF#IVCGj*Bl2(o z7a1|hpUAdo+o!NzpTIr~KcjGng;Nv>-LoV9)!&ihoL{0Shj}He5ZigjRk(S?$n_}o z5<9F==oLzBkztgqk?RrH`6}|4IvTmUHZGG5#*AL)xr?jiu8V7B_EZTJLhrczbR3H8BnOE4DMUK0FBrE*oCcQW6IUBXT`%3_ghMXt2| zn?`X|7ha9RDZyQ5Wgg3=(s8GdmtuSpSK+~cNuZF>(>h2*dI&bhJiF;j=%dE}=pt^; iGFr?6M(voR2k6eE2Aii7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|Nfgc5Pj=7apJgXnm|b*4gCVr7Me?Mtq>%@0U3G-szf<$oK@J8+Q@bgzl1~o z0Ox{4B`VQ7KML{IgysOUc6Vm>&Ad0W{`u?s4*Y0ysJ>V!4?R3+&ivrnWB1s2!u>G?PWBwAGSQkzDxs0U+hmj(` z6657e;1Vl0DQ}qw!@fdnkr|7)LDn*F8d%B{wQv)+h-h+ou%A0vu5=x=OvT$*4en-G gV4+t0hSDhZTJLhrczbR3H8BnOE4DMUK0FBrE*oCcQW6IUBXT`%3_ghMXt2| zn?`X|7ha9RDZyQ5Wgg3=(s8GdmtuSpSK+~cNuZF>(>h2*dI&bhJiF;j=%dE}=pt^; iGFr?6M(voR2k6eE2Aii7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|N0ia<-WNlvOJ0;V`m%{smNkcs&?*7 zqdu#OPor>6a1TXOrgEp+xKqojUR=aYcraiRC}aefK;!Ri5ra3(7ON$5>zMNg=*~ie V&E4u^J=Weo00%Blg#It(eE}M}B0B&8 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions5/test.class b/regression/exceptions/exceptions5/test.class new file mode 100644 index 0000000000000000000000000000000000000000..1b251e32471f5d7fe325eac698256834648f5e0a GIT binary patch literal 997 zcmZuv+fEZv6kVq??X=U<7SKw)AS&p9O1)Ik77etO#AJ#O7!tuC({=)br8P5y@mu%- zp3y`So5;H#Wn6nic)&F0?6r6IZLKrEe*gFhpo|wLawr*iU?L{=p$T2=BNGX+k4+>| zN?{0P15Zq(CHU0D9G)3?t}r_31cB>^UcVPKyufL7-Hw73oW| zp*Ylql28qWqNx%U}ef9M#~d^VE12Gst6DVeD-C#ecfJ z^8LO~iqgP9C4(yF74m19Z(2KUJEV4Jp?a6HQ;&`tc)r^??Zw5zJ^n$>*KmWcmg6g{ z{FqE9(m=g2%KHMn60M?*&m2J=62x$kcOnYvC=h4tZhbUBGPe_ zxwqN<4o?BeZ39-eW?)*b8M*F)Q}3NVP&ujshDV0JBfAenKY*@%gL(e3q-7kj%z`}W JeL6AB{sHnbp}znC literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions5/test.desc b/regression/exceptions/exceptions5/test.desc new file mode 100644 index 00000000000..dc5ca4fa5cb --- /dev/null +++ b/regression/exceptions/exceptions5/test.desc @@ -0,0 +1,8 @@ +CORE +test.class + +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions5/test.java b/regression/exceptions/exceptions5/test.java new file mode 100644 index 00000000000..e539f06df1e --- /dev/null +++ b/regression/exceptions/exceptions5/test.java @@ -0,0 +1,27 @@ +class A extends Throwable {} +class B extends A {} +class C extends B {} +class D extends C {}public class test { + public static void main (String arg[]) { + try { + D d = new D(); + C c = new C(); + B b = new B(); + A a = new A(); + A e = a; + throw e; + } + catch(D exc) { + assert false; + } + catch(C exc) { + assert false; + } + catch(B exc) { + assert false; + } + catch(A exc) { + } + } +} + diff --git a/regression/exceptions/exceptions6/A.class b/regression/exceptions/exceptions6/A.class new file mode 100644 index 0000000000000000000000000000000000000000..fbaaf105dbaddd4eb32dc843a524880a3ff50fe4 GIT binary patch literal 280 zcmXYru};H45JYF4ON@<4AW%_JLJHE*5g|ngBqWOhQ2L8G!6N63oHNRAQ6MA=K7fxx zj6;gO-FZ8s+n?XBZvbaFNMW#>po6^_!x;MlQPz#1H&L(QLeM!rnF-8g_2>kHT)n$( z7IRlW*m+4Z%&WqdGh1t`H_(J7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*?v$M18 z`}2GOSYqfwN8iT4MnJIEDp&P}piibT!3c|!Bm|Ml<-WNlvOJ0;V`mf*X@L|9tP{`O~42{3HMGW3BTdWq$tz*s}pgRi< WHg~Ht9XPE0UjQyVo(R1z<$nPh2O>NG literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions6/D.class b/regression/exceptions/exceptions6/D.class new file mode 100644 index 0000000000000000000000000000000000000000..12179e84294d669f8f9f06e51f5400f5cc8f5db6 GIT binary patch literal 216 zcmXX0ia<-WNlvOJ0;V`m%{smNkcs&?*7 zqdu#OPor>6a1TXOrgEp+xKqojUR=aYcraiRC}aefK;!Ri5ra3(7ON$5>zMNg=*~ie V&E4u^J=Weo00%Blg#It(eE}M}B0B&8 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions6/test.class b/regression/exceptions/exceptions6/test.class new file mode 100644 index 0000000000000000000000000000000000000000..e0c57f3e31882cdf481a96c6f9f53834e3440c85 GIT binary patch literal 806 zcmZuv&2JJx9DTF9u95vnGdRS%dZ*3+_Va4KEQ?qd8~dhytE z)!4))Hu2~mWqh;NVxotc`F+0Mn>X|0=htrlHgMO5gNBLgHZ(LW*tlWQYMNNJkyV+N zg`D!&Y}~{x6YBz{x);Yml*nlqKajCEoCG5Qu`Q78%1|cv1oYvhMR)3ZlPxcj%0CGj$!i%C!%c!X>9Bj(lc7Ml`O4k#-g)hb7mnM5B$DB{ zqtJ!qddykDd!M`8V~_6kRi_t?iB$Seqrk!-@%%SWy|?LDUY&Oo$aVe633q!iokf1| zNGhh5BD1dMJ6J@46MGI8aK=Fe%L0`-v)&&~9!AkLVqu>|RJVz?gWI?xP?%RgAMONx zLT%=u%?V}YeMdnoqhNH3N509732M5H8lTAF(}_Yw(V(S+C@64WqSxjrcxGCM5C=3g z6uD>9pp6o3=XU|l;v78-Wt?Y3HGgNd#^gZg$fASglwS)5YjR3p^2#$) z#RXcbrizOx`z|iwGSRMZIWV4>xLWR;sFm5baw^6~S_>={?Jvmh!8G<^=$~NxD~tll OKy&UZ`L5B?Q2zx(l8Oxg literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions6/test.desc b/regression/exceptions/exceptions6/test.desc new file mode 100644 index 00000000000..79549d80731 --- /dev/null +++ b/regression/exceptions/exceptions6/test.desc @@ -0,0 +1,9 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 18 function.*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions6/test.java b/regression/exceptions/exceptions6/test.java new file mode 100644 index 00000000000..fd9a7fd5326 --- /dev/null +++ b/regression/exceptions/exceptions6/test.java @@ -0,0 +1,26 @@ +class A extends RuntimeException { + int i; + A() { + i = 1; + } +} +class B extends A {} +class C extends B {} + +public class test { + public static void main (String args[]) { + try { + try { + int i = 0; + throw new A(); + } + catch(A exc) { + assert exc.i==2; + } + } + catch(B exc) { + assert exc.i==2; + } + + } +} diff --git a/regression/exceptions/exceptions7/A.class b/regression/exceptions/exceptions7/A.class new file mode 100644 index 0000000000000000000000000000000000000000..963ae156be051ca07ea2d602053e012a3d27a7a4 GIT binary patch literal 241 zcmXX=O;5r=5PbuswY3W2=*gpUuorF+lg8kw;Q*%hZQaP2c5B)#@o#xD@!${OM-gX{ zNoL+h-b?0i{P_hi$0WiKR{^dAj0ygd4ckY;@a{e*cu&o%CX6#SdfnHBZeLVUi8IZb zQdPNX+3BSuQG(CW@UysN#6;bBCelyKv8QYrJ6YoqP1btzNpmRpEZ_t;J0Rp-H$s}9|kN*P*5s4yPo>K82_(?21 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions7/B.class b/regression/exceptions/exceptions7/B.class new file mode 100644 index 0000000000000000000000000000000000000000..47ae8f218e49b4ac942425d72a88b21c2772b518 GIT binary patch literal 216 zcmXX7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|NB-u+J+&n?qEXyU`Y_q(UxcfNDJ+wVWWegjZL&47s&9jgWud6o@mSV_acnvRDC zbP2BOcw}G$6&;TS3d>Fyx|^JHQyDmZztWBZ z&+qR@cF|=YyU9%9$f(Xpbw9>vL)JS%pL~UXlnZ3rk<)#5;JlBU(|&BSERfpm4kjjy z_HYz*-IgaMr=_Y5Da6DKEH-U&)lFoP6DUp<)_>1tKL~~aa~hN)i*-CPv5BgHHO+p} zId;1dXEcSH1CE!zdv53jZto8t6-Og};B1eu#0N6@fWj(D1&maX1s3;N-YPr=&&1jV z#5n^6dG5(85Cz8OB%Z@H-qM)Ibt1C(2eVb4tud6>7aZ*v8qdVR`lbB|$x~#;&3ni+mQr{NluuZl5 zD8>%<=ttHRaf8Y&^54V)cUgNY#!7K?n_su%Xd(98!W}G9!(FafBwy-S$~AP{liU3q oDP_~EQPkoBrsa(<$ecpg&Y-EEk^Fn6k}Uznd@3hj;zhxOUndZfg#Z8m literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions7/test.desc b/regression/exceptions/exceptions7/test.desc new file mode 100644 index 00000000000..e138e4349ec --- /dev/null +++ b/regression/exceptions/exceptions7/test.desc @@ -0,0 +1,9 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 21 function.*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions7/test.java b/regression/exceptions/exceptions7/test.java new file mode 100644 index 00000000000..e03be8a56fb --- /dev/null +++ b/regression/exceptions/exceptions7/test.java @@ -0,0 +1,25 @@ +class A extends RuntimeException {} +class B extends A {} +class C extends B {} + +public class test { + public static void main (String args[]) { + try { + try { + C c = new C(); + A a = new A(); + throw a; + } + catch(C exc) { + assert false; + } + catch(B exc) { + assert false; + } + } + catch(A exc) { + assert false; + } + + } +} diff --git a/regression/exceptions/exceptions8/A.class b/regression/exceptions/exceptions8/A.class new file mode 100644 index 0000000000000000000000000000000000000000..963ae156be051ca07ea2d602053e012a3d27a7a4 GIT binary patch literal 241 zcmXX=O;5r=5PbuswY3W2=*gpUuorF+lg8kw;Q*%hZQaP2c5B)#@o#xD@!${OM-gX{ zNoL+h-b?0i{P_hi$0WiKR{^dAj0ygd4ckY;@a{e*cu&o%CX6#SdfnHBZeLVUi8IZb zQdPNX+3BSuQG(CW@UysN#6;bBCelyKv8QYrJ6YoqP1btzNpmRpEZ_t;J0Rp-H$s}9|kN*P*5s4yPo>K82_(?21 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions8/B.class b/regression/exceptions/exceptions8/B.class new file mode 100644 index 0000000000000000000000000000000000000000..47ae8f218e49b4ac942425d72a88b21c2772b518 GIT binary patch literal 216 zcmXX7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|Nfgc5Ph3Cwd2@nJ|MJEXn<0Z6dFDX92y~#00-*AA*d4NQYh~Lsb z&~rheKqPwSMRbKYo7u4qycjOxUREsF_H}xuoNUi4>|PGPs%M zwydLWA}yDKU-GSFvP@4)<4S(pz4;7M?>V|^W4*H(L zwBrxG=X<+dFMKJ%3I!+Vxq}Ti^u?YywfK!6k;93-C|)JURuGW3OXRe~_CE9kw~6ge z?DpQSyYI%il+I$iu0K>LRbD$g?t8aBaEIIVP8|Bf?Nt$@TuE*+S#!f}7ApQHki*~* z6pTi1Floi?1bbo6d+Lkuv}juvehWF|$=c#-b2TlTL*7Cb(+V@E3YvdL^&|{~ki~^T z$BKn}xUY~qjeODF@p>`Gb?RylIBE9O_aZ;^`X^lMKHlR6$GnNld?=d_s&X?@ok#_5ZRp+UArfNq}hXe@}xljFe;ta7h!DmsTWk@IVNb(k=6FjpcBwigMxmG(~OEwP2 z@g_``N{-n|{5O(m@VChK$&k~g9APh!!Qh&~EUgUDd0ZfxlWdliWSexUiMU15gY6iUnxQ0{lCo@a zjxy#cs!T!4v_x!;Eg8%#bFPX}S>DYOmB&bYGSMrz%2OJ!psnjz$hLG`%QAEEWOOUz iSRh}>e1^3TT|0o5`~>6QHxQx}64oPmsp~WnsQdzqm68qs literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions8/test.desc b/regression/exceptions/exceptions8/test.desc new file mode 100644 index 00000000000..a400cbb8d02 --- /dev/null +++ b/regression/exceptions/exceptions8/test.desc @@ -0,0 +1,9 @@ +CORE +test.class + +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 23 function.*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions8/test.java b/regression/exceptions/exceptions8/test.java new file mode 100644 index 00000000000..7d6af5324b7 --- /dev/null +++ b/regression/exceptions/exceptions8/test.java @@ -0,0 +1,29 @@ +class A extends RuntimeException {} +class B extends A {} +class C extends B {} + +public class test { + static void foo() { + try { + B b = new B(); + throw b; + } + catch(C exc) { + int i=0; + } + } + + public static void main (String args[]) { + try { + A a = new A(); + foo(); + throw a; + } + catch(B exc) { + assert false; + } + catch(A exc) { + assert false; + } + } +} diff --git a/regression/exceptions/exceptions9/A.class b/regression/exceptions/exceptions9/A.class new file mode 100644 index 0000000000000000000000000000000000000000..ad46eafd1d9234e74590cd579aff0f7eb17f9bfd GIT binary patch literal 276 zcmXYrK}*9x5QX2QYh%`EYxU&GqxN7g9t4X}N((~ppwjy`F1nI#B;AOA%Yz6W`UCt? z#h2Q{%$xaU9y7n|pA~>h9BU|a6SQy`qZi{yAdYb>Xb+ut;YQFpJD&;ExO}pLPUgJ5 zs~2-yJ(_tz(#y)+6f;w~rr$ypUfhz_Y;-Nq4`p5DcIuk-B-mxRcs1`PMU34PJ81LZ zNO01?L1Fy!;J)_3E$rkYw{O9f9;f_J@nd1ou&wAPN!VQ>+RSwS8`4)_h(1XpXl6}q ToQk@~D*fN2?r-=3bA-+x##1h8 literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions9/B.class b/regression/exceptions/exceptions9/B.class new file mode 100644 index 0000000000000000000000000000000000000000..3af09687e1afeb9c7dd88272ec5fde0e48c3b12d GIT binary patch literal 216 zcmXX7D18_mM(%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN#-1 z8r4~qd>RHzf_up8B9S}Q#GOi()$Af}!h->mKmlWe5j6hZ6ftK{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|Nl=Sil_%DO3#1TF~TuIf(&WNkYe* zfvN=q6^oIpNv0W@w{Q*D4J-)cCY>;JgUIu{;e9W38XdPKAT|UNOJ3KD?h3?8<#hpl z)o-~1gLSX#KHk}GxWO|C7Rc89rqfw>0#EwApdP*ULUPn2H;fj^@yhqfQL2?|WOo>- zFEcC}wA^=1>90tCiyslGwa961J#yYCI`+f2+m6>2$d_K$H=Vamwc~W#)wL+_y6r`! z&k5SBnEOwfa}h9?nw?%l)|$T)G~I`ul%JFe=Om?#42D>Lncs?yGzM+lz^Fi>UvT+k zSPz204{V%6fzl*}ftxmN;kH1g4}a3wbej?RJWj43UhQz`?4{*~Uf{M)N!fL@!vrV3 zfpIP@#qEkrL299;gX9?EnWb0dEqKQ(2N3%-G~{?DRM5m3+V(L3XOX98O0|s0#~+E- zc+VGikvfF-;(!~NJ?dNa&xr3LH~SR{{R0LLVGv>->7Nv3fkZlDs^A2PL9IH~%BiJU zAkR#J<%W4yQB-0oMA$4kOrO2eI|^7$T$eZ|(_iuV<9nq$*?f{UDyEMaoQX-qRSN$M$-Fr$Qy5oZ!}EL1i# zqJ#ovBB#__@R!n_8ko)#I&->{1yu|f$_{*ky$eI%gC6^W_`mxZBTpQfeNS$&L`OsU E51X%=N&o-= literal 0 HcmV?d00001 diff --git a/regression/exceptions/exceptions9/test.desc b/regression/exceptions/exceptions9/test.desc new file mode 100644 index 00000000000..dc5ca4fa5cb --- /dev/null +++ b/regression/exceptions/exceptions9/test.desc @@ -0,0 +1,8 @@ +CORE +test.class + +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/regression/exceptions/exceptions9/test.java b/regression/exceptions/exceptions9/test.java new file mode 100644 index 00000000000..53f7838fd03 --- /dev/null +++ b/regression/exceptions/exceptions9/test.java @@ -0,0 +1,39 @@ +class A extends RuntimeException { + int i=1; +}; + +class B extends A { +}; + +public class test { + static int foo(int k) { + try { + if(k==0) + { + A a = new A(); + throw a; + } + else + { + A b = new A(); + throw b; + } + + } + catch(B exc) { + assert exc.i==1; + } + return 1; + } + + + public static void main (String args[]) { + try { + A a = new A(); + foo(6); + } + catch(A exc) { + assert exc.i==1; + } + } +} From 1aafb6103b2b0b14fd7f7e2a4b2216143a74c96b Mon Sep 17 00:00:00 2001 From: Cristina Date: Wed, 8 Feb 2017 17:26:27 +0000 Subject: [PATCH 17/67] Recreate the try-catch structure from the exception table - Adjust the working set conversion algorithm from bytecode to codet to also handler exception handlers. - Use CATCH-PUSH and CATCH-POP expressions to recreate the try-catch blocks. --- .../java_bytecode_convert_method.cpp | 225 ++++++++++++++++-- .../java_bytecode_convert_method_class.h | 1 + 2 files changed, 201 insertions(+), 25 deletions(-) diff --git a/src/java_bytecode/java_bytecode_convert_method.cpp b/src/java_bytecode/java_bytecode_convert_method.cpp index f101d19c824..69d4dffd04f 100644 --- a/src/java_bytecode/java_bytecode_convert_method.cpp +++ b/src/java_bytecode/java_bytecode_convert_method.cpp @@ -108,6 +108,13 @@ exprt::operandst java_bytecode_convert_methodt::pop(std::size_t n) return operands; } +void java_bytecode_convert_methodt::pop_residue(std::size_t n) +{ + std::size_t residue_size=n<=stack.size()?n:stack.size(); + + stack.resize(stack.size()-residue_size); +} + void java_bytecode_convert_methodt::push(const exprt::operandst &o) { stack.resize(stack.size()+o.size()); @@ -169,7 +176,6 @@ const exprt java_bytecode_convert_methodt::variable( symbol_exprt result(identifier, t); result.set(ID_C_base_name, base_name); used_local_names.insert(result); - return result; } else @@ -866,6 +872,24 @@ codet java_bytecode_convert_methodt::convert_instructions( a_entry.first->second.successors.push_back(next->address); } + if(i_it->statement=="athrow" || + i_it->statement=="invokestatic" || + i_it->statement=="invokevirtual") + { + // find the corresponding try-catch blocks and add the handlers + // to the targets + for(std::size_t e=0; eaddress>=method.exception_table[e].start_pc && + i_it->addresssecond.successors.push_back( + method.exception_table[e].handler_pc); + targets.insert(method.exception_table[e].handler_pc); + } + } + } + if(i_it->statement=="goto" || i_it->statement==patternt("if_?cmp??") || i_it->statement==patternt("if??") || @@ -943,7 +967,6 @@ codet java_bytecode_convert_methodt::convert_instructions( setup_local_variables(method, address_map); std::set working_set; - bool assertion_failure=false; if(!instructions.empty()) working_set.insert(instructions.front().address); @@ -953,6 +976,7 @@ codet java_bytecode_convert_methodt::convert_instructions( std::set::iterator cur=working_set.begin(); address_mapt::iterator a_it=address_map.find(*cur); assert(a_it!=address_map.end()); + unsigned cur_pc=*cur; working_set.erase(cur); if(a_it->second.done) @@ -989,6 +1013,46 @@ codet java_bytecode_convert_methodt::convert_instructions( statement=std::string(id2string(statement), 0, statement.size()-2); } + // we throw away the first statement in an exception handler + // as we don't know if a function call had a normal or exceptional return + size_t e; + for(e=0; eaddress, + false); + + // throw away the operands + pop_residue(bytecode_info.pop); + + // add a CATCH-PUSH signaling a handler + side_effect_expr_catcht catch_handler_expr; + // pack the exception variable so that it can be used + // later for instrumentation + catch_handler_expr.set(ID_handler, exc_var); + codet catch_handler=code_expressiont(catch_handler_expr); + + code_labelt newlabel(label(i2string(cur_pc)), code_blockt()); + code_blockt label_block=to_code_block(newlabel.code()); + code_blockt handler_block; + handler_block.move_to_operands(c); + handler_block.move_to_operands(catch_handler); + handler_block.move_to_operands(label_block); + c=handler_block; + + break; + } + } + + if(esource_location; - throw_expr.copy_to_operands(op[0]); - c=code_expressiont(throw_expr); - results[0]=op[0]; - } - else - { - // TODO: this can be removed once we properly handle throw - // if this athrow is generated by an assertion, then skip it - c=code_skipt(); - assertion_failure=false; - } + side_effect_expr_throwt throw_expr; + throw_expr.add_source_location()=i_it->source_location; + throw_expr.copy_to_operands(op[0]); + c=code_expressiont(throw_expr); + results[0]=op[0]; } else if(statement=="checkcast") { @@ -1061,14 +1115,7 @@ codet java_bytecode_convert_methodt::convert_instructions( statement=="invokevirtual" || statement=="invokestatic") { - // Remember that this is triggered by an assertion - if(statement=="invokespecial" && - id2string(arg0.get(ID_identifier)) - .find("AssertionError")!=std::string::npos) - { - assertion_failure=true; - } - const bool use_this(statement!="invokestatic"); + const bool use_this(statement != "invokestatic"); const bool is_virtual( statement=="invokevirtual" || statement=="invokeinterface"); @@ -1992,6 +2039,134 @@ codet java_bytecode_convert_methodt::convert_instructions( c.operands()=op; } + // next we do the exception handling + std::vector exception_ids; + std::vector handler_labels; + + // add the CATCH-PUSH instruction(s) + // be aware of different try-catch blocks with the same starting pc + std::size_t pos=0; + int end_pc=-1; + while(possource_location.get_line().empty()) c.add_source_location()=i_it->source_location; diff --git a/src/java_bytecode/java_bytecode_convert_method_class.h b/src/java_bytecode/java_bytecode_convert_method_class.h index ae4ba711640..4fb24c47b84 100644 --- a/src/java_bytecode/java_bytecode_convert_method_class.h +++ b/src/java_bytecode/java_bytecode_convert_method_class.h @@ -141,6 +141,7 @@ class java_bytecode_convert_methodt:public messaget exprt::operandst pop(std::size_t n); + void pop_residue(std::size_t n); void push(const exprt::operandst &o); bool is_constructor(const class_typet::methodt &method); From b9283bbd14e445d161aae284e4161574d0ad4636 Mon Sep 17 00:00:00 2001 From: Cristina Date: Wed, 14 Dec 2016 15:24:53 +0000 Subject: [PATCH 18/67] Remove throw/try-catch and add the required instrumentation For each function f we record its exceptional return value as variable f#exception_value and each throw/function call is instrumented with assignments involving these variables. Then, the dynamic dispatch of exception handlers is done by using instanceof over such variables. --- regression/exceptions/exceptions1/test.desc | 2 +- .../exceptions/exceptions15/InetAddress.class | Bin 0 -> 251 bytes .../exceptions15/InetSocketAddress.class | Bin 0 -> 263 bytes regression/exceptions/exceptions15/test.class | Bin 0 -> 1006 bytes regression/exceptions/exceptions15/test.desc | 8 + regression/exceptions/exceptions15/test.java | 20 + regression/exceptions/exceptions2/test.desc | 2 +- regression/exceptions/exceptions4/test.class | Bin 743 -> 914 bytes regression/exceptions/exceptions4/test.java | 2 + regression/exceptions/exceptions5/test.class | Bin 997 -> 1198 bytes regression/exceptions/exceptions5/test.java | 45 +- src/cbmc/cbmc_parse_options.cpp | 3 + .../goto_analyzer_parse_options.cpp | 3 + .../goto_instrument_parse_options.cpp | 3 + src/goto-programs/Makefile | 4 +- src/goto-programs/goto_convert.cpp | 80 +++ src/goto-programs/goto_convert_class.h | 4 + src/goto-programs/goto_convert_exceptions.cpp | 67 ++ .../goto_convert_side_effect.cpp | 25 + src/goto-programs/remove_exceptions.cpp | 586 ++++++++++++++++++ src/goto-programs/remove_exceptions.h | 24 + .../java_bytecode_convert_method.cpp | 132 ++-- src/symex/symex_parse_options.cpp | 4 + src/util/irep_ids.txt | 1 - src/util/std_code.h | 1 - 25 files changed, 936 insertions(+), 80 deletions(-) create mode 100644 regression/exceptions/exceptions15/InetAddress.class create mode 100644 regression/exceptions/exceptions15/InetSocketAddress.class create mode 100644 regression/exceptions/exceptions15/test.class create mode 100644 regression/exceptions/exceptions15/test.desc create mode 100644 regression/exceptions/exceptions15/test.java create mode 100644 src/goto-programs/remove_exceptions.cpp create mode 100644 src/goto-programs/remove_exceptions.h diff --git a/regression/exceptions/exceptions1/test.desc b/regression/exceptions/exceptions1/test.desc index baf72e7da81..7c6146907d0 100644 --- a/regression/exceptions/exceptions1/test.desc +++ b/regression/exceptions/exceptions1/test.desc @@ -4,7 +4,7 @@ test.class ^EXIT=10$ ^SIGNAL=0$ ^.*assertion at file test.java line 26 function.*: FAILURE$ -\*\* 1 of 35 failed (2 iterations)$ +\*\* 1 of 4 failed (2 iterations)$ ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/regression/exceptions/exceptions15/InetAddress.class b/regression/exceptions/exceptions15/InetAddress.class new file mode 100644 index 0000000000000000000000000000000000000000..3229324e624dde300b6b541750ba938c64539274 GIT binary patch literal 251 zcmYjL%L>9k44i0fwbloIfk*XVFWwYE1VJczP`q#3MOSJI?dpGd5RBA;vM9y`caxp-NG_CFtZ7;3;Za4qX5S)!MscHOZ`v-bd56#7!QV>B9f*vg1Uy?gsTsgIcyWh>;*9Bn6Ea5_wy;6I@t#$?TN)8~h3U z0bWHDNHo!Rf0Xe|S=)kXI(O#YbI+N3W`F$_|cZHLUYcNw*C;NIJq%NwVKMc%#)@86=7l6Vr{gSn8!_ zQ^_=4m}%_!hkiZs-_(AvzwRHjhohYWg~cGs>~S}fmI~x*Xv`>@dFRY1 z9!eObd8> zu`tXv-%i>nbMKu4FoG*Q(MD9bn&#(>7Gth#ePQTr&9_@C=jE)GKwQNbn}l&HBYBpQ zShJTo+#U|A!(nweZlIcRd?vHa8;sX#v!}?N!rnMWdE+bcN9g|n=lvN9zfK4ST$<2F zxS6uT9cYCS8sJ1FW~&r3Q`bmX;%^)`i6(XD0^`{QOzswLbHoYO9a!rQ?vzl#-HyBS jZAoCbTs(z)1jjyxo%@FT|4ti@K3LvMLsZm5udj0q%O9*WOr-yukZ(W z1`{xn$h$wvc%~qP$WC_VyMO09Gr#}*`~_ecbrVx4X_z+=QD@n}0xCMnCKhqafQ2Ou zRTBnEI_5RhOx(sD4R-~y1v?0&A3B~JJa+=SGmt$2u`Up=JFXKx6^ND>)&ycruO|hP zEytB_M#GNu->YDOOv~%qgEiZClzwcCg`b>&HCmwz!WCu@ZO0YJmp`^P>@Rk0V7vWV zJMKnK@ufXvjqJF_S+jt)se%S%EmuCD zwB%{;=785oetR--eAznzO^(759lXPJ%<&;i@xh4Hv>KCA6hg7VJxi^|Q}CRq>_hBO zh~NVE_>mDg%GR-*$3TvUff@Nl@FP*XWFu4USwvAZyJM{nQ Rm}S@mBGxlST7gOg#lQE)sVM*e delta 439 zcmZWlOG*Pl6s(?K&(AoCzeFcv)G=zJ1|$av<4yu@bvcR%L0pO3oIwX%?DK4x$40NOZo;bK!_%Y~+V?7+shMBRm@@Q#aJ>`62p zl20S1E-Q(8Fo%MGNO+HZc<{3`5m%Z%_HiH(^wRsZb(7v+w@xp5SC@C$Otkwp>i{As zD?K9}0!%|YPt>9p^k!oWF=C)0ptXKT6dC)!aS01V4i>RQMty#wTBDC9(9XxuyUl6$ z8Rh`q1QrQ79ine^N4ZGNYf$VWB-ZmX5hNL#$06_K9afk+WPepERQVdUHh(N*g=Iay zlu^lBim-|`Dnec##)(9=kVr%-}2OhKRI6MW_e zcm@+lY$ES|lyRK_Aw)8nv)4ZRa`s;PoZo+b{sPdCIUTJSQ1L=XK*~WKij+e-!cq?F z&@d3e2u3yOG=`TEG-F)FgpO+%&@iZBNW-v-NgWwvRpbPkJ51NL9M7&++$q~N3ngn! zKr9P{$LxyjjSB=*-HQTBuDWIkMDupVny-}$mh(Y63&iu)qFGur9b4*Wn~Jw#yUdaI zEY}-lblJ2k0*Tbe{HD2Wrb}jJJ-y&Lc4d83W*0m(n4hAjC`y!*s31{RB2%J_L_9EP zeUUzY+jUKx0eHwF^8E|9$FCi9QSX~(HLY*{8$@z%gB@&d67&v%7Q ztLR?wkD_m$wDfE$LJuy{)OM*^OSDohxzP z9K@RC+K#n$UNjl=YBX@z%V_7lY2~F8v7~I1C6=9hmZ-0gz*SOcG0LUBO%8UL z^&6RyJbhv=joh^3KKY5!>j64gQIfb5U96xTDjxD2g?f-@r4ZtpK#w1h^HB$5SAEn) zw8M-&^phjn#UnhXe8N8gZ9_$Gf-gTUm#1>+lU+SKA8o%M1vJH*kI=FQRoRCU{DH>* S$1GEZ5HKd?Wq3{{fd0S!tketu delta 581 zcmZXRO-~b16o#LfX*=!hv=q=DdonxX zo}CGjK!S%KzIDn z8}6$|G??=!>~!`!)pwoUt?G+6JDYF!;-+8g&xs0ng_6a~3-C}o=_~PpU!12YsWwQ$@U@HFJxEGh`t?BX?@0A$`t?0BwEKB0Tq3| zv-Q7m%eAerp{oQ~LW^4MLooP$MkMN@-4Nwv`7IGy5n@gLhA6%kJxh9BMAMY%=Z44@ z^m>y4O|eVgQa)giP%@;6BZ_XzOEONLVOP;`-hgUXoL6>7XzvOE~ zZq*&DCeYZ)Ki3qd=E|VECwEHzkT7vXA~?Yu>(O_c{X4a7nZ%Et>R)o#J>R #include #include +#include #include #include #include @@ -894,6 +895,8 @@ bool cbmc_parse_optionst::process_goto_program( cmdline.isset("pointer-check")); // Java virtual functions -> explicit dispatch tables: remove_virtual_functions(symbol_table, goto_functions); + // remove catch and throw + remove_exceptions(symbol_table, goto_functions); // Similar removal of RTTI inspection: remove_instanceof(symbol_table, goto_functions); diff --git a/src/goto-analyzer/goto_analyzer_parse_options.cpp b/src/goto-analyzer/goto_analyzer_parse_options.cpp index 89d3d56731c..e462740c1cc 100644 --- a/src/goto-analyzer/goto_analyzer_parse_options.cpp +++ b/src/goto-analyzer/goto_analyzer_parse_options.cpp @@ -19,6 +19,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include #include +#include #include #include #include @@ -387,6 +388,8 @@ bool goto_analyzer_parse_optionst::process_goto_program( remove_function_pointers(goto_model, cmdline.isset("pointer-check")); // Java virtual functions -> explicit dispatch tables: remove_virtual_functions(goto_model); + // remove Java throw and catch + remove_exceptions(goto_model); // remove rtti remove_instanceof(goto_model); diff --git a/src/goto-instrument/goto_instrument_parse_options.cpp b/src/goto-instrument/goto_instrument_parse_options.cpp index 3cbbac3a55b..209a5daeed1 100644 --- a/src/goto-instrument/goto_instrument_parse_options.cpp +++ b/src/goto-instrument/goto_instrument_parse_options.cpp @@ -18,6 +18,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include #include +#include #include #include #include @@ -810,6 +811,8 @@ void goto_instrument_parse_optionst::do_indirect_call_and_rtti_removal( cmdline.isset("pointer-check")); status() << "Virtual function removal" << eom; remove_virtual_functions(symbol_table, goto_functions); + status() << "Catch and throw removal" << eom; + remove_exceptions(symbol_table, goto_functions); status() << "Java instanceof removal" << eom; remove_instanceof(symbol_table, goto_functions); } diff --git a/src/goto-programs/Makefile b/src/goto-programs/Makefile index d8cb835e4a8..d5cc5ea25eb 100644 --- a/src/goto-programs/Makefile +++ b/src/goto-programs/Makefile @@ -13,8 +13,8 @@ SRC = goto_convert.cpp goto_convert_function_call.cpp \ remove_unused_functions.cpp remove_vector.cpp \ wp.cpp goto_clean_expr.cpp safety_checker.cpp parameter_assignments.cpp \ compute_called_functions.cpp link_to_library.cpp \ - remove_returns.cpp osx_fat_reader.cpp remove_complex.cpp \ - goto_trace.cpp xml_goto_trace.cpp vcd_goto_trace.cpp \ + remove_returns.cpp remove_exceptions.cpp osx_fat_reader.cpp \ + remove_complex.cpp goto_trace.cpp xml_goto_trace.cpp vcd_goto_trace.cpp \ graphml_witness.cpp remove_virtual_functions.cpp \ class_hierarchy.cpp show_goto_functions.cpp get_goto_model.cpp \ slice_global_inits.cpp goto_inline_class.cpp class_identifier.cpp \ diff --git a/src/goto-programs/goto_convert.cpp b/src/goto-programs/goto_convert.cpp index a3124f3b898..58cf6666897 100644 --- a/src/goto-programs/goto_convert.cpp +++ b/src/goto-programs/goto_convert.cpp @@ -47,6 +47,85 @@ static bool is_empty(const goto_programt &goto_program) /*******************************************************************\ +Function: finish_catch_push_targets + + Inputs: + + Outputs: + + Purpose: Populate the CATCH instructions with the targets + corresponding to their associated labels + +\*******************************************************************/ + +static void finish_catch_push_targets(goto_programt &dest) +{ + std::map label_targets; + + // in the first pass collect the labels and the corresponding targets + Forall_goto_program_instructions(it, dest) + { + if(!it->labels.empty()) + { + for(auto label : it->labels) + // record the label and the corresponding target + label_targets.insert(std::make_pair(label, it)); + } + } + + // in the second pass set the targets + Forall_goto_program_instructions(it, dest) + { + if(it->is_catch()) + { + bool handler_added=true; + irept exceptions=it->code.find(ID_exception_list); + + if(exceptions.is_nil() && + it->code.has_operands()) + exceptions=it->code.op0().find(ID_exception_list); + + const irept::subt &exception_list=exceptions.get_sub(); + + if(!exception_list.empty()) + { + // in this case we have a CATCH_PUSH + irept handlers=it->code.find(ID_label); + if(handlers.is_nil() && + it->code.has_operands()) + handlers=it->code.op0().find(ID_label); + const irept::subt &handler_list=handlers.get_sub(); + + // some handlers may not have been converted (if there was no + // exception to be caught); in such a situation we abort + for(const auto &handler : handler_list) + { + if(label_targets.find(handler.id())==label_targets.end()) + { + handler_added=false; + break; + } + } + + if(!handler_added) + continue; + + for(const auto &handler : handler_list) + { + std::map::const_iterator handler_it= + label_targets.find(handler.id()); + assert(handler_it!=label_targets.end()); + // set the target + it->targets.push_back(handler_it->second); + } + } + } + } +} + +/******************************************************************* \ + Function: goto_convertt::finish_gotos Inputs: @@ -302,6 +381,7 @@ void goto_convertt::goto_convert_rec( finish_gotos(dest); finish_computed_gotos(dest); finish_guarded_gotos(dest); + finish_catch_push_targets(dest); } /*******************************************************************\ diff --git a/src/goto-programs/goto_convert_class.h b/src/goto-programs/goto_convert_class.h index feab8197046..05c35efa3c0 100644 --- a/src/goto-programs/goto_convert_class.h +++ b/src/goto-programs/goto_convert_class.h @@ -94,6 +94,9 @@ class goto_convertt:public messaget side_effect_exprt &expr, goto_programt &dest, bool result_is_used); + void remove_push_catch( + side_effect_exprt &expr, + goto_programt &dest); void remove_assignment( side_effect_exprt &expr, goto_programt &dest, @@ -237,6 +240,7 @@ class goto_convertt:public messaget void convert_msc_try_except(const codet &code, goto_programt &dest); void convert_msc_leave(const codet &code, goto_programt &dest); void convert_try_catch(const codet &code, goto_programt &dest); + void convert_java_try_catch(const codet &code, goto_programt &dest); void convert_CPROVER_try_catch(const codet &code, goto_programt &dest); void convert_CPROVER_try_finally(const codet &code, goto_programt &dest); void convert_CPROVER_throw(const codet &code, goto_programt &dest); diff --git a/src/goto-programs/goto_convert_exceptions.cpp b/src/goto-programs/goto_convert_exceptions.cpp index 8d04f3cca16..63f503e8a0b 100644 --- a/src/goto-programs/goto_convert_exceptions.cpp +++ b/src/goto-programs/goto_convert_exceptions.cpp @@ -128,6 +128,73 @@ void goto_convertt::convert_msc_leave( /*******************************************************************\ +Function: goto_convertt::convert_java_try_catch + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +void goto_convertt::convert_java_try_catch( + const codet &code, + goto_programt &dest) +{ + assert(!code.operands().empty()); + + // add the CATCH instruction to 'dest' + goto_programt::targett catch_instruction=dest.add_instruction(); + catch_instruction->make_catch(); + catch_instruction->code.set_statement(ID_catch); + catch_instruction->source_location=code.source_location(); + catch_instruction->function=code.source_location().get_function(); + + // the CATCH instruction is annotated with a list of exception IDs + const irept exceptions=code.op0().find(ID_exception_list); + if(exceptions.is_not_nil()) + { + irept::subt exceptions_sub=exceptions.get_sub(); + irept::subt &exception_list= + catch_instruction->code.add(ID_exception_list).get_sub(); + exception_list.resize(exceptions_sub.size()); + for(size_t i=0; icode.add(ID_label).get_sub(); + handlers_list.resize(handlers_sub.size()); + for(size_t i=0; icode.get_sub().resize(1); + catch_instruction->code.get_sub()[0]=code.op0().op0(); + } + + // add a SKIP target for the end of everything + goto_programt end; + goto_programt::targett end_target=end.add_instruction(); + end_target->make_skip(); + end_target->source_location=code.source_location(); + end_target->function=code.source_location().get_function(); + + // add the end-target + dest.destructive_append(end); +} + +/*******************************************************************\ + Function: goto_convertt::convert_try_catch Inputs: diff --git a/src/goto-programs/goto_convert_side_effect.cpp b/src/goto-programs/goto_convert_side_effect.cpp index f34ee9d03a0..dbebb856ec1 100644 --- a/src/goto-programs/goto_convert_side_effect.cpp +++ b/src/goto-programs/goto_convert_side_effect.cpp @@ -767,6 +767,29 @@ void goto_convertt::remove_statement_expression( /*******************************************************************\ +Function: goto_convertt::remove_push_catch + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +void goto_convertt::remove_push_catch( + side_effect_exprt &expr, + goto_programt &dest) +{ + // we only get here for ID_push_catch, which is only used for Java + convert_java_try_catch(code_expressiont(expr), dest); + + // the result can't be used, these are void + expr.make_nil(); +} + +/*******************************************************************\ + Function: goto_convertt::remove_side_effect Inputs: @@ -837,6 +860,8 @@ void goto_convertt::remove_side_effect( // the result can't be used, these are void expr.make_nil(); } + else if(statement==ID_push_catch) + remove_push_catch(expr, dest); else { error().source_location=expr.find_source_location(); diff --git a/src/goto-programs/remove_exceptions.cpp b/src/goto-programs/remove_exceptions.cpp new file mode 100644 index 00000000000..14700921e24 --- /dev/null +++ b/src/goto-programs/remove_exceptions.cpp @@ -0,0 +1,586 @@ +/*******************************************************************\ + +Module: Remove exception handling + +Author: Cristina David + +Date: December 2016 + +\*******************************************************************/ +#define DEBUG +#ifdef DEBUG +#include +#endif +#include + +#include +#include + +#include "remove_exceptions.h" + +class remove_exceptionst +{ + typedef std::vector> catch_handlerst; + typedef std::vector stack_catcht; + +public: + explicit remove_exceptionst(symbol_tablet &_symbol_table): + symbol_table(_symbol_table) + { + } + + void operator()( + goto_functionst &goto_functions); + +protected: + symbol_tablet &symbol_table; + + void add_exceptional_returns( + const goto_functionst::function_mapt::iterator &); + + void replace_throws( + const goto_functionst::function_mapt::iterator &); + + void instrument_function_calls( + const goto_functionst::function_mapt::iterator &); + + void instrument_exception_handlers( + const goto_functionst::function_mapt::iterator &); + + void add_gotos( + const goto_functionst::function_mapt::iterator &); + + void add_throw_gotos( + const goto_functionst::function_mapt::iterator &, + const goto_programt::instructionst::iterator &, + const stack_catcht &); + + void add_function_call_gotos( + const goto_functionst::function_mapt::iterator &, + const goto_programt::instructionst::iterator &, + const stack_catcht &); +}; + +/*******************************************************************\ + +Function: remove_exceptionst::add_exceptional_returns + +Inputs: + +Outputs: + +Purpose: adds exceptional return variables for every function that + may escape exceptions + +\*******************************************************************/ + +void remove_exceptionst::add_exceptional_returns( + const goto_functionst::function_mapt::iterator &func_it) +{ + const irep_idt &function_id=func_it->first; + goto_programt &goto_program=func_it->second.body; + + assert(symbol_table.has_symbol(function_id)); + const symbolt &function_symbol=symbol_table.lookup(function_id); + + // for now only add exceptional returns for Java + if(function_symbol.mode!=ID_java) + return; + + if(goto_program.empty()) + return; + + // We generate an exceptional return value for any function that has + // a throw or a function call. This can be improved by only considering + // function calls that may escape exceptions. However, this will + // require multiple passes. + bool add_exceptional_var=false; + Forall_goto_program_instructions(instr_it, goto_program) + if(instr_it->is_throw() || instr_it->is_function_call()) + { + add_exceptional_var=true; + break; + } + + if(add_exceptional_var) + { + // look up the function symbol + symbol_tablet::symbolst::iterator s_it= + symbol_table.symbols.find(function_id); + + assert(s_it!=symbol_table.symbols.end()); + + auxiliary_symbolt new_symbol; + new_symbol.is_static_lifetime=true; + new_symbol.module=function_symbol.module; + new_symbol.base_name=id2string(function_symbol.base_name)+EXC_SUFFIX; + new_symbol.name=id2string(function_symbol.name)+EXC_SUFFIX; + new_symbol.mode=function_symbol.mode; + new_symbol.type=typet(ID_pointer, empty_typet()); + symbol_table.add(new_symbol); + + // initialize the exceptional return with NULL + symbol_exprt lhs_expr_null=new_symbol.symbol_expr(); + exprt rhs_expr_null; + rhs_expr_null=null_pointer_exprt(pointer_typet(empty_typet())); + goto_programt::targett t_null= + goto_program.insert_before(goto_program.instructions.begin()); + t_null->make_assignment(); + t_null->source_location= + goto_program.instructions.begin()->source_location; + t_null->code=code_assignt( + lhs_expr_null, + rhs_expr_null); + t_null->function=function_id; + } + return; +} + +/*******************************************************************\ + +Function: remove_exceptionst::replace_throws + +Inputs: + +Outputs: + +Purpose: turns 'throw x' in function f into an assignment to f#exc_value + +\*******************************************************************/ + +void remove_exceptionst::replace_throws( + const goto_functionst::function_mapt::iterator &func_it) +{ + const irep_idt &function_id=func_it->first; + goto_programt &goto_program=func_it->second.body; + + if(goto_program.empty()) + return; + + Forall_goto_program_instructions(instr_it, goto_program) + { + if(instr_it->is_throw() && + symbol_table.has_symbol(id2string(function_id)+EXC_SUFFIX)) + { + assert(instr_it->code.operands().size()==1); + const symbolt &exc_symbol= + symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); + + // replace "throw x;" by "f#exception_value=x;" + symbol_exprt lhs_expr=exc_symbol.symbol_expr(); + // find the symbol corresponding to the thrown exceptions + exprt exc_expr=instr_it->code; + while(exc_expr.id()!=ID_symbol && exc_expr.has_operands()) + exc_expr=exc_expr.op0(); + + // add the assignment with the appropriate cast + code_assignt assignment(typecast_exprt(lhs_expr, exc_expr.type()), + exc_expr); + // now turn the `throw' into `assignment' + instr_it->type=ASSIGN; + instr_it->code=assignment; + } + } +} + +/*******************************************************************\ + +Function: remove_exceptionst::instrument_function_calls + +Inputs: + +Outputs: + +Purpose: after each function call g() in function f + adds f#exception_value=g#exception_value; + +\*******************************************************************/ + +void remove_exceptionst::instrument_function_calls( + const goto_functionst::function_mapt::iterator &func_it) +{ + const irep_idt &caller_id=func_it->first; + goto_programt &goto_program=func_it->second.body; + + if(goto_program.empty()) + return; + + Forall_goto_program_instructions(instr_it, goto_program) + { + if(instr_it->is_function_call()) + { + code_function_callt &function_call=to_code_function_call(instr_it->code); + const irep_idt &callee_id= + to_symbol_expr(function_call.function()).get_identifier(); + + // can exceptions escape? + if(symbol_table.has_symbol(id2string(callee_id)+EXC_SUFFIX) && + symbol_table.has_symbol(id2string(caller_id)+EXC_SUFFIX)) + { + const symbolt &callee= + symbol_table.lookup(id2string(callee_id)+EXC_SUFFIX); + const symbolt &caller= + symbol_table.lookup(id2string(caller_id)+EXC_SUFFIX); + + symbol_exprt rhs_expr=callee.symbol_expr(); + symbol_exprt lhs_expr=caller.symbol_expr(); + + goto_programt::targett t=goto_program.insert_after(instr_it); + t->make_assignment(); + t->source_location=instr_it->source_location; + t->code=code_assignt(lhs_expr, rhs_expr); + t->function=instr_it->function; + } + } + } +} + +/*******************************************************************\ + +Function: remove_exceptionst::instrument_exception_handlers + +Inputs: + +Outputs: + +Purpose: at the beginning of each handler in function f + adds exc=f#exception_value; f#exception_value=NULL; + +\*******************************************************************/ + +void remove_exceptionst::instrument_exception_handlers( + const goto_functionst::function_mapt::iterator &func_it) +{ + const irep_idt &function_id=func_it->first; + goto_programt &goto_program=func_it->second.body; + + if(goto_program.empty()) + return; + + Forall_goto_program_instructions(instr_it, goto_program) + { + // is this a handler + if(instr_it->type==CATCH && instr_it->code.has_operands()) + { + // retrieve the exception variable + const irept &exception=instr_it->code.op0(); + + if(symbol_table.has_symbol(id2string(function_id)+EXC_SUFFIX)) + { + const symbolt &function_symbol= + symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); + // next we reset the exceptional return to NULL + symbol_exprt lhs_expr_null=function_symbol.symbol_expr(); + exprt rhs_expr_null; + rhs_expr_null=null_pointer_exprt(pointer_typet(empty_typet())); + + // add the assignment + goto_programt::targett t_null=goto_program.insert_after(instr_it); + t_null->make_assignment(); + t_null->source_location=instr_it->source_location; + t_null->code=code_assignt( + lhs_expr_null, + rhs_expr_null); + t_null->function=instr_it->function; + + // add the assignment exc=f#exception_value + symbol_exprt rhs_expr_exc=function_symbol.symbol_expr(); + + const exprt &lhs_expr_exc=static_cast(exception); + goto_programt::targett t_exc=goto_program.insert_after(instr_it); + t_exc->make_assignment(); + t_exc->source_location=instr_it->source_location; + t_exc->code=code_assignt( + typecast_exprt(lhs_expr_exc, rhs_expr_exc.type()), + rhs_expr_exc); + t_exc->function=instr_it->function; + } + + instr_it->make_skip(); + } + } +} + +/*******************************************************************\ + +Function: remove_exceptionst::add_gotos_throw + +Inputs: + +Outputs: + +Purpose: instruments each throw with conditional GOTOS to the + corresponding exception handlers + +\*******************************************************************/ + +void remove_exceptionst::add_throw_gotos( + const goto_functionst::function_mapt::iterator &func_it, + const goto_programt::instructionst::iterator &instr_it, + const remove_exceptionst::stack_catcht &stack_catch) +{ + assert(instr_it->type==THROW); + + goto_programt &goto_program=func_it->second.body; + + assert(instr_it->code.operands().size()==1); + + // find the end of the function + goto_programt::targett end_function; + for(end_function=instr_it; + !end_function->is_end_function(); + end_function++) {} + if(end_function!=instr_it) + { + // jump to the end of the function + // this will appear after the GOTO-based dynamic dispatch below + goto_programt::targett t_end=goto_program.insert_after(instr_it); + t_end->make_goto(end_function); + t_end->source_location=instr_it->source_location; + t_end->function=instr_it->function; + } + + // add GOTOs implementing the dynamic dispatch of the + // exception handlers + for(std::size_t i=stack_catch.size(); i-->0;) + { + for(std::size_t j=stack_catch[i].size(); j-->0;) + { + goto_programt::targett new_state_pc= + stack_catch[i][j].second; + + // find handler + goto_programt::targett t_exc=goto_program.insert_after(instr_it); + t_exc->make_goto(new_state_pc); + t_exc->source_location=instr_it->source_location; + t_exc->function=instr_it->function; + + // use instanceof to check that this is the correct handler + symbol_typet type(stack_catch[i][j].first); + type_exprt expr(type); + // find the symbol corresponding to the caught exceptions + exprt exc_symbol=instr_it->code; + while(exc_symbol.id()!=ID_symbol) + exc_symbol=exc_symbol.op0(); + + binary_predicate_exprt check(exc_symbol, ID_java_instanceof, expr); + t_exc->guard=check; + } + } +} + +/*******************************************************************\ + +Function: remove_exceptionst::add_function_call_gotos + +Inputs: + +Outputs: + +Purpose: instruments each function call that may escape exceptions + with conditional GOTOS to the corresponding exception handlers + +\*******************************************************************/ + +void remove_exceptionst::add_function_call_gotos( + const goto_functionst::function_mapt::iterator &func_it, + const goto_programt::instructionst::iterator &instr_it, + const stack_catcht &stack_catch) +{ + assert(instr_it->type==FUNCTION_CALL); + + goto_programt &goto_program=func_it->second.body; + + // save the address of the next instruction + goto_programt::instructionst::iterator next_it=instr_it; + next_it++; + + code_function_callt &function_call=to_code_function_call(instr_it->code); + assert(function_call.function().id()==ID_symbol); + const irep_idt &callee_id= + to_symbol_expr(function_call.function()).get_identifier(); + + if(symbol_table.has_symbol(id2string(callee_id)+EXC_SUFFIX)) + { + // dynamic dispatch of the escaped exception + const symbolt &callee_exc_symbol= + symbol_table.lookup(id2string(callee_id)+EXC_SUFFIX); + symbol_exprt callee_exc=callee_exc_symbol.symbol_expr(); + + for(std::size_t i=stack_catch.size(); i-->0;) + { + for(std::size_t j=stack_catch[i].size(); j-->0;) + { + goto_programt::targett new_state_pc; + new_state_pc=stack_catch[i][j].second; + goto_programt::targett t_exc=goto_program.insert_after(instr_it); + t_exc->make_goto(new_state_pc); + t_exc->source_location=instr_it->source_location; + t_exc->function=instr_it->function; + // use instanceof to check that this is the correct handler + symbol_typet type(stack_catch[i][j].first); + type_exprt expr(type); + binary_predicate_exprt check_instanceof( + callee_exc, + ID_java_instanceof, + expr); + t_exc->guard=check_instanceof; + } + } + + // add a null check (so that instanceof can be applied) + equal_exprt eq_null( + callee_exc, + null_pointer_exprt(pointer_typet(empty_typet()))); + // jump to the next instruction + goto_programt::targett t_null=goto_program.insert_after(instr_it); + t_null->make_goto(next_it); + t_null->source_location=instr_it->source_location; + t_null->function=instr_it->function; + t_null->guard=eq_null; + } +} + +/*******************************************************************\ + +Function: remove_exceptionst::add_gotos + +Inputs: + +Outputs: + +Purpose: instruments each throw and function calls that may escape exceptions + with conditional GOTOS to the corresponding exception handlers + +\*******************************************************************/ + +void remove_exceptionst::add_gotos( + const goto_functionst::function_mapt::iterator &func_it) +{ + // Stack of try-catch blocks + stack_catcht stack_catch; + + goto_programt &goto_program=func_it->second.body; + + if(goto_program.empty()) + return; + Forall_goto_program_instructions(instr_it, goto_program) + { + // it's a CATCH but not a handler + if(instr_it->type==CATCH && !instr_it->code.has_operands()) + { + if(instr_it->targets.empty()) // pop + { + // pop from the stack if possible + if(!stack_catch.empty()) + { + stack_catch.pop_back(); + } + else + { +#ifdef DEBUG + std::cout << "Remove exceptions: empty stack" << std::endl; +#endif + } + } + else // push + { + remove_exceptionst::catch_handlerst exception; + stack_catch.push_back(exception); + remove_exceptionst::catch_handlerst &last_exception= + stack_catch.back(); + + // copy targets + const irept::subt &exception_list= + instr_it->code.find(ID_exception_list).get_sub(); + assert(exception_list.size()==instr_it->targets.size()); + + // Fill the map with the catch type and the target + unsigned i=0; + for(auto target : instr_it->targets) + { + last_exception.push_back( + std::make_pair(exception_list[i].id(), target)); + i++; + } + } + + instr_it->make_skip(); + } + else if(instr_it->type==THROW) + { + add_throw_gotos(func_it, instr_it, stack_catch); + } + else if(instr_it->type==FUNCTION_CALL) + { + add_function_call_gotos(func_it, instr_it, stack_catch); + } + } +} + + +/*******************************************************************\ + +Function: remove_exceptionst::operator() + +Inputs: + +Outputs: + +Purpose: + +\*******************************************************************/ + +void remove_exceptionst::operator()(goto_functionst &goto_functions) +{ + Forall_goto_functions(it, goto_functions) + { + add_exceptional_returns(it); + } + Forall_goto_functions(it, goto_functions) + { + instrument_exception_handlers(it); + add_gotos(it); + instrument_function_calls(it); + replace_throws(it); + } +} + +/*******************************************************************\ + +Function: remove_exceptions + +Inputs: + +Outputs: + +Purpose: removes throws/CATCH-POP/CATCH-PUSH + +\*******************************************************************/ + +void remove_exceptions( + symbol_tablet &symbol_table, + goto_functionst &goto_functions) +{ + remove_exceptionst remove_exceptions(symbol_table); + remove_exceptions(goto_functions); +} + +/*******************************************************************\ + +Function: remove_exceptions + +Inputs: + +Outputs: + +Purpose: removes throws/CATCH-POP/CATCH-PUSH + +\*******************************************************************/ + +void remove_exceptions(goto_modelt &goto_model) +{ + remove_exceptionst remove_exceptions(goto_model.symbol_table); + remove_exceptions(goto_model.goto_functions); +} diff --git a/src/goto-programs/remove_exceptions.h b/src/goto-programs/remove_exceptions.h new file mode 100644 index 00000000000..89162b5833d --- /dev/null +++ b/src/goto-programs/remove_exceptions.h @@ -0,0 +1,24 @@ +/*******************************************************************\ + +Module: Remove function exceptional returns + +Author: Cristina David + +Date: December 2016 + +\*******************************************************************/ + +#ifndef CPROVER_GOTO_PROGRAMS_REMOVE_EXCEPTIONS_H +#define CPROVER_GOTO_PROGRAMS_REMOVE_EXCEPTIONS_H + +#include + +#define EXC_SUFFIX "#exception_value" + +// Removes 'throw x' and CATCH-PUSH/CATCH-POP +// and adds the required instrumentation (GOTOs and assignments) + +void remove_exceptions(symbol_tablet &, goto_functionst &); +void remove_exceptions(goto_modelt &); + +#endif diff --git a/src/java_bytecode/java_bytecode_convert_method.cpp b/src/java_bytecode/java_bytecode_convert_method.cpp index 69d4dffd04f..19174326c6c 100644 --- a/src/java_bytecode/java_bytecode_convert_method.cpp +++ b/src/java_bytecode/java_bytecode_convert_method.cpp @@ -108,9 +108,21 @@ exprt::operandst java_bytecode_convert_methodt::pop(std::size_t n) return operands; } +/*******************************************************************\ + +Function: java_bytecode_convert_methodt::pop_residue + +Inputs: + +Outputs: + +Purpose: removes minimum(n, stack.size()) elements from the stack + +\*******************************************************************/ + void java_bytecode_convert_methodt::pop_residue(std::size_t n) { - std::size_t residue_size=n<=stack.size()?n:stack.size(); + std::size_t residue_size=std::min(n, stack.size()); stack.resize(stack.size()-residue_size); } @@ -804,8 +816,10 @@ static void gather_symbol_live_ranges( } } else + { forall_operands(it, e) gather_symbol_live_ranges(pc, *it, result); + } } /*******************************************************************\ @@ -874,18 +888,20 @@ codet java_bytecode_convert_methodt::convert_instructions( if(i_it->statement=="athrow" || i_it->statement=="invokestatic" || - i_it->statement=="invokevirtual") + i_it->statement=="invokevirtual" || + i_it->statement=="invokespecial" || + i_it->statement=="invokeinterface") { // find the corresponding try-catch blocks and add the handlers // to the targets - for(std::size_t e=0; eaddress>=method.exception_table[e].start_pc && - i_it->addressaddress>=exception_row.start_pc && + i_it->addresssecond.successors.push_back( - method.exception_table[e].handler_pc); - targets.insert(method.exception_table[e].handler_pc); + exception_row.handler_pc); + targets.insert(exception_row.handler_pc); } } } @@ -1023,7 +1039,7 @@ codet java_bytecode_convert_methodt::convert_instructions( exprt exc_var=variable( arg0, statement[0], i_it->address, - false); + NO_CAST); // throw away the operands pop_residue(bytecode_info.pop); @@ -1032,17 +1048,19 @@ codet java_bytecode_convert_methodt::convert_instructions( side_effect_expr_catcht catch_handler_expr; // pack the exception variable so that it can be used // later for instrumentation - catch_handler_expr.set(ID_handler, exc_var); + catch_handler_expr.get_sub().resize(1); + catch_handler_expr.get_sub()[0]=exc_var; + codet catch_handler=code_expressiont(catch_handler_expr); + code_labelt newlabel(label(std::to_string(cur_pc)), + code_blockt()); - code_labelt newlabel(label(i2string(cur_pc)), code_blockt()); code_blockt label_block=to_code_block(newlabel.code()); code_blockt handler_block; handler_block.move_to_operands(c); handler_block.move_to_operands(catch_handler); handler_block.move_to_operands(label_block); c=handler_block; - break; } } @@ -1065,11 +1083,30 @@ codet java_bytecode_convert_methodt::convert_instructions( else if(statement=="athrow") { assert(op.size()==1 && results.size()==1); + code_blockt block; + if(!disable_runtime_checks) + { + // TODO throw NullPointerException instead + const typecast_exprt lhs(op[0], pointer_typet(empty_typet())); + const exprt rhs(null_pointer_exprt(to_pointer_type(lhs.type()))); + const exprt not_equal_null( + binary_relation_exprt(lhs, ID_notequal, rhs)); + code_assertt check(not_equal_null); + check.add_source_location() + .set_comment("Throw null"); + check.add_source_location() + .set_property_class("null-pointer-exception"); + block.move_to_operands(check); + } + side_effect_expr_throwt throw_expr; throw_expr.add_source_location()=i_it->source_location; throw_expr.copy_to_operands(op[0]); c=code_expressiont(throw_expr); results[0]=op[0]; + + block.move_to_operands(c); + c=block; } else if(statement=="checkcast") { @@ -1115,7 +1152,7 @@ codet java_bytecode_convert_methodt::convert_instructions( statement=="invokevirtual" || statement=="invokestatic") { - const bool use_this(statement != "invokestatic"); + const bool use_this(statement!="invokestatic"); const bool is_virtual( statement=="invokevirtual" || statement=="invokeinterface"); @@ -2046,17 +2083,19 @@ codet java_bytecode_convert_methodt::convert_instructions( // add the CATCH-PUSH instruction(s) // be aware of different try-catch blocks with the same starting pc std::size_t pos=0; - int end_pc=-1; + size_t end_pc=0; while(possource_location.get_line().empty()) c.add_source_location()=i_it->source_location; @@ -2178,6 +2194,18 @@ codet java_bytecode_convert_methodt::convert_instructions( address_mapt::iterator a_it2=address_map.find(address); assert(a_it2!=address_map.end()); + // we don't worry about exception handlers as we don't load the + // operands from the stack anyway -- we keep explicit global + // exception variables + for(const auto &exception_row : method.exception_table) + { + if(address==exception_row.handler_pc) + { + stack.clear(); + break; + } + } + if(!stack.empty() && a_it2->second.predecessors.size()>1) { // copy into temporaries @@ -2242,8 +2270,6 @@ codet java_bytecode_convert_methodt::convert_instructions( } } - // TODO: add exception handlers from exception table - // review successor computation of athrow! code_blockt code; // Add anonymous locals to the symtab: diff --git a/src/symex/symex_parse_options.cpp b/src/symex/symex_parse_options.cpp index 2ed3fedc518..54aa9382759 100644 --- a/src/symex/symex_parse_options.cpp +++ b/src/symex/symex_parse_options.cpp @@ -32,6 +32,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include #include +#include #include #include @@ -369,6 +370,9 @@ bool symex_parse_optionst::process_goto_program(const optionst &options) remove_vector(goto_model); // Java virtual functions -> explicit dispatch tables: remove_virtual_functions(goto_model); + // Java throw and catch -> explicit exceptional return variables: + remove_exceptions(goto_model); + // Java instanceof -> clsid comparison: remove_instanceof(goto_model); rewrite_union(goto_model); adjust_float_expressions(goto_model); diff --git a/src/util/irep_ids.txt b/src/util/irep_ids.txt index 666556d4b78..066a5f831cc 100644 --- a/src/util/irep_ids.txt +++ b/src/util/irep_ids.txt @@ -739,7 +739,6 @@ java_instanceof java_super_method_call java_enum_static_unwind push_catch -handler string_constraint string_not_contains_constraint cprover_char_literal_func diff --git a/src/util/std_code.h b/src/util/std_code.h index ed1f8f28b74..eb7982f3bbd 100644 --- a/src/util/std_code.h +++ b/src/util/std_code.h @@ -1130,7 +1130,6 @@ class side_effect_expr_catcht:public side_effect_exprt inline side_effect_expr_catcht():side_effect_exprt(ID_push_catch) { } - // TODO: change to ID_catch inline explicit side_effect_expr_catcht(const irept &exception_list): side_effect_exprt(ID_push_catch) { From eb89cc51eb189a539f6b1e6d1e481d48c32341cf Mon Sep 17 00:00:00 2001 From: Cristina Date: Wed, 15 Feb 2017 14:20:28 +0000 Subject: [PATCH 19/67] Moved Java exceptions regression tests These tests are now under cbmc-java. --- .../cbmc-java/NullPointer3/NullPointer3.class | Bin 270 -> 380 bytes .../cbmc-java/NullPointer3/NullPointer3.java | 1 - regression/cbmc-java/NullPointer3/test.desc | 4 ++-- .../exceptions1/A.class | Bin .../exceptions1/B.class | Bin .../exceptions1/C.class | Bin .../exceptions1/D.class | Bin .../exceptions1/test.class | Bin .../exceptions1/test.desc | 2 +- .../exceptions1/test.java | 0 .../exceptions10/A.class | Bin .../exceptions10/B.class | Bin .../exceptions10/C.class | Bin .../exceptions10/test.class | Bin .../exceptions10/test.desc | 0 .../exceptions10/test.java | 0 .../exceptions11/A.class | Bin .../exceptions11/B.class | Bin .../exceptions11/test.class | Bin .../exceptions11/test.desc | 0 .../exceptions11/test.java | 0 .../exceptions12/A.class | Bin .../exceptions12/B.class | Bin .../exceptions12/C.class | Bin .../exceptions12/F.class | Bin .../exceptions12/test.class | Bin .../exceptions12/test.desc | 0 .../exceptions12/test.java | 0 .../exceptions13/A.class | Bin .../exceptions13/B.class | Bin .../exceptions13/C.class | Bin .../exceptions13/F.class | Bin .../exceptions13/test.class | Bin .../exceptions13/test.desc | 0 .../exceptions13/test.java | 0 .../exceptions14/A.class | Bin .../exceptions14/B.class | Bin .../exceptions14/C.class | Bin .../exceptions14/test.class | Bin .../exceptions14/test.desc | 0 .../exceptions14/test.java | 0 .../exceptions15/InetAddress.class | Bin .../exceptions15/InetSocketAddress.class | Bin .../exceptions15/test.class | Bin .../exceptions15/test.desc | 0 .../exceptions15/test.java | 0 .../exceptions16}/A.class | Bin .../exceptions16}/B.class | Bin .../exceptions16}/C.class | Bin regression/cbmc-java/exceptions16/test.class | Bin 0 -> 718 bytes regression/cbmc-java/exceptions16/test.desc | 9 ++++++++ regression/cbmc-java/exceptions16/test.java | 21 ++++++++++++++++++ .../exceptions2/A.class | Bin .../exceptions2}/B.class | Bin .../exceptions2}/C.class | Bin .../exceptions2/test.class | Bin .../exceptions2/test.desc | 2 +- .../exceptions2/test.java | 0 .../exceptions3/A.class | Bin .../exceptions3}/B.class | Bin .../exceptions3}/C.class | Bin .../exceptions3/test.class | Bin .../exceptions3/test.desc | 0 .../exceptions3/test.java | 0 .../exceptions4/A.class | Bin .../exceptions4}/B.class | Bin .../exceptions4}/C.class | Bin .../exceptions4/test.class | Bin .../exceptions4/test.desc | 0 .../exceptions4/test.java | 0 .../exceptions5/A.class | Bin .../exceptions5}/B.class | Bin .../exceptions5}/C.class | Bin .../exceptions5/D.class | Bin .../exceptions5/test.class | Bin .../exceptions5/test.desc | 0 .../exceptions5/test.java | 0 .../exceptions6/A.class | Bin .../exceptions6/B.class | Bin .../exceptions6/C.class | Bin .../exceptions6/D.class | Bin .../exceptions6/test.class | Bin .../exceptions6/test.desc | 0 .../exceptions6/test.java | 0 .../exceptions7}/A.class | Bin .../exceptions7}/B.class | Bin .../exceptions7}/C.class | Bin .../exceptions7/test.class | Bin .../exceptions7/test.desc | 0 .../exceptions7/test.java | 0 regression/cbmc-java/exceptions8/A.class | Bin 0 -> 241 bytes regression/cbmc-java/exceptions8/B.class | Bin 0 -> 216 bytes .../exceptions8}/C.class | Bin .../exceptions8/test.class | Bin .../exceptions8/test.desc | 0 .../exceptions8/test.java | 0 .../exceptions9/A.class | Bin .../exceptions9/B.class | Bin regression/cbmc-java/exceptions9/C.class | Bin 0 -> 216 bytes .../exceptions9/test.class | Bin .../exceptions9/test.desc | 0 .../exceptions9/test.java | 0 regression/exceptions/Makefile | 14 ------------ 103 files changed, 34 insertions(+), 19 deletions(-) rename regression/{exceptions => cbmc-java}/exceptions1/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions1/B.class (100%) rename regression/{exceptions => cbmc-java}/exceptions1/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions1/D.class (100%) rename regression/{exceptions => cbmc-java}/exceptions1/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions1/test.desc (80%) rename regression/{exceptions => cbmc-java}/exceptions1/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions10/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions10/B.class (100%) rename regression/{exceptions => cbmc-java}/exceptions10/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions10/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions10/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions10/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions11/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions11/B.class (100%) rename regression/{exceptions => cbmc-java}/exceptions11/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions11/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions11/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions12/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions12/B.class (100%) rename regression/{exceptions => cbmc-java}/exceptions12/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions12/F.class (100%) rename regression/{exceptions => cbmc-java}/exceptions12/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions12/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions12/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions13/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions13/B.class (100%) rename regression/{exceptions => cbmc-java}/exceptions13/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions13/F.class (100%) rename regression/{exceptions => cbmc-java}/exceptions13/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions13/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions13/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions14/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions14/B.class (100%) rename regression/{exceptions => cbmc-java}/exceptions14/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions14/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions14/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions14/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions15/InetAddress.class (100%) rename regression/{exceptions => cbmc-java}/exceptions15/InetSocketAddress.class (100%) rename regression/{exceptions => cbmc-java}/exceptions15/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions15/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions15/test.java (100%) rename regression/{exceptions/exceptions7 => cbmc-java/exceptions16}/A.class (100%) rename regression/{exceptions/exceptions2 => cbmc-java/exceptions16}/B.class (100%) rename regression/{exceptions/exceptions2 => cbmc-java/exceptions16}/C.class (100%) create mode 100644 regression/cbmc-java/exceptions16/test.class create mode 100644 regression/cbmc-java/exceptions16/test.desc create mode 100644 regression/cbmc-java/exceptions16/test.java rename regression/{exceptions => cbmc-java}/exceptions2/A.class (100%) rename regression/{exceptions/exceptions3 => cbmc-java/exceptions2}/B.class (100%) rename regression/{exceptions/exceptions3 => cbmc-java/exceptions2}/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions2/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions2/test.desc (79%) rename regression/{exceptions => cbmc-java}/exceptions2/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions3/A.class (100%) rename regression/{exceptions/exceptions4 => cbmc-java/exceptions3}/B.class (100%) rename regression/{exceptions/exceptions4 => cbmc-java/exceptions3}/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions3/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions3/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions3/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions4/A.class (100%) rename regression/{exceptions/exceptions5 => cbmc-java/exceptions4}/B.class (100%) rename regression/{exceptions/exceptions5 => cbmc-java/exceptions4}/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions4/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions4/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions4/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions5/A.class (100%) rename regression/{exceptions/exceptions7 => cbmc-java/exceptions5}/B.class (100%) rename regression/{exceptions/exceptions7 => cbmc-java/exceptions5}/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions5/D.class (100%) rename regression/{exceptions => cbmc-java}/exceptions5/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions5/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions5/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions6/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions6/B.class (100%) rename regression/{exceptions => cbmc-java}/exceptions6/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions6/D.class (100%) rename regression/{exceptions => cbmc-java}/exceptions6/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions6/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions6/test.java (100%) rename regression/{exceptions/exceptions8 => cbmc-java/exceptions7}/A.class (100%) rename regression/{exceptions/exceptions8 => cbmc-java/exceptions7}/B.class (100%) rename regression/{exceptions/exceptions8 => cbmc-java/exceptions7}/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions7/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions7/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions7/test.java (100%) create mode 100644 regression/cbmc-java/exceptions8/A.class create mode 100644 regression/cbmc-java/exceptions8/B.class rename regression/{exceptions/exceptions9 => cbmc-java/exceptions8}/C.class (100%) rename regression/{exceptions => cbmc-java}/exceptions8/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions8/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions8/test.java (100%) rename regression/{exceptions => cbmc-java}/exceptions9/A.class (100%) rename regression/{exceptions => cbmc-java}/exceptions9/B.class (100%) create mode 100644 regression/cbmc-java/exceptions9/C.class rename regression/{exceptions => cbmc-java}/exceptions9/test.class (100%) rename regression/{exceptions => cbmc-java}/exceptions9/test.desc (100%) rename regression/{exceptions => cbmc-java}/exceptions9/test.java (100%) delete mode 100644 regression/exceptions/Makefile diff --git a/regression/cbmc-java/NullPointer3/NullPointer3.class b/regression/cbmc-java/NullPointer3/NullPointer3.class index 8ad089310c3a7896b660934861b104537c1edd65..b79f5adef44f30757862ddef9c91c22f2700cf2a 100644 GIT binary patch delta 224 zcmeBU`oko8>ff$?3=9k=3?f_%%nX9;3_|P-!V^Wcw1s@~lM{2o5{ohulX6l+Km;QL zOG!p%F(U(?k6&p{PC$NUUP)?^vGqh-C25w#qI95)aI{ZWVp*boPGVlVesD=qW?s7W z#Ms0VeFjD#WME*`+RnhZ5y)U-Uff$?3=9k=4E$US%nUs247}_Nd=o{rCgvziTp1rA%fJYP3=FJV+Zh-) r0vU`9>_CzYEXc^f$-n``j6gmEgA|YkDP>~ZkEV_lD9#0vVc-S;HuwxN diff --git a/regression/cbmc-java/NullPointer3/NullPointer3.java b/regression/cbmc-java/NullPointer3/NullPointer3.java index 00004f14467..fa8b227dd94 100644 --- a/regression/cbmc-java/NullPointer3/NullPointer3.java +++ b/regression/cbmc-java/NullPointer3/NullPointer3.java @@ -4,5 +4,4 @@ public static void main(String[] args) { throw null; // NULL pointer dereference } - } diff --git a/regression/cbmc-java/NullPointer3/test.desc b/regression/cbmc-java/NullPointer3/test.desc index cc33c21738b..5dd14d8dfb9 100644 --- a/regression/cbmc-java/NullPointer3/test.desc +++ b/regression/cbmc-java/NullPointer3/test.desc @@ -1,9 +1,9 @@ CORE NullPointer3.class ---pointer-check --stop-on-fail +--pointer-check ^EXIT=10$ ^SIGNAL=0$ -^ file NullPointer3.java line 5 function java::NullPointer3.main:\(\[Ljava/lang/String;\)V bytecode_index 1$ +^.*Throw null: FAILURE$ ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/regression/exceptions/exceptions1/A.class b/regression/cbmc-java/exceptions1/A.class similarity index 100% rename from regression/exceptions/exceptions1/A.class rename to regression/cbmc-java/exceptions1/A.class diff --git a/regression/exceptions/exceptions1/B.class b/regression/cbmc-java/exceptions1/B.class similarity index 100% rename from regression/exceptions/exceptions1/B.class rename to regression/cbmc-java/exceptions1/B.class diff --git a/regression/exceptions/exceptions1/C.class b/regression/cbmc-java/exceptions1/C.class similarity index 100% rename from regression/exceptions/exceptions1/C.class rename to regression/cbmc-java/exceptions1/C.class diff --git a/regression/exceptions/exceptions1/D.class b/regression/cbmc-java/exceptions1/D.class similarity index 100% rename from regression/exceptions/exceptions1/D.class rename to regression/cbmc-java/exceptions1/D.class diff --git a/regression/exceptions/exceptions1/test.class b/regression/cbmc-java/exceptions1/test.class similarity index 100% rename from regression/exceptions/exceptions1/test.class rename to regression/cbmc-java/exceptions1/test.class diff --git a/regression/exceptions/exceptions1/test.desc b/regression/cbmc-java/exceptions1/test.desc similarity index 80% rename from regression/exceptions/exceptions1/test.desc rename to regression/cbmc-java/exceptions1/test.desc index 7c6146907d0..ca52107829c 100644 --- a/regression/exceptions/exceptions1/test.desc +++ b/regression/cbmc-java/exceptions1/test.desc @@ -4,7 +4,7 @@ test.class ^EXIT=10$ ^SIGNAL=0$ ^.*assertion at file test.java line 26 function.*: FAILURE$ -\*\* 1 of 4 failed (2 iterations)$ +\*\* 1 of 9 failed (2 iterations)$ ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/regression/exceptions/exceptions1/test.java b/regression/cbmc-java/exceptions1/test.java similarity index 100% rename from regression/exceptions/exceptions1/test.java rename to regression/cbmc-java/exceptions1/test.java diff --git a/regression/exceptions/exceptions10/A.class b/regression/cbmc-java/exceptions10/A.class similarity index 100% rename from regression/exceptions/exceptions10/A.class rename to regression/cbmc-java/exceptions10/A.class diff --git a/regression/exceptions/exceptions10/B.class b/regression/cbmc-java/exceptions10/B.class similarity index 100% rename from regression/exceptions/exceptions10/B.class rename to regression/cbmc-java/exceptions10/B.class diff --git a/regression/exceptions/exceptions10/C.class b/regression/cbmc-java/exceptions10/C.class similarity index 100% rename from regression/exceptions/exceptions10/C.class rename to regression/cbmc-java/exceptions10/C.class diff --git a/regression/exceptions/exceptions10/test.class b/regression/cbmc-java/exceptions10/test.class similarity index 100% rename from regression/exceptions/exceptions10/test.class rename to regression/cbmc-java/exceptions10/test.class diff --git a/regression/exceptions/exceptions10/test.desc b/regression/cbmc-java/exceptions10/test.desc similarity index 100% rename from regression/exceptions/exceptions10/test.desc rename to regression/cbmc-java/exceptions10/test.desc diff --git a/regression/exceptions/exceptions10/test.java b/regression/cbmc-java/exceptions10/test.java similarity index 100% rename from regression/exceptions/exceptions10/test.java rename to regression/cbmc-java/exceptions10/test.java diff --git a/regression/exceptions/exceptions11/A.class b/regression/cbmc-java/exceptions11/A.class similarity index 100% rename from regression/exceptions/exceptions11/A.class rename to regression/cbmc-java/exceptions11/A.class diff --git a/regression/exceptions/exceptions11/B.class b/regression/cbmc-java/exceptions11/B.class similarity index 100% rename from regression/exceptions/exceptions11/B.class rename to regression/cbmc-java/exceptions11/B.class diff --git a/regression/exceptions/exceptions11/test.class b/regression/cbmc-java/exceptions11/test.class similarity index 100% rename from regression/exceptions/exceptions11/test.class rename to regression/cbmc-java/exceptions11/test.class diff --git a/regression/exceptions/exceptions11/test.desc b/regression/cbmc-java/exceptions11/test.desc similarity index 100% rename from regression/exceptions/exceptions11/test.desc rename to regression/cbmc-java/exceptions11/test.desc diff --git a/regression/exceptions/exceptions11/test.java b/regression/cbmc-java/exceptions11/test.java similarity index 100% rename from regression/exceptions/exceptions11/test.java rename to regression/cbmc-java/exceptions11/test.java diff --git a/regression/exceptions/exceptions12/A.class b/regression/cbmc-java/exceptions12/A.class similarity index 100% rename from regression/exceptions/exceptions12/A.class rename to regression/cbmc-java/exceptions12/A.class diff --git a/regression/exceptions/exceptions12/B.class b/regression/cbmc-java/exceptions12/B.class similarity index 100% rename from regression/exceptions/exceptions12/B.class rename to regression/cbmc-java/exceptions12/B.class diff --git a/regression/exceptions/exceptions12/C.class b/regression/cbmc-java/exceptions12/C.class similarity index 100% rename from regression/exceptions/exceptions12/C.class rename to regression/cbmc-java/exceptions12/C.class diff --git a/regression/exceptions/exceptions12/F.class b/regression/cbmc-java/exceptions12/F.class similarity index 100% rename from regression/exceptions/exceptions12/F.class rename to regression/cbmc-java/exceptions12/F.class diff --git a/regression/exceptions/exceptions12/test.class b/regression/cbmc-java/exceptions12/test.class similarity index 100% rename from regression/exceptions/exceptions12/test.class rename to regression/cbmc-java/exceptions12/test.class diff --git a/regression/exceptions/exceptions12/test.desc b/regression/cbmc-java/exceptions12/test.desc similarity index 100% rename from regression/exceptions/exceptions12/test.desc rename to regression/cbmc-java/exceptions12/test.desc diff --git a/regression/exceptions/exceptions12/test.java b/regression/cbmc-java/exceptions12/test.java similarity index 100% rename from regression/exceptions/exceptions12/test.java rename to regression/cbmc-java/exceptions12/test.java diff --git a/regression/exceptions/exceptions13/A.class b/regression/cbmc-java/exceptions13/A.class similarity index 100% rename from regression/exceptions/exceptions13/A.class rename to regression/cbmc-java/exceptions13/A.class diff --git a/regression/exceptions/exceptions13/B.class b/regression/cbmc-java/exceptions13/B.class similarity index 100% rename from regression/exceptions/exceptions13/B.class rename to regression/cbmc-java/exceptions13/B.class diff --git a/regression/exceptions/exceptions13/C.class b/regression/cbmc-java/exceptions13/C.class similarity index 100% rename from regression/exceptions/exceptions13/C.class rename to regression/cbmc-java/exceptions13/C.class diff --git a/regression/exceptions/exceptions13/F.class b/regression/cbmc-java/exceptions13/F.class similarity index 100% rename from regression/exceptions/exceptions13/F.class rename to regression/cbmc-java/exceptions13/F.class diff --git a/regression/exceptions/exceptions13/test.class b/regression/cbmc-java/exceptions13/test.class similarity index 100% rename from regression/exceptions/exceptions13/test.class rename to regression/cbmc-java/exceptions13/test.class diff --git a/regression/exceptions/exceptions13/test.desc b/regression/cbmc-java/exceptions13/test.desc similarity index 100% rename from regression/exceptions/exceptions13/test.desc rename to regression/cbmc-java/exceptions13/test.desc diff --git a/regression/exceptions/exceptions13/test.java b/regression/cbmc-java/exceptions13/test.java similarity index 100% rename from regression/exceptions/exceptions13/test.java rename to regression/cbmc-java/exceptions13/test.java diff --git a/regression/exceptions/exceptions14/A.class b/regression/cbmc-java/exceptions14/A.class similarity index 100% rename from regression/exceptions/exceptions14/A.class rename to regression/cbmc-java/exceptions14/A.class diff --git a/regression/exceptions/exceptions14/B.class b/regression/cbmc-java/exceptions14/B.class similarity index 100% rename from regression/exceptions/exceptions14/B.class rename to regression/cbmc-java/exceptions14/B.class diff --git a/regression/exceptions/exceptions14/C.class b/regression/cbmc-java/exceptions14/C.class similarity index 100% rename from regression/exceptions/exceptions14/C.class rename to regression/cbmc-java/exceptions14/C.class diff --git a/regression/exceptions/exceptions14/test.class b/regression/cbmc-java/exceptions14/test.class similarity index 100% rename from regression/exceptions/exceptions14/test.class rename to regression/cbmc-java/exceptions14/test.class diff --git a/regression/exceptions/exceptions14/test.desc b/regression/cbmc-java/exceptions14/test.desc similarity index 100% rename from regression/exceptions/exceptions14/test.desc rename to regression/cbmc-java/exceptions14/test.desc diff --git a/regression/exceptions/exceptions14/test.java b/regression/cbmc-java/exceptions14/test.java similarity index 100% rename from regression/exceptions/exceptions14/test.java rename to regression/cbmc-java/exceptions14/test.java diff --git a/regression/exceptions/exceptions15/InetAddress.class b/regression/cbmc-java/exceptions15/InetAddress.class similarity index 100% rename from regression/exceptions/exceptions15/InetAddress.class rename to regression/cbmc-java/exceptions15/InetAddress.class diff --git a/regression/exceptions/exceptions15/InetSocketAddress.class b/regression/cbmc-java/exceptions15/InetSocketAddress.class similarity index 100% rename from regression/exceptions/exceptions15/InetSocketAddress.class rename to regression/cbmc-java/exceptions15/InetSocketAddress.class diff --git a/regression/exceptions/exceptions15/test.class b/regression/cbmc-java/exceptions15/test.class similarity index 100% rename from regression/exceptions/exceptions15/test.class rename to regression/cbmc-java/exceptions15/test.class diff --git a/regression/exceptions/exceptions15/test.desc b/regression/cbmc-java/exceptions15/test.desc similarity index 100% rename from regression/exceptions/exceptions15/test.desc rename to regression/cbmc-java/exceptions15/test.desc diff --git a/regression/exceptions/exceptions15/test.java b/regression/cbmc-java/exceptions15/test.java similarity index 100% rename from regression/exceptions/exceptions15/test.java rename to regression/cbmc-java/exceptions15/test.java diff --git a/regression/exceptions/exceptions7/A.class b/regression/cbmc-java/exceptions16/A.class similarity index 100% rename from regression/exceptions/exceptions7/A.class rename to regression/cbmc-java/exceptions16/A.class diff --git a/regression/exceptions/exceptions2/B.class b/regression/cbmc-java/exceptions16/B.class similarity index 100% rename from regression/exceptions/exceptions2/B.class rename to regression/cbmc-java/exceptions16/B.class diff --git a/regression/exceptions/exceptions2/C.class b/regression/cbmc-java/exceptions16/C.class similarity index 100% rename from regression/exceptions/exceptions2/C.class rename to regression/cbmc-java/exceptions16/C.class diff --git a/regression/cbmc-java/exceptions16/test.class b/regression/cbmc-java/exceptions16/test.class new file mode 100644 index 0000000000000000000000000000000000000000..189317658cea5cab3e52e378ccf0809e28a7198b GIT binary patch literal 718 zcmZWl-A)rh7(KJQ-D#JllpL{WOy5=F+pcO~F+XCaec^JKW z5q>CWH~=*Zl-Hwpq{Z7!hH0d>wCP+is}Ty$=DyobxbiU;~J(}F`qvZZPB+sL7Z^k zUtk|&>>SSPGn6jQ;nK^Cf6AxD7n?0C5;b{TYBEh1NNyU~Z0S<9q~d8dYEs55>R4rK zBWR8Y$q8m~okC`ds8NV);|6XLaf{c7vn6r6`dp$}C9A<*%3dq5z+}Dr4V7a^=LC-Z V754x08=?{{|B2bs9VQm$egkzSbi@Dv literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/exceptions16/test.desc b/regression/cbmc-java/exceptions16/test.desc new file mode 100644 index 00000000000..960b995f7d3 --- /dev/null +++ b/regression/cbmc-java/exceptions16/test.desc @@ -0,0 +1,9 @@ +CORE +test.class +--function test.foo +^EXIT=10$ +^SIGNAL=0$ +^.*assertion at file test.java line 18 function.*: FAILURE$ +^VERIFICATION FAILED$ +-- +^warning: ignoring diff --git a/regression/cbmc-java/exceptions16/test.java b/regression/cbmc-java/exceptions16/test.java new file mode 100644 index 00000000000..9d1c2729516 --- /dev/null +++ b/regression/cbmc-java/exceptions16/test.java @@ -0,0 +1,21 @@ +class A extends RuntimeException {} +class B extends A {} +class C extends B {} + +public class test { + static void foo (int x) { + try { + x++; + } + catch(A exc) { + assert false; + } + + try { + throw new B(); + } + catch(B exc) { + assert false; + } + } +} diff --git a/regression/exceptions/exceptions2/A.class b/regression/cbmc-java/exceptions2/A.class similarity index 100% rename from regression/exceptions/exceptions2/A.class rename to regression/cbmc-java/exceptions2/A.class diff --git a/regression/exceptions/exceptions3/B.class b/regression/cbmc-java/exceptions2/B.class similarity index 100% rename from regression/exceptions/exceptions3/B.class rename to regression/cbmc-java/exceptions2/B.class diff --git a/regression/exceptions/exceptions3/C.class b/regression/cbmc-java/exceptions2/C.class similarity index 100% rename from regression/exceptions/exceptions3/C.class rename to regression/cbmc-java/exceptions2/C.class diff --git a/regression/exceptions/exceptions2/test.class b/regression/cbmc-java/exceptions2/test.class similarity index 100% rename from regression/exceptions/exceptions2/test.class rename to regression/cbmc-java/exceptions2/test.class diff --git a/regression/exceptions/exceptions2/test.desc b/regression/cbmc-java/exceptions2/test.desc similarity index 79% rename from regression/exceptions/exceptions2/test.desc rename to regression/cbmc-java/exceptions2/test.desc index 179b234c875..45f5bac3bc2 100644 --- a/regression/exceptions/exceptions2/test.desc +++ b/regression/cbmc-java/exceptions2/test.desc @@ -4,7 +4,7 @@ test.class ^EXIT=10$ ^SIGNAL=0$ ^.*assertion at file test.java line 15 function.*: FAILURE$ -^\*\* 1 of 2 failed (2 iterations)$ +^\*\* 1 of 5 failed (2 iterations)$ ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/regression/exceptions/exceptions2/test.java b/regression/cbmc-java/exceptions2/test.java similarity index 100% rename from regression/exceptions/exceptions2/test.java rename to regression/cbmc-java/exceptions2/test.java diff --git a/regression/exceptions/exceptions3/A.class b/regression/cbmc-java/exceptions3/A.class similarity index 100% rename from regression/exceptions/exceptions3/A.class rename to regression/cbmc-java/exceptions3/A.class diff --git a/regression/exceptions/exceptions4/B.class b/regression/cbmc-java/exceptions3/B.class similarity index 100% rename from regression/exceptions/exceptions4/B.class rename to regression/cbmc-java/exceptions3/B.class diff --git a/regression/exceptions/exceptions4/C.class b/regression/cbmc-java/exceptions3/C.class similarity index 100% rename from regression/exceptions/exceptions4/C.class rename to regression/cbmc-java/exceptions3/C.class diff --git a/regression/exceptions/exceptions3/test.class b/regression/cbmc-java/exceptions3/test.class similarity index 100% rename from regression/exceptions/exceptions3/test.class rename to regression/cbmc-java/exceptions3/test.class diff --git a/regression/exceptions/exceptions3/test.desc b/regression/cbmc-java/exceptions3/test.desc similarity index 100% rename from regression/exceptions/exceptions3/test.desc rename to regression/cbmc-java/exceptions3/test.desc diff --git a/regression/exceptions/exceptions3/test.java b/regression/cbmc-java/exceptions3/test.java similarity index 100% rename from regression/exceptions/exceptions3/test.java rename to regression/cbmc-java/exceptions3/test.java diff --git a/regression/exceptions/exceptions4/A.class b/regression/cbmc-java/exceptions4/A.class similarity index 100% rename from regression/exceptions/exceptions4/A.class rename to regression/cbmc-java/exceptions4/A.class diff --git a/regression/exceptions/exceptions5/B.class b/regression/cbmc-java/exceptions4/B.class similarity index 100% rename from regression/exceptions/exceptions5/B.class rename to regression/cbmc-java/exceptions4/B.class diff --git a/regression/exceptions/exceptions5/C.class b/regression/cbmc-java/exceptions4/C.class similarity index 100% rename from regression/exceptions/exceptions5/C.class rename to regression/cbmc-java/exceptions4/C.class diff --git a/regression/exceptions/exceptions4/test.class b/regression/cbmc-java/exceptions4/test.class similarity index 100% rename from regression/exceptions/exceptions4/test.class rename to regression/cbmc-java/exceptions4/test.class diff --git a/regression/exceptions/exceptions4/test.desc b/regression/cbmc-java/exceptions4/test.desc similarity index 100% rename from regression/exceptions/exceptions4/test.desc rename to regression/cbmc-java/exceptions4/test.desc diff --git a/regression/exceptions/exceptions4/test.java b/regression/cbmc-java/exceptions4/test.java similarity index 100% rename from regression/exceptions/exceptions4/test.java rename to regression/cbmc-java/exceptions4/test.java diff --git a/regression/exceptions/exceptions5/A.class b/regression/cbmc-java/exceptions5/A.class similarity index 100% rename from regression/exceptions/exceptions5/A.class rename to regression/cbmc-java/exceptions5/A.class diff --git a/regression/exceptions/exceptions7/B.class b/regression/cbmc-java/exceptions5/B.class similarity index 100% rename from regression/exceptions/exceptions7/B.class rename to regression/cbmc-java/exceptions5/B.class diff --git a/regression/exceptions/exceptions7/C.class b/regression/cbmc-java/exceptions5/C.class similarity index 100% rename from regression/exceptions/exceptions7/C.class rename to regression/cbmc-java/exceptions5/C.class diff --git a/regression/exceptions/exceptions5/D.class b/regression/cbmc-java/exceptions5/D.class similarity index 100% rename from regression/exceptions/exceptions5/D.class rename to regression/cbmc-java/exceptions5/D.class diff --git a/regression/exceptions/exceptions5/test.class b/regression/cbmc-java/exceptions5/test.class similarity index 100% rename from regression/exceptions/exceptions5/test.class rename to regression/cbmc-java/exceptions5/test.class diff --git a/regression/exceptions/exceptions5/test.desc b/regression/cbmc-java/exceptions5/test.desc similarity index 100% rename from regression/exceptions/exceptions5/test.desc rename to regression/cbmc-java/exceptions5/test.desc diff --git a/regression/exceptions/exceptions5/test.java b/regression/cbmc-java/exceptions5/test.java similarity index 100% rename from regression/exceptions/exceptions5/test.java rename to regression/cbmc-java/exceptions5/test.java diff --git a/regression/exceptions/exceptions6/A.class b/regression/cbmc-java/exceptions6/A.class similarity index 100% rename from regression/exceptions/exceptions6/A.class rename to regression/cbmc-java/exceptions6/A.class diff --git a/regression/exceptions/exceptions6/B.class b/regression/cbmc-java/exceptions6/B.class similarity index 100% rename from regression/exceptions/exceptions6/B.class rename to regression/cbmc-java/exceptions6/B.class diff --git a/regression/exceptions/exceptions6/C.class b/regression/cbmc-java/exceptions6/C.class similarity index 100% rename from regression/exceptions/exceptions6/C.class rename to regression/cbmc-java/exceptions6/C.class diff --git a/regression/exceptions/exceptions6/D.class b/regression/cbmc-java/exceptions6/D.class similarity index 100% rename from regression/exceptions/exceptions6/D.class rename to regression/cbmc-java/exceptions6/D.class diff --git a/regression/exceptions/exceptions6/test.class b/regression/cbmc-java/exceptions6/test.class similarity index 100% rename from regression/exceptions/exceptions6/test.class rename to regression/cbmc-java/exceptions6/test.class diff --git a/regression/exceptions/exceptions6/test.desc b/regression/cbmc-java/exceptions6/test.desc similarity index 100% rename from regression/exceptions/exceptions6/test.desc rename to regression/cbmc-java/exceptions6/test.desc diff --git a/regression/exceptions/exceptions6/test.java b/regression/cbmc-java/exceptions6/test.java similarity index 100% rename from regression/exceptions/exceptions6/test.java rename to regression/cbmc-java/exceptions6/test.java diff --git a/regression/exceptions/exceptions8/A.class b/regression/cbmc-java/exceptions7/A.class similarity index 100% rename from regression/exceptions/exceptions8/A.class rename to regression/cbmc-java/exceptions7/A.class diff --git a/regression/exceptions/exceptions8/B.class b/regression/cbmc-java/exceptions7/B.class similarity index 100% rename from regression/exceptions/exceptions8/B.class rename to regression/cbmc-java/exceptions7/B.class diff --git a/regression/exceptions/exceptions8/C.class b/regression/cbmc-java/exceptions7/C.class similarity index 100% rename from regression/exceptions/exceptions8/C.class rename to regression/cbmc-java/exceptions7/C.class diff --git a/regression/exceptions/exceptions7/test.class b/regression/cbmc-java/exceptions7/test.class similarity index 100% rename from regression/exceptions/exceptions7/test.class rename to regression/cbmc-java/exceptions7/test.class diff --git a/regression/exceptions/exceptions7/test.desc b/regression/cbmc-java/exceptions7/test.desc similarity index 100% rename from regression/exceptions/exceptions7/test.desc rename to regression/cbmc-java/exceptions7/test.desc diff --git a/regression/exceptions/exceptions7/test.java b/regression/cbmc-java/exceptions7/test.java similarity index 100% rename from regression/exceptions/exceptions7/test.java rename to regression/cbmc-java/exceptions7/test.java diff --git a/regression/cbmc-java/exceptions8/A.class b/regression/cbmc-java/exceptions8/A.class new file mode 100644 index 0000000000000000000000000000000000000000..963ae156be051ca07ea2d602053e012a3d27a7a4 GIT binary patch literal 241 zcmXX=O;5r=5PbuswY3W2=*gpUuorF+lg8kw;Q*%hZQaP2c5B)#@o#xD@!${OM-gX{ zNoL+h-b?0i{P_hi$0WiKR{^dAj0ygd4ckY;@a{e*cu&o%CX6#SdfnHBZeLVUi8IZb zQdPNX+3BSuQG(CW@UysN#6;bBCelyKv8QYrJ6YoqP1btzNpmRpEZ_t;J0Rp-H$s}9|kN*P*5s4yPo>K82_(?21 literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/exceptions8/B.class b/regression/cbmc-java/exceptions8/B.class new file mode 100644 index 0000000000000000000000000000000000000000..47ae8f218e49b4ac942425d72a88b21c2772b518 GIT binary patch literal 216 zcmXX7D1o9M#q%+AiT z@6YoEV1a=P9X%U;8$Q8WsZ3RCf!TDLcb3PedAtLN)W> zG^(>I`7{ic1ox2FMIv{qi93}ntJy`|ga-pAfda+`BWV1+DPr)3*K{pl# WT<*@-G|^!l`~vXc^F-)=Q^5xrb|N Date: Fri, 17 Feb 2017 08:42:35 +0000 Subject: [PATCH 20/67] Escaping brackets in test descriptions --- regression/cbmc-java/exceptions1/test.desc | 2 +- regression/cbmc-java/exceptions2/test.desc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/regression/cbmc-java/exceptions1/test.desc b/regression/cbmc-java/exceptions1/test.desc index ca52107829c..638351f4397 100644 --- a/regression/cbmc-java/exceptions1/test.desc +++ b/regression/cbmc-java/exceptions1/test.desc @@ -4,7 +4,7 @@ test.class ^EXIT=10$ ^SIGNAL=0$ ^.*assertion at file test.java line 26 function.*: FAILURE$ -\*\* 1 of 9 failed (2 iterations)$ +\*\* 1 of 9 failed \(2 iterations\)$ ^VERIFICATION FAILED$ -- ^warning: ignoring diff --git a/regression/cbmc-java/exceptions2/test.desc b/regression/cbmc-java/exceptions2/test.desc index 45f5bac3bc2..8645e5ea074 100644 --- a/regression/cbmc-java/exceptions2/test.desc +++ b/regression/cbmc-java/exceptions2/test.desc @@ -4,7 +4,7 @@ test.class ^EXIT=10$ ^SIGNAL=0$ ^.*assertion at file test.java line 15 function.*: FAILURE$ -^\*\* 1 of 5 failed (2 iterations)$ +^\*\* 1 of 5 failed \(2 iterations\)$ ^VERIFICATION FAILED$ -- ^warning: ignoring From b96e03ac99867fdc3d3d72d7a32f85e6ad0c6dbe Mon Sep 17 00:00:00 2001 From: Cristina Date: Fri, 17 Feb 2017 09:38:26 +0000 Subject: [PATCH 21/67] Fixed test description for cbmc-java/virtual7 The exception handling instrumentation introduces new labels and thus the target of the gotos in the goto-program needs to be incremented. --- regression/cbmc-java/virtual7/test.desc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/regression/cbmc-java/virtual7/test.desc b/regression/cbmc-java/virtual7/test.desc index b2b26ecb9ce..3846f5c4a69 100644 --- a/regression/cbmc-java/virtual7/test.desc +++ b/regression/cbmc-java/virtual7/test.desc @@ -3,10 +3,10 @@ test.class --show-goto-functions ^EXIT=0$ ^SIGNAL=0$ -IF "java::E".*THEN GOTO [12] -IF "java::B".*THEN GOTO [12] -IF "java::D".*THEN GOTO [12] -IF "java::C".*THEN GOTO [12] +IF "java::E".*THEN GOTO [67] +IF "java::B".*THEN GOTO [67] +IF "java::D".*THEN GOTO [67] +IF "java::C".*THEN GOTO [67] -- IF "java::A".*THEN GOTO -GOTO 4 +GOTO 9 From 3b31d232ce5405b06857a8d34e620f1b6b614841 Mon Sep 17 00:00:00 2001 From: Cristina Date: Tue, 28 Feb 2017 19:34:06 +0000 Subject: [PATCH 22/67] Recompute live ranges for local variables and add corresponding DEAD instructions This needs to be done because the exception handling instrumentation introduces GOTOs which modify the existent live ranges. --- src/goto-programs/remove_exceptions.cpp | 104 +++++++++++++++++++----- 1 file changed, 83 insertions(+), 21 deletions(-) diff --git a/src/goto-programs/remove_exceptions.cpp b/src/goto-programs/remove_exceptions.cpp index 14700921e24..4b4e5debe35 100644 --- a/src/goto-programs/remove_exceptions.cpp +++ b/src/goto-programs/remove_exceptions.cpp @@ -7,11 +7,13 @@ Author: Cristina David Date: December 2016 \*******************************************************************/ -#define DEBUG + #ifdef DEBUG #include #endif + #include +#include #include #include @@ -47,19 +49,20 @@ class remove_exceptionst void instrument_exception_handlers( const goto_functionst::function_mapt::iterator &); - void add_gotos( const goto_functionst::function_mapt::iterator &); void add_throw_gotos( const goto_functionst::function_mapt::iterator &, const goto_programt::instructionst::iterator &, - const stack_catcht &); + const stack_catcht &, + std::vector &); void add_function_call_gotos( const goto_functionst::function_mapt::iterator &, const goto_programt::instructionst::iterator &, - const stack_catcht &); + const stack_catcht &, + std::vector &); }; /*******************************************************************\ @@ -134,7 +137,6 @@ void remove_exceptionst::add_exceptional_returns( rhs_expr_null); t_null->function=function_id; } - return; } /*******************************************************************\ @@ -318,11 +320,13 @@ Purpose: instruments each throw with conditional GOTOS to the void remove_exceptionst::add_throw_gotos( const goto_functionst::function_mapt::iterator &func_it, const goto_programt::instructionst::iterator &instr_it, - const remove_exceptionst::stack_catcht &stack_catch) + const remove_exceptionst::stack_catcht &stack_catch, + std::vector &locals) { assert(instr_it->type==THROW); goto_programt &goto_program=func_it->second.body; + const irep_idt &function_id=func_it->first; assert(instr_it->code.operands().size()==1); @@ -341,6 +345,11 @@ void remove_exceptionst::add_throw_gotos( t_end->function=instr_it->function; } + // find the symbol corresponding to the caught exceptions + const symbolt &exc_symbol= + symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); + symbol_exprt exc_thrown=exc_symbol.symbol_expr(); + // add GOTOs implementing the dynamic dispatch of the // exception handlers for(std::size_t i=stack_catch.size(); i-->0;) @@ -359,15 +368,21 @@ void remove_exceptionst::add_throw_gotos( // use instanceof to check that this is the correct handler symbol_typet type(stack_catch[i][j].first); type_exprt expr(type); - // find the symbol corresponding to the caught exceptions - exprt exc_symbol=instr_it->code; - while(exc_symbol.id()!=ID_symbol) - exc_symbol=exc_symbol.op0(); - binary_predicate_exprt check(exc_symbol, ID_java_instanceof, expr); + binary_predicate_exprt check(exc_thrown, ID_java_instanceof, expr); t_exc->guard=check; } } + + // add dead instructions + for(const auto &local : locals) + { + goto_programt::targett t_dead=goto_program.insert_after(instr_it); + t_dead->make_dead(); + t_dead->code=code_deadt(local); + t_dead->source_location=instr_it->source_location; + t_dead->function=instr_it->function; + } } /*******************************************************************\ @@ -386,7 +401,8 @@ Purpose: instruments each function call that may escape exceptions void remove_exceptionst::add_function_call_gotos( const goto_functionst::function_mapt::iterator &func_it, const goto_programt::instructionst::iterator &instr_it, - const stack_catcht &stack_catch) + const stack_catcht &stack_catch, + std::vector &locals) { assert(instr_it->type==FUNCTION_CALL); @@ -403,7 +419,7 @@ void remove_exceptionst::add_function_call_gotos( if(symbol_table.has_symbol(id2string(callee_id)+EXC_SUFFIX)) { - // dynamic dispatch of the escaped exception + // we may have an escaping exception const symbolt &callee_exc_symbol= symbol_table.lookup(id2string(callee_id)+EXC_SUFFIX); symbol_exprt callee_exc=callee_exc_symbol.symbol_expr(); @@ -429,11 +445,20 @@ void remove_exceptionst::add_function_call_gotos( } } + // add dead instructions + for(const auto &local : locals) + { + goto_programt::targett t_dead=goto_program.insert_after(instr_it); + t_dead->make_dead(); + t_dead->code=code_deadt(local); + t_dead->source_location=instr_it->source_location; + t_dead->function=instr_it->function; + } + // add a null check (so that instanceof can be applied) equal_exprt eq_null( callee_exc, null_pointer_exprt(pointer_typet(empty_typet()))); - // jump to the next instruction goto_programt::targett t_null=goto_program.insert_after(instr_it); t_null->make_goto(next_it); t_null->source_location=instr_it->source_location; @@ -458,20 +483,54 @@ Purpose: instruments each throw and function calls that may escape exceptions void remove_exceptionst::add_gotos( const goto_functionst::function_mapt::iterator &func_it) { - // Stack of try-catch blocks - stack_catcht stack_catch; - + stack_catcht stack_catch; // stack of try-catch blocks + std::vector> stack_locals; // stack of local vars + std::vector locals; + bool skip_dead=false; goto_programt &goto_program=func_it->second.body; if(goto_program.empty()) return; Forall_goto_program_instructions(instr_it, goto_program) { + if(!instr_it->labels.empty()) + skip_dead=false; + if(instr_it->is_decl()) + { + code_declt decl=to_code_decl(instr_it->code); + locals.push_back(decl.symbol()); + } + if(instr_it->is_dead()) + { + code_deadt dead=to_code_dead(instr_it->code); + auto it=std::find(locals.begin(), + locals.end(), + dead.symbol()); + // avoid DEAD re-declarations + if(it==locals.end()) + { + if(skip_dead) + { + // this DEAD has been already added by a throw + instr_it->make_skip(); + } + } + else + { + locals.erase(it); + } + } // it's a CATCH but not a handler - if(instr_it->type==CATCH && !instr_it->code.has_operands()) + else if(instr_it->type==CATCH && !instr_it->code.has_operands()) { if(instr_it->targets.empty()) // pop { + // pop the local vars stack + if(!stack_locals.empty()) + { + locals=stack_locals.back(); + stack_locals.pop_back(); + } // pop from the stack if possible if(!stack_catch.empty()) { @@ -486,6 +545,9 @@ void remove_exceptionst::add_gotos( } else // push { + stack_locals.push_back(locals); + locals.clear(); + remove_exceptionst::catch_handlerst exception; stack_catch.push_back(exception); remove_exceptionst::catch_handlerst &last_exception= @@ -505,16 +567,16 @@ void remove_exceptionst::add_gotos( i++; } } - instr_it->make_skip(); } else if(instr_it->type==THROW) { - add_throw_gotos(func_it, instr_it, stack_catch); + skip_dead=true; + add_throw_gotos(func_it, instr_it, stack_catch, locals); } else if(instr_it->type==FUNCTION_CALL) { - add_function_call_gotos(func_it, instr_it, stack_catch); + add_function_call_gotos(func_it, instr_it, stack_catch, locals); } } } From 96764a2db85552749cbc876d806f84126134a08f Mon Sep 17 00:00:00 2001 From: Cristina Date: Tue, 28 Feb 2017 19:35:54 +0000 Subject: [PATCH 23/67] Forced try-catch to start a new basic block This was required in order for variables local to the try-catch to be declared at the right location. This way, after adding the exception instrumentation in remove_exceptions, we will be able to correctly re-compute live ranges for these variables. --- .../java_bytecode_convert_method.cpp | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/src/java_bytecode/java_bytecode_convert_method.cpp b/src/java_bytecode/java_bytecode_convert_method.cpp index 19174326c6c..bc13e61c1cf 100644 --- a/src/java_bytecode/java_bytecode_convert_method.cpp +++ b/src/java_bytecode/java_bytecode_convert_method.cpp @@ -5,7 +5,7 @@ Module: JAVA Bytecode Language Conversion Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ - +#define DEBUG #ifdef DEBUG #include #endif @@ -2080,7 +2080,10 @@ codet java_bytecode_convert_methodt::convert_instructions( std::vector exception_ids; std::vector handler_labels; - // add the CATCH-PUSH instruction(s) + // for each try-catch add a CATCH-PUSH instruction + // each CATCH-PUSH records a list of all the handler labels + // together with a list of all the exception ids + // be aware of different try-catch blocks with the same starting pc std::size_t pos=0; size_t end_pc=0; @@ -2100,8 +2103,7 @@ codet java_bytecode_convert_methodt::convert_instructions( method.exception_table[pos].end_pc==end_pc) { exception_ids.push_back( - method.exception_table[pos]. - catch_type.get_identifier()); + method.exception_table[pos].catch_type.get_identifier()); // record the exception handler in the CATCH-PUSH // instruction by generating a label corresponding to // the handler's pc @@ -2122,7 +2124,7 @@ codet java_bytecode_convert_methodt::convert_instructions( for(size_t i=0; i1; - + // Start a new lexical block if we've just entered a try block + if(!start_new_block && previous_address!=-1) + { + for(const auto &exception_row : method.exception_table) + if(exception_row.start_pc==previous_address) + { + start_new_block=true; + break; + } + } + if(start_new_block) { code_labelt newlabel(label(std::to_string(address)), code_blockt()); @@ -2330,6 +2343,8 @@ codet java_bytecode_convert_methodt::convert_instructions( add_to_block.add(c); } start_new_block=address_pair.second.successors.size()>1; + + previous_address=address; } // Find out where temporaries are used: From fa1e3d2157741a50fd8ccb9035fd6599e31cdd83 Mon Sep 17 00:00:00 2001 From: Chris Smowton Date: Wed, 30 Nov 2016 11:00:31 +0000 Subject: [PATCH 24/67] Java checkcast: fix stack when check disabled The checkcast instruction should always return the pointer it checked, even when we're not generating an assert in the case that it failed. --- src/java_bytecode/java_bytecode_convert_method.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/java_bytecode/java_bytecode_convert_method.cpp b/src/java_bytecode/java_bytecode_convert_method.cpp index 54412747708..4dad0f7dd77 100644 --- a/src/java_bytecode/java_bytecode_convert_method.cpp +++ b/src/java_bytecode/java_bytecode_convert_method.cpp @@ -980,10 +980,11 @@ codet java_bytecode_convert_methodt::convert_instructions( c=code_assertt(check); c.add_source_location().set_comment("Dynamic cast check"); c.add_source_location().set_property_class("bad-dynamic-cast"); - results[0]=op[0]; } else c=code_skipt(); + + results[0]=op[0]; } else if(statement=="invokedynamic") { From a43b86297ddc3ce02f278936ae90c2cce009e1aa Mon Sep 17 00:00:00 2001 From: "Robert (Jamie) Munro" Date: Thu, 16 Feb 2017 16:36:33 +0000 Subject: [PATCH 25/67] Explore matching nested bracketed stuff --- scripts/cpplint.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/scripts/cpplint.py b/scripts/cpplint.py index 7fdc937ecf5..0020b299de9 100755 --- a/scripts/cpplint.py +++ b/scripts/cpplint.py @@ -552,7 +552,9 @@ "Missing space before {": r's/\([^ ]\){/\1 {/', "Tab found, replace by spaces": r's/\t/ /', "Line ends in whitespace. Consider deleting these extra spaces.": r's/\s*$//', - #"Redundant blank line at the end of a code block should be deleted.": "d", # messes up line numbers for other errors. + # "Statement after an if should be on a new line": r's/^\(\s*\)if *\(([^()]*)\) *\(.*\)$/\1if\2\n\1 \3/', # Single layer of nested bracets + # "Statement after an if should be on a new line": r's/^\(\s*\)if *\((\([^()]\|([^()]*)\)*)\) *\(.*\)$/\1if\2\n\1 \4/', # Max 2 layers of nested bracets; messes up line numbers for other errors. + # "Redundant blank line at the end of a code block should be deleted.": "d", # messes up line numbers for other errors. } _regexp_compile_cache = {} From 4e6c7b2144c1659e34ae2dd98298bb2e676c7a5c Mon Sep 17 00:00:00 2001 From: "Robert (Jamie) Munro" Date: Mon, 20 Feb 2017 00:50:11 +0000 Subject: [PATCH 26/67] Fix ; after } errors --- scripts/cpplint.py | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/cpplint.py b/scripts/cpplint.py index 0020b299de9..697ad401f78 100755 --- a/scripts/cpplint.py +++ b/scripts/cpplint.py @@ -552,6 +552,7 @@ "Missing space before {": r's/\([^ ]\){/\1 {/', "Tab found, replace by spaces": r's/\t/ /', "Line ends in whitespace. Consider deleting these extra spaces.": r's/\s*$//', + "You don't need a ; after a }": r's/};/}/', # "Statement after an if should be on a new line": r's/^\(\s*\)if *\(([^()]*)\) *\(.*\)$/\1if\2\n\1 \3/', # Single layer of nested bracets # "Statement after an if should be on a new line": r's/^\(\s*\)if *\((\([^()]\|([^()]*)\)*)\) *\(.*\)$/\1if\2\n\1 \4/', # Max 2 layers of nested bracets; messes up line numbers for other errors. # "Redundant blank line at the end of a code block should be deleted.": "d", # messes up line numbers for other errors. From 89d259eb974234cba2e7a06fb0a8eb7b7a9db210 Mon Sep 17 00:00:00 2001 From: "Robert (Jamie) Munro" Date: Mon, 20 Feb 2017 11:01:20 +0000 Subject: [PATCH 27/67] Fix missing space after , errors --- scripts/cpplint.py | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/cpplint.py b/scripts/cpplint.py index 697ad401f78..d6937b13ac5 100755 --- a/scripts/cpplint.py +++ b/scripts/cpplint.py @@ -553,6 +553,7 @@ "Tab found, replace by spaces": r's/\t/ /', "Line ends in whitespace. Consider deleting these extra spaces.": r's/\s*$//', "You don't need a ; after a }": r's/};/}/', + "Missing space after ,": r's/,\([^ ]\)/, \1/', # "Statement after an if should be on a new line": r's/^\(\s*\)if *\(([^()]*)\) *\(.*\)$/\1if\2\n\1 \3/', # Single layer of nested bracets # "Statement after an if should be on a new line": r's/^\(\s*\)if *\((\([^()]\|([^()]*)\)*)\) *\(.*\)$/\1if\2\n\1 \4/', # Max 2 layers of nested bracets; messes up line numbers for other errors. # "Redundant blank line at the end of a code block should be deleted.": "d", # messes up line numbers for other errors. From ce6b2b4ec7727f0f45e78c585fec6a90a319181f Mon Sep 17 00:00:00 2001 From: "Robert (Jamie) Munro" Date: Mon, 20 Feb 2017 11:13:14 +0000 Subject: [PATCH 28/67] Replace tabs globally within the line --- scripts/cpplint.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/cpplint.py b/scripts/cpplint.py index d6937b13ac5..002fc43dc85 100755 --- a/scripts/cpplint.py +++ b/scripts/cpplint.py @@ -550,7 +550,7 @@ "Remove space before ( in switch (": "s/switch (/switch(/", "Should have a space between // and comment": 's/\/\//\/\/ /', "Missing space before {": r's/\([^ ]\){/\1 {/', - "Tab found, replace by spaces": r's/\t/ /', + "Tab found, replace by spaces": r's/\t/ /g', "Line ends in whitespace. Consider deleting these extra spaces.": r's/\s*$//', "You don't need a ; after a }": r's/};/}/', "Missing space after ,": r's/,\([^ ]\)/, \1/', From 0b11c4385fb2d8b79afe35ec41d019f9e2b8dd41 Mon Sep 17 00:00:00 2001 From: "Robert (Jamie) Munro" Date: Fri, 3 Mar 2017 10:22:19 +0000 Subject: [PATCH 29/67] Add space after comma globally within the line --- scripts/cpplint.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/cpplint.py b/scripts/cpplint.py index 002fc43dc85..450e9b8f64c 100755 --- a/scripts/cpplint.py +++ b/scripts/cpplint.py @@ -553,7 +553,7 @@ "Tab found, replace by spaces": r's/\t/ /g', "Line ends in whitespace. Consider deleting these extra spaces.": r's/\s*$//', "You don't need a ; after a }": r's/};/}/', - "Missing space after ,": r's/,\([^ ]\)/, \1/', + "Missing space after ,": r's/,\([^ ]\)/, \1/g', # "Statement after an if should be on a new line": r's/^\(\s*\)if *\(([^()]*)\) *\(.*\)$/\1if\2\n\1 \3/', # Single layer of nested bracets # "Statement after an if should be on a new line": r's/^\(\s*\)if *\((\([^()]\|([^()]*)\)*)\) *\(.*\)$/\1if\2\n\1 \4/', # Max 2 layers of nested bracets; messes up line numbers for other errors. # "Redundant blank line at the end of a code block should be deleted.": "d", # messes up line numbers for other errors. From f81c73c9a7d63fc6c23f2b052db609fedcb7096c Mon Sep 17 00:00:00 2001 From: Lucas Cordeiro Date: Fri, 3 Mar 2017 10:46:24 +0000 Subject: [PATCH 30/67] set EXIT to 10 to all failing string-solver test cases set EXIT to 10 in the test description of each string-solver test case that is supposed to fail --- regression/strings/RegexMatches02/test.desc | 2 +- regression/strings/RegexSubstitution02/test.desc | 2 +- regression/strings/StaticCharMethods02/test.desc | 2 +- regression/strings/StaticCharMethods03/test.desc | 2 +- regression/strings/StaticCharMethods04/test.desc | 2 +- regression/strings/StaticCharMethods05/test.desc | 2 +- regression/strings/StringBuilderAppend02/test.desc | 2 +- regression/strings/StringBuilderCapLen02/test.desc | 2 +- regression/strings/StringBuilderCapLen03/test.desc | 2 +- regression/strings/StringBuilderCapLen04/test.desc | 2 +- regression/strings/StringBuilderChars02/test.desc | 2 +- regression/strings/StringBuilderChars03/test.desc | 2 +- regression/strings/StringBuilderChars04/test.desc | 2 +- regression/strings/StringBuilderChars05/test.desc | 2 +- regression/strings/StringBuilderChars06/test.desc | 2 +- regression/strings/StringBuilderConstructors02/test.desc | 2 +- regression/strings/StringBuilderInsertDelete02/test.desc | 2 +- regression/strings/StringBuilderInsertDelete03/test.desc | 2 +- regression/strings/StringCompare02/test.desc | 2 +- regression/strings/StringCompare03/test.desc | 2 +- regression/strings/StringCompare04/test.desc | 2 +- regression/strings/StringCompare05/test.desc | 2 +- regression/strings/StringConcatenation02/test.desc | 2 +- regression/strings/StringConcatenation03/test.desc | 2 +- regression/strings/StringConcatenation04/test.desc | 2 +- regression/strings/StringConstructors02/test.desc | 2 +- regression/strings/StringConstructors03/test.desc | 2 +- regression/strings/StringConstructors04/test.desc | 2 +- regression/strings/StringConstructors05/test.desc | 2 +- regression/strings/StringIndexMethods02/test.desc | 2 +- regression/strings/StringIndexMethods03/test.desc | 2 +- regression/strings/StringIndexMethods04/test.desc | 2 +- regression/strings/StringIndexMethods05/test.desc | 2 +- regression/strings/StringMiscellaneous02/test.desc | 2 +- regression/strings/StringMiscellaneous03/test.desc | 2 +- regression/strings/StringStartEnd02/test.desc | 2 +- regression/strings/StringStartEnd03/test.desc | 2 +- regression/strings/StringValueOf02/test.desc | 2 +- regression/strings/StringValueOf03/test.desc | 2 +- regression/strings/StringValueOf04/test.desc | 2 +- regression/strings/StringValueOf05/test.desc | 2 +- regression/strings/StringValueOf06/test.desc | 2 +- regression/strings/StringValueOf07/test.desc | 2 +- regression/strings/StringValueOf08/test.desc | 2 +- regression/strings/StringValueOf09/test.desc | 2 +- regression/strings/StringValueOf10/test.desc | 2 +- regression/strings/SubString02/test.desc | 2 +- regression/strings/SubString03/test.desc | 2 +- regression/strings/TokenTest02/test.desc | 2 +- regression/strings/Validate02/test.desc | 2 +- 50 files changed, 50 insertions(+), 50 deletions(-) diff --git a/regression/strings/RegexMatches02/test.desc b/regression/strings/RegexMatches02/test.desc index 92d72ae941e..86353d9a54c 100644 --- a/regression/strings/RegexMatches02/test.desc +++ b/regression/strings/RegexMatches02/test.desc @@ -1,7 +1,7 @@ FUTURE RegexMatches02.class --string-refine --unwind 100 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/RegexSubstitution02/test.desc b/regression/strings/RegexSubstitution02/test.desc index eb2c03599a1..0645c3ac9b8 100644 --- a/regression/strings/RegexSubstitution02/test.desc +++ b/regression/strings/RegexSubstitution02/test.desc @@ -1,7 +1,7 @@ FUTURE RegexSubstitution02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StaticCharMethods02/test.desc b/regression/strings/StaticCharMethods02/test.desc index 496814588a7..00aaaba8964 100644 --- a/regression/strings/StaticCharMethods02/test.desc +++ b/regression/strings/StaticCharMethods02/test.desc @@ -1,7 +1,7 @@ FUTURE StaticCharMethods02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StaticCharMethods03/test.desc b/regression/strings/StaticCharMethods03/test.desc index d48bf57dbba..6f3d3bc5607 100644 --- a/regression/strings/StaticCharMethods03/test.desc +++ b/regression/strings/StaticCharMethods03/test.desc @@ -1,7 +1,7 @@ FUTURE StaticCharMethods03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StaticCharMethods04/test.desc b/regression/strings/StaticCharMethods04/test.desc index 93eebbae1da..0c9484ef337 100644 --- a/regression/strings/StaticCharMethods04/test.desc +++ b/regression/strings/StaticCharMethods04/test.desc @@ -1,7 +1,7 @@ FUTURE StaticCharMethods04.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StaticCharMethods05/test.desc b/regression/strings/StaticCharMethods05/test.desc index e009650a853..5b4a6b4b622 100644 --- a/regression/strings/StaticCharMethods05/test.desc +++ b/regression/strings/StaticCharMethods05/test.desc @@ -1,7 +1,7 @@ FUTURE StaticCharMethods05.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderAppend02/test.desc b/regression/strings/StringBuilderAppend02/test.desc index 4ff9da595b5..1336c45c3d2 100644 --- a/regression/strings/StringBuilderAppend02/test.desc +++ b/regression/strings/StringBuilderAppend02/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderAppend02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderCapLen02/test.desc b/regression/strings/StringBuilderCapLen02/test.desc index cf2a98acf6d..72a0bbd72c2 100644 --- a/regression/strings/StringBuilderCapLen02/test.desc +++ b/regression/strings/StringBuilderCapLen02/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderCapLen02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderCapLen03/test.desc b/regression/strings/StringBuilderCapLen03/test.desc index 7095d79fe5f..474bdc661ab 100644 --- a/regression/strings/StringBuilderCapLen03/test.desc +++ b/regression/strings/StringBuilderCapLen03/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderCapLen03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderCapLen04/test.desc b/regression/strings/StringBuilderCapLen04/test.desc index ce51066e789..fa342b79518 100644 --- a/regression/strings/StringBuilderCapLen04/test.desc +++ b/regression/strings/StringBuilderCapLen04/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderCapLen04.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderChars02/test.desc b/regression/strings/StringBuilderChars02/test.desc index 3a6bde6ef78..50e49d474bc 100644 --- a/regression/strings/StringBuilderChars02/test.desc +++ b/regression/strings/StringBuilderChars02/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderChars02.class --string-refine --unwind 100 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderChars03/test.desc b/regression/strings/StringBuilderChars03/test.desc index 12f20189434..23dda39df4e 100644 --- a/regression/strings/StringBuilderChars03/test.desc +++ b/regression/strings/StringBuilderChars03/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderChars03.class --string-refine --unwind 100 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderChars04/test.desc b/regression/strings/StringBuilderChars04/test.desc index a2658cf2fe4..a68edd89395 100644 --- a/regression/strings/StringBuilderChars04/test.desc +++ b/regression/strings/StringBuilderChars04/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderChars04.class --string-refine --unwind 100 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderChars05/test.desc b/regression/strings/StringBuilderChars05/test.desc index 2bcbdbab934..eeac328e02b 100644 --- a/regression/strings/StringBuilderChars05/test.desc +++ b/regression/strings/StringBuilderChars05/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderChars05.class --string-refine --unwind 100 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderChars06/test.desc b/regression/strings/StringBuilderChars06/test.desc index 4a711edf496..a3dc3712a5a 100644 --- a/regression/strings/StringBuilderChars06/test.desc +++ b/regression/strings/StringBuilderChars06/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderChars06.class --string-refine --unwind 100 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderConstructors02/test.desc b/regression/strings/StringBuilderConstructors02/test.desc index 8cbad8cfe16..5e951bc8079 100644 --- a/regression/strings/StringBuilderConstructors02/test.desc +++ b/regression/strings/StringBuilderConstructors02/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringBuilderConstructors02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderInsertDelete02/test.desc b/regression/strings/StringBuilderInsertDelete02/test.desc index f78bf3f983a..ae4d0ca5b81 100644 --- a/regression/strings/StringBuilderInsertDelete02/test.desc +++ b/regression/strings/StringBuilderInsertDelete02/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderInsertDelete02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringBuilderInsertDelete03/test.desc b/regression/strings/StringBuilderInsertDelete03/test.desc index b3882f41f7e..3dfa92f0338 100644 --- a/regression/strings/StringBuilderInsertDelete03/test.desc +++ b/regression/strings/StringBuilderInsertDelete03/test.desc @@ -1,7 +1,7 @@ FUTURE StringBuilderInsertDelete03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringCompare02/test.desc b/regression/strings/StringCompare02/test.desc index abc986be65d..eb52d1f1a58 100644 --- a/regression/strings/StringCompare02/test.desc +++ b/regression/strings/StringCompare02/test.desc @@ -1,7 +1,7 @@ FUTURE StringCompare02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringCompare03/test.desc b/regression/strings/StringCompare03/test.desc index fa518907143..bd0f3177acf 100644 --- a/regression/strings/StringCompare03/test.desc +++ b/regression/strings/StringCompare03/test.desc @@ -1,7 +1,7 @@ FUTURE StringCompare03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringCompare04/test.desc b/regression/strings/StringCompare04/test.desc index f1b2a9790cc..88ecddbfcf6 100644 --- a/regression/strings/StringCompare04/test.desc +++ b/regression/strings/StringCompare04/test.desc @@ -1,7 +1,7 @@ FUTURE StringCompare04.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringCompare05/test.desc b/regression/strings/StringCompare05/test.desc index 159809fac0f..1358a05a36b 100644 --- a/regression/strings/StringCompare05/test.desc +++ b/regression/strings/StringCompare05/test.desc @@ -1,7 +1,7 @@ FUTURE StringCompare05.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringConcatenation02/test.desc b/regression/strings/StringConcatenation02/test.desc index 937caa3295e..0e1faf53d5e 100644 --- a/regression/strings/StringConcatenation02/test.desc +++ b/regression/strings/StringConcatenation02/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringConcatenation02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringConcatenation03/test.desc b/regression/strings/StringConcatenation03/test.desc index 26ccc899a87..3c01a4ee0a9 100644 --- a/regression/strings/StringConcatenation03/test.desc +++ b/regression/strings/StringConcatenation03/test.desc @@ -1,7 +1,7 @@ FUTURE StringConcatenation03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringConcatenation04/test.desc b/regression/strings/StringConcatenation04/test.desc index ea980c45d54..3dbecf065ba 100644 --- a/regression/strings/StringConcatenation04/test.desc +++ b/regression/strings/StringConcatenation04/test.desc @@ -1,7 +1,7 @@ FUTURE StringConcatenation04.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringConstructors02/test.desc b/regression/strings/StringConstructors02/test.desc index c2a30b3534c..e3904d1d557 100644 --- a/regression/strings/StringConstructors02/test.desc +++ b/regression/strings/StringConstructors02/test.desc @@ -1,7 +1,7 @@ FUTURE StringConstructors02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringConstructors03/test.desc b/regression/strings/StringConstructors03/test.desc index 5419e5ae48e..0caf75f41ea 100644 --- a/regression/strings/StringConstructors03/test.desc +++ b/regression/strings/StringConstructors03/test.desc @@ -1,7 +1,7 @@ FUTURE StringConstructors03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringConstructors04/test.desc b/regression/strings/StringConstructors04/test.desc index 21394f70327..75364dcde22 100644 --- a/regression/strings/StringConstructors04/test.desc +++ b/regression/strings/StringConstructors04/test.desc @@ -1,7 +1,7 @@ FUTURE StringConstructors04.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringConstructors05/test.desc b/regression/strings/StringConstructors05/test.desc index 9804850d77e..e74dfc73f6c 100644 --- a/regression/strings/StringConstructors05/test.desc +++ b/regression/strings/StringConstructors05/test.desc @@ -1,7 +1,7 @@ FUTURE StringConstructors05.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringIndexMethods02/test.desc b/regression/strings/StringIndexMethods02/test.desc index cad6c487fae..28df14f0145 100644 --- a/regression/strings/StringIndexMethods02/test.desc +++ b/regression/strings/StringIndexMethods02/test.desc @@ -1,7 +1,7 @@ FUTURE StringIndexMethods02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringIndexMethods03/test.desc b/regression/strings/StringIndexMethods03/test.desc index 3dff0b27714..02f9934726b 100644 --- a/regression/strings/StringIndexMethods03/test.desc +++ b/regression/strings/StringIndexMethods03/test.desc @@ -1,7 +1,7 @@ FUTURE StringIndexMethods03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringIndexMethods04/test.desc b/regression/strings/StringIndexMethods04/test.desc index 758f22d2bf4..cb94fecb6a6 100644 --- a/regression/strings/StringIndexMethods04/test.desc +++ b/regression/strings/StringIndexMethods04/test.desc @@ -1,7 +1,7 @@ FUTURE StringIndexMethods04.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringIndexMethods05/test.desc b/regression/strings/StringIndexMethods05/test.desc index d415ef1381e..cb43b009246 100644 --- a/regression/strings/StringIndexMethods05/test.desc +++ b/regression/strings/StringIndexMethods05/test.desc @@ -1,7 +1,7 @@ FUTURE StringIndexMethods05.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringMiscellaneous02/test.desc b/regression/strings/StringMiscellaneous02/test.desc index 53c46cf1a7f..8f1a1d9475f 100644 --- a/regression/strings/StringMiscellaneous02/test.desc +++ b/regression/strings/StringMiscellaneous02/test.desc @@ -1,7 +1,7 @@ FUTURE StringMiscellaneous02.class --string-refine --unwind 30 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringMiscellaneous03/test.desc b/regression/strings/StringMiscellaneous03/test.desc index f255272ed5b..341867d536f 100644 --- a/regression/strings/StringMiscellaneous03/test.desc +++ b/regression/strings/StringMiscellaneous03/test.desc @@ -1,7 +1,7 @@ FUTURE StringMiscellaneous03.class --string-refine --unwind 30 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringStartEnd02/test.desc b/regression/strings/StringStartEnd02/test.desc index 16f696efa01..8e623622f72 100644 --- a/regression/strings/StringStartEnd02/test.desc +++ b/regression/strings/StringStartEnd02/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringStartEnd02.class --string-refine --unwind 30 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringStartEnd03/test.desc b/regression/strings/StringStartEnd03/test.desc index e6d8c460709..2903ec98e3e 100644 --- a/regression/strings/StringStartEnd03/test.desc +++ b/regression/strings/StringStartEnd03/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringStartEnd03.class --string-refine --unwind 15 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf02/test.desc b/regression/strings/StringValueOf02/test.desc index 00835385bc8..a10b398bf41 100644 --- a/regression/strings/StringValueOf02/test.desc +++ b/regression/strings/StringValueOf02/test.desc @@ -1,7 +1,7 @@ FUTURE StringValueOf02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf03/test.desc b/regression/strings/StringValueOf03/test.desc index 19921a8e98f..4ed709a2404 100644 --- a/regression/strings/StringValueOf03/test.desc +++ b/regression/strings/StringValueOf03/test.desc @@ -1,7 +1,7 @@ FUTURE StringValueOf03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf04/test.desc b/regression/strings/StringValueOf04/test.desc index 1312d27676d..0d8442e9de1 100644 --- a/regression/strings/StringValueOf04/test.desc +++ b/regression/strings/StringValueOf04/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringValueOf04.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf05/test.desc b/regression/strings/StringValueOf05/test.desc index ccb5b3dc440..f77cdef0b8e 100644 --- a/regression/strings/StringValueOf05/test.desc +++ b/regression/strings/StringValueOf05/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringValueOf05.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf06/test.desc b/regression/strings/StringValueOf06/test.desc index c78afa98f2f..56551c4a14b 100644 --- a/regression/strings/StringValueOf06/test.desc +++ b/regression/strings/StringValueOf06/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringValueOf06.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf07/test.desc b/regression/strings/StringValueOf07/test.desc index 7b19c4ff67b..6dde9de229d 100644 --- a/regression/strings/StringValueOf07/test.desc +++ b/regression/strings/StringValueOf07/test.desc @@ -1,7 +1,7 @@ KNOWNBUG StringValueOf07.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf08/test.desc b/regression/strings/StringValueOf08/test.desc index a7d90b1b9ef..21d64075aaf 100644 --- a/regression/strings/StringValueOf08/test.desc +++ b/regression/strings/StringValueOf08/test.desc @@ -1,7 +1,7 @@ FUTURE StringValueOf08.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf09/test.desc b/regression/strings/StringValueOf09/test.desc index 10f6b102a67..4ff97a7caef 100644 --- a/regression/strings/StringValueOf09/test.desc +++ b/regression/strings/StringValueOf09/test.desc @@ -1,7 +1,7 @@ FUTURE StringValueOf09.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/StringValueOf10/test.desc b/regression/strings/StringValueOf10/test.desc index 5de3d5aade7..10e7f184189 100644 --- a/regression/strings/StringValueOf10/test.desc +++ b/regression/strings/StringValueOf10/test.desc @@ -1,7 +1,7 @@ FUTURE StringValueOf10.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/SubString02/test.desc b/regression/strings/SubString02/test.desc index e7b21cdd678..063ce88f0f2 100644 --- a/regression/strings/SubString02/test.desc +++ b/regression/strings/SubString02/test.desc @@ -1,7 +1,7 @@ KNOWNBUG SubString02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/SubString03/test.desc b/regression/strings/SubString03/test.desc index 2b8db21a829..f985329ce2d 100644 --- a/regression/strings/SubString03/test.desc +++ b/regression/strings/SubString03/test.desc @@ -1,7 +1,7 @@ KNOWNBUG SubString03.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/TokenTest02/test.desc b/regression/strings/TokenTest02/test.desc index 3bcf7505e25..48e6b0c1ab6 100644 --- a/regression/strings/TokenTest02/test.desc +++ b/regression/strings/TokenTest02/test.desc @@ -1,7 +1,7 @@ FUTURE TokenTest02.class --string-refine --unwind 15 -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- diff --git a/regression/strings/Validate02/test.desc b/regression/strings/Validate02/test.desc index b30016bf880..a5a3a6f1d20 100644 --- a/regression/strings/Validate02/test.desc +++ b/regression/strings/Validate02/test.desc @@ -1,7 +1,7 @@ FUTURE Validate02.class --string-refine -^EXIT=0$ +^EXIT=10$ ^SIGNAL=0$ ^VERIFICATION FAILED$ -- From 122ec36b18d77bf94d6ffa8f24bc62036718dc35 Mon Sep 17 00:00:00 2001 From: Chris Smowton Date: Thu, 27 Oct 2016 15:19:44 +0100 Subject: [PATCH 31/67] Add string-infix utility --- src/util/infix.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 src/util/infix.h diff --git a/src/util/infix.h b/src/util/infix.h new file mode 100644 index 00000000000..2fcc1338d5d --- /dev/null +++ b/src/util/infix.h @@ -0,0 +1,22 @@ +/*******************************************************************\ + +Module: String infix shorthand + +Author: Chris Smowton, chris.smowton@diffblue.com + +\*******************************************************************/ + +#ifndef CPROVER_UTIL_INFIX_H +#define CPROVER_UTIL_INFIX_H + +#include + +inline bool has_infix( + const std::string &s, + const std::string &infix, + size_t offset) +{ + return s.compare(offset, infix.size(), infix)==0; +} + +#endif From 47f84b924478f4fa9f5db908a0dcbdb00c2064d7 Mon Sep 17 00:00:00 2001 From: Chris Smowton Date: Thu, 23 Feb 2017 16:50:10 +0000 Subject: [PATCH 32/67] Add json->irep deserialization routine --- src/util/json_irep.cpp | 40 +++++++++++++++++++++++++++++++++++++++- src/util/json_irep.h | 1 + 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/src/util/json_irep.cpp b/src/util/json_irep.cpp index 7a3d1a8f2bc..403247c1d04 100644 --- a/src/util/json_irep.cpp +++ b/src/util/json_irep.cpp @@ -10,12 +10,14 @@ Author: Thomas Kiley, thomas.kiley@diffblue.com #include "json.h" #include "json_irep.h" +#include + /*******************************************************************\ Function: json_irept::json_irept Inputs: - include_comments - when generating the JSON, should the comments + include_comments - when writing JSON, should the comments sub tree be included. Outputs: @@ -131,3 +133,39 @@ void json_irept::convert_named_sub_tree( } } +/*******************************************************************\ + +Function: json_irept::convert_from_json + + Inputs: input - json object to convert + + Outputs: result - irep equivalent of input + + Purpose: Deserialize a JSON irep representation. + +\*******************************************************************/ + +void json_irept::convert_from_json(const jsont &in, irept &out) const +{ + std::vector have_keys; + for(const auto &keyval : in.object) + have_keys.push_back(keyval.first); + std::sort(have_keys.begin(), have_keys.end()); + if(have_keys!=std::vector{"comment", "id", "namedSub", "sub"}) + throw "irep JSON representation is missing one of needed keys: " + "'id', 'sub', 'namedSub', 'comment'"; + + out.id(in["id"].value); + + for(const auto &sub : in["sub"].array) + { + out.get_sub().push_back(irept()); + convert_from_json(sub, out.get_sub().back()); + } + + for(const auto &named_sub : in["namedSub"].object) + convert_from_json(named_sub.second, out.get_named_sub()[named_sub.first]); + + for(const auto &comment : in["comment"].object) + convert_from_json(comment.second, out.get_comments()[comment.first]); +} diff --git a/src/util/json_irep.h b/src/util/json_irep.h index 749917cb34b..20a364d31e9 100644 --- a/src/util/json_irep.h +++ b/src/util/json_irep.h @@ -18,6 +18,7 @@ class json_irept public: explicit json_irept(bool include_comments); void convert_from_irep(const irept &irep, jsont &json) const; + void convert_from_json(const jsont &, irept &) const; private: void convert_sub_tree( From 38f8f5c1811cc19b3d473f6f19c531876cd6b070 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Tue, 7 Mar 2017 19:30:12 -0800 Subject: [PATCH 33/67] libzip/zlib download no longer needed --- COMPILING | 4 ---- 1 file changed, 4 deletions(-) diff --git a/COMPILING b/COMPILING index 13b8339abd7..60579fe9f3b 100644 --- a/COMPILING +++ b/COMPILING @@ -48,8 +48,6 @@ We assume that you have a Debian/Ubuntu or Red Hat-like distribution. cd cbmc-git/src make minisat2-download - make libzip-download zlib-download - make libzip-build make @@ -126,8 +124,6 @@ Follow these instructions: cd cbmc-git/src make minisat2-download - make libzip-download zlib-download - make libzip-build make From 1dcee0d2a25b4b94e11bfe30d9648f24e765bbc6 Mon Sep 17 00:00:00 2001 From: Pascal Kesseli Date: Wed, 8 Mar 2017 15:12:37 +0000 Subject: [PATCH 34/67] Fixed compilation issues on MinGW Added missing includes which caused compilation errors on MinGW 5.3.0. --- src/cegis/cegis-util/cbmc_runner.cpp | 2 ++ src/cegis/genetic/dynamic_test_runner_helper.cpp | 1 + src/cegis/jsa/learn/extract_candidate.cpp | 2 ++ 3 files changed, 5 insertions(+) diff --git a/src/cegis/cegis-util/cbmc_runner.cpp b/src/cegis/cegis-util/cbmc_runner.cpp index 58739658ab1..1d30bbfa63e 100644 --- a/src/cegis/cegis-util/cbmc_runner.cpp +++ b/src/cegis/cegis-util/cbmc_runner.cpp @@ -7,6 +7,8 @@ Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ +#include + #include #include diff --git a/src/cegis/genetic/dynamic_test_runner_helper.cpp b/src/cegis/genetic/dynamic_test_runner_helper.cpp index f357b80b72d..bb3de1236d5 100644 --- a/src/cegis/genetic/dynamic_test_runner_helper.cpp +++ b/src/cegis/genetic/dynamic_test_runner_helper.cpp @@ -12,6 +12,7 @@ Author: Daniel Kroening, kroening@kroening.com #endif #include +#include #include #include diff --git a/src/cegis/jsa/learn/extract_candidate.cpp b/src/cegis/jsa/learn/extract_candidate.cpp index 40ed53af0b2..0a27a48c2bd 100644 --- a/src/cegis/jsa/learn/extract_candidate.cpp +++ b/src/cegis/jsa/learn/extract_candidate.cpp @@ -7,6 +7,8 @@ Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ +#include + #include #include #include From 4e8760856bb7c5130c8aad314c278e67b446e0e6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Thu, 9 Mar 2017 11:05:27 +0100 Subject: [PATCH 35/67] remove `` from unapproved headers in cpplint The reason for `` being discouraged seems to be a preference for an external library within Google: https://github.com/google/styleguide/issues/194 --- scripts/cpplint.py | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/cpplint.py b/scripts/cpplint.py index 7fdc937ecf5..3d457bb4113 100755 --- a/scripts/cpplint.py +++ b/scripts/cpplint.py @@ -6264,7 +6264,6 @@ def FlagCxx11Features(filename, clean_lines, linenum, error): 'thread', 'chrono', 'ratio', - 'regex', 'system_error', ): error(filename, linenum, 'build/c++11', 5, From b236ee4738602140cab93b29b47ea122161b8991 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Sat, 4 Mar 2017 12:00:51 +0100 Subject: [PATCH 36/67] allow regex to limit class files loaded from JAR --- src/cbmc/cbmc_parse_options.cpp | 1 + src/cbmc/cbmc_parse_options.h | 1 + src/java_bytecode/jar_file.cpp | 23 ++++++++++++------ src/java_bytecode/jar_file.h | 25 +++++++++++++------- src/java_bytecode/java_bytecode_language.cpp | 5 ++++ src/java_bytecode/java_bytecode_language.h | 1 + src/java_bytecode/java_class_loader.h | 4 ++++ 7 files changed, 44 insertions(+), 16 deletions(-) diff --git a/src/cbmc/cbmc_parse_options.cpp b/src/cbmc/cbmc_parse_options.cpp index 7364752d093..e0e3b7db70e 100644 --- a/src/cbmc/cbmc_parse_options.cpp +++ b/src/cbmc/cbmc_parse_options.cpp @@ -1155,6 +1155,7 @@ void cbmc_parse_optionst::help() // NOLINTNEXTLINE(whitespace/line_length) " --java-max-vla-length limit the length of user-code-created arrays\n" // NOLINTNEXTLINE(whitespace/line_length) + " --java-cp-include-files regexp of class files to load\n" " --java-unwind-enum-static try to unwind loops in static initialization of enums\n" "\n" "Semantic transformations:\n" diff --git a/src/cbmc/cbmc_parse_options.h b/src/cbmc/cbmc_parse_options.h index adc6e2ee517..a3fc5e7e7d3 100644 --- a/src/cbmc/cbmc_parse_options.h +++ b/src/cbmc/cbmc_parse_options.h @@ -55,6 +55,7 @@ class optionst; "(round-to-nearest)(round-to-plus-inf)(round-to-minus-inf)(round-to-zero)" \ "(graphml-witness):" \ "(java-max-vla-length):(java-unwind-enum-static)" \ + "(java-cp-include-files):" \ "(localize-faults)(localize-faults-method):" \ "(lazy-methods)" \ "(fixedbv)(floatbv)(all-claims)(all-properties)" // legacy, and will eventually disappear // NOLINT(whitespace/line_length) diff --git a/src/java_bytecode/jar_file.cpp b/src/java_bytecode/jar_file.cpp index d679f21c070..f7cb0726494 100644 --- a/src/java_bytecode/jar_file.cpp +++ b/src/java_bytecode/jar_file.cpp @@ -9,8 +9,8 @@ Author: Daniel Kroening, kroening@kroening.com #include #include #include - #include "jar_file.h" +#include /*******************************************************************\ @@ -24,7 +24,7 @@ Function: jar_filet::open \*******************************************************************/ -void jar_filet::open(const std::string &filename) +void jar_filet::open(std::string &java_cp_include_files, const std::string &filename) { if(!mz_ok) { @@ -38,8 +38,7 @@ void jar_filet::open(const std::string &filename) std::size_t number_of_files= mz_zip_reader_get_num_files(&zip); - index.reserve(number_of_files); - + size_t filtered_index=0; for(std::size_t i=0; i buffer; size_t bufsize=file_stat.m_uncomp_size; buffer.resize(bufsize); mz_bool read_ok= - mz_zip_reader_extract_to_mem(&zip, i, buffer.data(), bufsize, 0); + mz_zip_reader_extract_to_mem(&zip, real_index, buffer.data(), bufsize, 0); if(read_ok!=MZ_TRUE) return std::string(); diff --git a/src/java_bytecode/jar_file.h b/src/java_bytecode/jar_file.h index 53f673102bf..7670cbf6a8b 100644 --- a/src/java_bytecode/jar_file.h +++ b/src/java_bytecode/jar_file.h @@ -15,27 +15,26 @@ Author: Daniel Kroening, kroening@kroening.com #include #include #include +#include class jar_filet { public: jar_filet():mz_ok(false) { } - - inline explicit jar_filet(const std::string &file_name) - { - open(file_name); - } + inline explicit jar_filet(const std::string &file_name) { } ~jar_filet(); - void open(const std::string &); + void open(std::string &java_cp_include_files, const std::string &); // Test for error; 'true' means we are good. - inline explicit operator bool() const { return true; // TODO - } + inline explicit operator bool() const { return mz_ok; } typedef std::vector indext; indext index; + // map internal index to real index in jar central directory + typedef std::map filtered_jart; + filtered_jart filtered_jar; std::string get_entry(std::size_t i); @@ -45,18 +44,25 @@ class jar_filet protected: mz_zip_archive zip; bool mz_ok; + std::string matcher; + std::map index_map; }; class jar_poolt { public: + void set_java_cp_include_files(std::string &_java_cp_include_files) + { + java_cp_include_files=_java_cp_include_files; + } jar_filet &operator()(const std::string &file_name) { + assert(!java_cp_include_files.empty() && "class regexp cannot be empty"); file_mapt::iterator it=file_map.find(file_name); if(it==file_map.end()) { jar_filet &jar_file=file_map[file_name]; - jar_file.open(file_name); + jar_file.open(java_cp_include_files, file_name); return jar_file; } else @@ -66,6 +72,7 @@ class jar_poolt protected: typedef std::map file_mapt; file_mapt file_map; + std::string java_cp_include_files; }; #endif // CPROVER_JAVA_BYTECODE_JAR_FILE_H diff --git a/src/java_bytecode/java_bytecode_language.cpp b/src/java_bytecode/java_bytecode_language.cpp index 79295995662..6a0327968b1 100644 --- a/src/java_bytecode/java_bytecode_language.cpp +++ b/src/java_bytecode/java_bytecode_language.cpp @@ -55,6 +55,10 @@ void java_bytecode_languaget::get_language_options(const cmdlinet &cmd) lazy_methods_mode=LAZY_METHODS_MODE_CONTEXT_INSENSITIVE; else lazy_methods_mode=LAZY_METHODS_MODE_EAGER; + if(cmd.isset("java-cp-include-files")) + java_cp_include_files=cmd.get_value("java-cp-include-files"); + else + java_cp_include_files=".*"; } /*******************************************************************\ @@ -129,6 +133,7 @@ bool java_bytecode_languaget::parse( const std::string &path) { java_class_loader.set_message_handler(get_message_handler()); + java_class_loader.set_java_cp_include_files(java_cp_include_files); // look at extension if(has_suffix(path, ".class")) diff --git a/src/java_bytecode/java_bytecode_language.h b/src/java_bytecode/java_bytecode_language.h index 643eacd5b7f..77689d6e12a 100644 --- a/src/java_bytecode/java_bytecode_language.h +++ b/src/java_bytecode/java_bytecode_language.h @@ -105,6 +105,7 @@ class java_bytecode_languaget:public languaget lazy_methodst lazy_methods; lazy_methods_modet lazy_methods_mode; bool string_refinement_enabled; + std::string java_cp_include_files; }; languaget *new_java_bytecode_language(); diff --git a/src/java_bytecode/java_class_loader.h b/src/java_bytecode/java_class_loader.h index b2a4953445a..8e8f5c5b82c 100644 --- a/src/java_bytecode/java_class_loader.h +++ b/src/java_bytecode/java_class_loader.h @@ -20,6 +20,10 @@ class java_class_loadert:public messaget { public: java_bytecode_parse_treet &operator()(const irep_idt &); + void set_java_cp_include_files(std::string &java_cp_include_files) + { + jar_pool.set_java_cp_include_files(java_cp_include_files); + } // maps class names to the parse trees typedef std::map class_mapt; From ed34a739d8be7e8e1af67b5f0a935e8b388e243a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Tue, 7 Mar 2017 13:04:24 +0100 Subject: [PATCH 37/67] support class load configuration via JSON file e.g. ``` { "jar": [ "A.jar", "B.jar" ], "classFiles": [ "jarfile3$A.class", "jarfile3.class" ] } ``` --- src/cbmc/Makefile | 3 +- src/cbmc/cbmc_parse_options.cpp | 2 +- src/cegis/Makefile | 3 +- src/goto-cc/Makefile | 3 +- src/goto-diff/Makefile | 3 +- src/goto-instrument/Makefile | 3 +- src/java_bytecode/jar_file.cpp | 50 ++++++++++++++++++++++----- src/java_bytecode/jar_file.h | 6 ++-- src/java_bytecode/java_class_loader.h | 1 + src/symex/Makefile | 3 +- 10 files changed, 60 insertions(+), 17 deletions(-) diff --git a/src/cbmc/Makefile b/src/cbmc/Makefile index 79224766188..8132097565c 100644 --- a/src/cbmc/Makefile +++ b/src/cbmc/Makefile @@ -28,7 +28,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../assembler/assembler$(LIBEXT) \ ../solvers/solvers$(LIBEXT) \ ../util/util$(LIBEXT) \ - ../miniz/miniz$(OBJEXT) + ../miniz/miniz$(OBJEXT) \ + ../json/json$(LIBEXT) INCLUDES= -I .. diff --git a/src/cbmc/cbmc_parse_options.cpp b/src/cbmc/cbmc_parse_options.cpp index e0e3b7db70e..5ed5d28054e 100644 --- a/src/cbmc/cbmc_parse_options.cpp +++ b/src/cbmc/cbmc_parse_options.cpp @@ -1155,7 +1155,7 @@ void cbmc_parse_optionst::help() // NOLINTNEXTLINE(whitespace/line_length) " --java-max-vla-length limit the length of user-code-created arrays\n" // NOLINTNEXTLINE(whitespace/line_length) - " --java-cp-include-files regexp of class files to load\n" + " --java-cp-include-files regexp or JSON list of files to load (with '@' prefix)\n" " --java-unwind-enum-static try to unwind loops in static initialization of enums\n" "\n" "Semantic transformations:\n" diff --git a/src/cegis/Makefile b/src/cegis/Makefile index 37fe5416953..f1a38ce4915 100644 --- a/src/cegis/Makefile +++ b/src/cegis/Makefile @@ -116,7 +116,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../cbmc/cbmc_dimacs$(OBJEXT) ../cbmc/all_properties$(OBJEXT) \ ../cbmc/fault_localization$(OBJEXT) \ ../cbmc/symex_coverage$(OBJEXT) \ - ../miniz/miniz$(OBJEXT) + ../miniz/miniz$(OBJEXT) \ + ../json/json$(LIBEXT) INCLUDES= -I .. diff --git a/src/goto-cc/Makefile b/src/goto-cc/Makefile index 04261db95f0..3079e7ebb00 100644 --- a/src/goto-cc/Makefile +++ b/src/goto-cc/Makefile @@ -14,7 +14,8 @@ OBJ += ../big-int/big-int$(LIBEXT) \ ../xmllang/xmllang$(LIBEXT) \ ../assembler/assembler$(LIBEXT) \ ../langapi/langapi$(LIBEXT) \ - ../miniz/miniz$(OBJEXT) + ../miniz/miniz$(OBJEXT) \ + ../json/json$(LIBEXT) INCLUDES= -I .. diff --git a/src/goto-diff/Makefile b/src/goto-diff/Makefile index c003d0c96b0..fd18897aaea 100644 --- a/src/goto-diff/Makefile +++ b/src/goto-diff/Makefile @@ -14,7 +14,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../xmllang/xmllang$(LIBEXT) \ ../util/util$(LIBEXT) \ ../solvers/solvers$(LIBEXT) \ - ../miniz/miniz$(OBJEXT) + ../miniz/miniz$(OBJEXT) \ + ../json/json$(LIBEXT) INCLUDES= -I .. diff --git a/src/goto-instrument/Makefile b/src/goto-instrument/Makefile index f79b62d806f..4cbd6121b24 100644 --- a/src/goto-instrument/Makefile +++ b/src/goto-instrument/Makefile @@ -38,7 +38,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../xmllang/xmllang$(LIBEXT) \ ../util/util$(LIBEXT) \ ../solvers/solvers$(LIBEXT) \ - ../miniz/miniz$(OBJEXT) + ../miniz/miniz$(OBJEXT) \ + ../json/json$(LIBEXT) INCLUDES= -I .. diff --git a/src/java_bytecode/jar_file.cpp b/src/java_bytecode/jar_file.cpp index f7cb0726494..0f45af67d33 100644 --- a/src/java_bytecode/jar_file.cpp +++ b/src/java_bytecode/jar_file.cpp @@ -8,10 +8,11 @@ Author: Daniel Kroening, kroening@kroening.com #include #include -#include +#include +#include #include "jar_file.h" #include - +#include /*******************************************************************\ Function: jar_filet::open @@ -24,7 +25,9 @@ Function: jar_filet::open \*******************************************************************/ -void jar_filet::open(std::string &java_cp_include_files, const std::string &filename) +void jar_filet::open( + std::string &java_cp_include_files, + const std::string &filename) { if(!mz_ok) { @@ -35,6 +38,32 @@ void jar_filet::open(std::string &java_cp_include_files, const std::string &file if(mz_ok) { + // '@' signals file reading with list of class files to load + bool regex_match=java_cp_include_files[0]!='@'; + std::regex regex_matcher; + std::smatch string_matcher; + std::unordered_set set_matcher; + jsont json_cp_config; + if(regex_match) + regex_matcher=std::regex(java_cp_include_files); + else + { + assert(java_cp_include_files.length()>1); + if(parse_json( + java_cp_include_files.substr(1), + get_message_handler(), + json_cp_config)) + throw "cannot read JSON input configuration for JAR loading"; + assert(json_cp_config.is_object() && "JSON has wrong format"); + jsont include_files=json_cp_config["classFiles"]; + assert(include_files.is_array() && "JSON has wrong format"); + for(const jsont &file_entry : include_files.array) + { + assert(file_entry.is_string()); + set_matcher.insert(file_entry.value); + } + } + std::size_t number_of_files= mz_zip_reader_get_num_files(&zip); @@ -47,11 +76,16 @@ void jar_filet::open(std::string &java_cp_include_files, const std::string &file mz_zip_reader_get_filename(&zip, i, filename_char, filename_length); assert(filename_length==filename_len); std::string file_name(filename_char); - std::smatch string_matcher; - std::regex matcher(java_cp_include_files); - // load .class files only if they match regex - if(std::regex_match(file_name, string_matcher, matcher) || - !has_suffix(file_name, ".class")) + + // non-class files are loaded in any case + bool add_file=!has_suffix(file_name, ".class"); + // load .class file only if they match regex + if(regex_match) + add_file|=std::regex_match(file_name, string_matcher, regex_matcher); + // load .class file only if it is in the match set + else + add_file|=set_matcher.count(file_name)>0; + if(add_file) { index.push_back(file_name); filtered_jar[filtered_index]=i; diff --git a/src/java_bytecode/jar_file.h b/src/java_bytecode/jar_file.h index 7670cbf6a8b..a1ff04bb933 100644 --- a/src/java_bytecode/jar_file.h +++ b/src/java_bytecode/jar_file.h @@ -16,8 +16,9 @@ Author: Daniel Kroening, kroening@kroening.com #include #include #include +#include -class jar_filet +class jar_filet:public messaget { public: jar_filet():mz_ok(false) { } @@ -48,7 +49,7 @@ class jar_filet std::map index_map; }; -class jar_poolt +class jar_poolt:public messaget { public: void set_java_cp_include_files(std::string &_java_cp_include_files) @@ -62,6 +63,7 @@ class jar_poolt if(it==file_map.end()) { jar_filet &jar_file=file_map[file_name]; + jar_file.set_message_handler(get_message_handler()); jar_file.open(java_cp_include_files, file_name); return jar_file; } diff --git a/src/java_bytecode/java_class_loader.h b/src/java_bytecode/java_class_loader.h index 8e8f5c5b82c..e76d5894860 100644 --- a/src/java_bytecode/java_class_loader.h +++ b/src/java_bytecode/java_class_loader.h @@ -23,6 +23,7 @@ class java_class_loadert:public messaget void set_java_cp_include_files(std::string &java_cp_include_files) { jar_pool.set_java_cp_include_files(java_cp_include_files); + jar_pool.set_message_handler(get_message_handler()); } // maps class names to the parse trees diff --git a/src/symex/Makefile b/src/symex/Makefile index f177e91bc07..e887ca55352 100644 --- a/src/symex/Makefile +++ b/src/symex/Makefile @@ -17,7 +17,8 @@ OBJ += ../ansi-c/ansi-c$(LIBEXT) \ ../pointer-analysis/dereference$(OBJEXT) \ ../goto-instrument/cover$(OBJEXT) \ ../path-symex/path-symex$(LIBEXT) \ - ../miniz/miniz$(OBJEXT) + ../miniz/miniz$(OBJEXT) \ + ../json/json$(LIBEXT) INCLUDES= -I .. From 469897f051b799212c5ca18eb3e60f09b80fa541 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Tue, 7 Mar 2017 13:32:27 +0100 Subject: [PATCH 38/67] add jars from JSON config to classpath --- src/java_bytecode/java_bytecode_language.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/java_bytecode/java_bytecode_language.cpp b/src/java_bytecode/java_bytecode_language.cpp index 6a0327968b1..923a7efcf8d 100644 --- a/src/java_bytecode/java_bytecode_language.cpp +++ b/src/java_bytecode/java_bytecode_language.cpp @@ -13,6 +13,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include #include +#include #include @@ -59,6 +60,25 @@ void java_bytecode_languaget::get_language_options(const cmdlinet &cmd) java_cp_include_files=cmd.get_value("java-cp-include-files"); else java_cp_include_files=".*"; + // load file list from JSON file + if(java_cp_include_files[0]=='@') + { + jsont json_cp_config; + if(parse_json( + java_cp_include_files.substr(1), + get_message_handler(), + json_cp_config)) + throw "cannot read JSON input configuration for JAR loading"; + assert(json_cp_config.is_object() && "JSON has wrong format"); + jsont include_files=json_cp_config["jar"]; + assert(include_files.is_array() && "JSON has wrong format"); + // add jars from JSON config file to classpath + for(const jsont &file_entry : include_files.array) + { + assert(file_entry.is_string() && has_suffix(file_entry.value, ".jar")); + config.java.classpath.push_back(file_entry.value); + } + } } /*******************************************************************\ From 3d009a9e8a459421bf916a6d5491a537b2e08e9d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Tue, 7 Mar 2017 14:51:08 +0100 Subject: [PATCH 39/67] add regression test --- regression/cbmc-java/jar-file4/A.jar | Bin 0 -> 721 bytes regression/cbmc-java/jar-file4/B.jar | Bin 0 -> 721 bytes regression/cbmc-java/jar-file4/C.jar | Bin 0 -> 934 bytes regression/cbmc-java/jar-file4/jar.json | 12 ++++++++++++ regression/cbmc-java/jar-file4/test.desc | 10 ++++++++++ 5 files changed, 22 insertions(+) create mode 100644 regression/cbmc-java/jar-file4/A.jar create mode 100644 regression/cbmc-java/jar-file4/B.jar create mode 100644 regression/cbmc-java/jar-file4/C.jar create mode 100644 regression/cbmc-java/jar-file4/jar.json create mode 100644 regression/cbmc-java/jar-file4/test.desc diff --git a/regression/cbmc-java/jar-file4/A.jar b/regression/cbmc-java/jar-file4/A.jar new file mode 100644 index 0000000000000000000000000000000000000000..e721e6f32f945341ca9aafca44a794bb16cfeb02 GIT binary patch literal 721 zcmWIWW@Zs#;Nak3$Pf4PVn70%3@i-3t|5-Po_=on|4uP5Ff#;rvvYt{FhP|C;M6Pv zQ~}rQ>*(j{<{BKL=j-;__snS@Z(Y5MyxzK6=gyqp9At3C_`%a6JuhD!Pv48Bt5`TA zUPvC1mXg%U_#v*U_I!z!#dC4dC*rEp7_Mf2D*9N&2zG^l;4&o_pdGG2jBrIdnim9s zvRR2mX_+~x#ww0_$vKI|#jgIo-iI9oYA>t!?p9O#8lCUNZ`vBR!Q6F1Q-DTQz@Ge9 ztE3-^O$zxFE!Xwnp!|b=p>*bhhozrA-fM1bzd!yygPO&wL#{dx7N&33mAAJ0#`)#k z48dDhyY+rAXE8jV@^MLVY1z5E+_@#Co*eA|-%e(4vW~UWax%H@c6Uu&aOj=WCeQnJ zM6c^=-F0mnhxA#E$@xYO>~|TM*coqqsFg9=oA_n@4?Z^oV>i*uG1Hc6ac>E6$vE ze0%0HG0}sPH<+z@1&;seJ8r*CB8U6P#@HjG)}OZV_A!P#r$zWp;kmxxiSXJZv4?-I z=u~tM?3bNZH7EDlG{JALIO}_I-!%OL2i}6vmH++&gC>v>6nKnGA`GZ002aNV6o3lg zQ3^^A=vtBE1Qh=WU<+izwIZbkWD`JfhwLy=+#$eWAQL?%1H4(;Kq{Dla5snnb~gZw CHqIXa literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/jar-file4/B.jar b/regression/cbmc-java/jar-file4/B.jar new file mode 100644 index 0000000000000000000000000000000000000000..d381e413e74f2aa5d1f92381ec7fe608679b7e81 GIT binary patch literal 721 zcmWIWW@Zs#;Nak3C=U1YVn70%3@i-3t|5-Po_=on|4uP5Ff#;rvvYt{FhP|C;M6Pv zQ~}rQ>*(j{<{BKL=j-;__snS@Z(Y5MyxzK6=gyqp9At3C_`%a6JuhD!Pv48Bt5`TA zUPvC1mXg%U_#v*U_I!z!#dC4dC*rEp7_Mf2D*9N&2zG^l;4&o_pdGG2jBrIdnim9s zvRR2mX_+~x#wt#F$vKI|#jgIo-iI9oYA-Lln|61`kH3Y&RVy^NG~E;77i)34*!-wA zIQ*_aut(6x{7Q``_WA~UuQ|Ld{P{Ebzu!Ca=TBWNv&G?s{QMJL*roMui`)>qp?twQ z+3Q7^{^b@9qQIepCtu>P_P*wY%PRA_JeQrmG^OPP=kb~6 z<{#hgne|L`p=|;C7b(TQA9MNs-$>e^E8v)Or~%rTH#=kQTIYU6gN z-;34QWKwO#biP_fuh(^cb4~c4MDz{Dzl@+Lv^lv+>OU}O0vSPp$H*kYfSLke(F;le zr~n?Np!9&Q6**2o@s9wuKqg!(Qffdp0Tg%04g*(j{<{BKL=j-;__snS@Z(Y5MyxzK6=gyqp9At3C_`%a6JuhD!Pv48Bt5`TA zUPvC1mXg%U_#v*U_I!z!#dC4dC*rEp7_Mf2D*9N&2zG^l;4&o_pdGG2jBv&AXjCuo z0cEoii_$W4QjPVJa}tY-eS>2Cg&jp~H{UJWEkD(1={5c%UKd##XPubMqPxOV*iOzs z?ZdWQ_RU-K&c3uq&??>SSR&rJv ziT4i4va`JsduL@3xcy<$LA6U8HoRESQ90Yd{JYGZ_WVRohaAp|w;GeOss)a0?BU$X zqQ$#6(9@#lQF@|G3EQUQXC^u%D)$^p308QnzgNg$d%LZs!B%0nqWmx0l&^aGs(qi~ zxqq$Y(q@$x`)=~yTdKKhiDTmn2TX z?49N|O)EjJ&w%(^$lVXOM%fRp!H`EL8T6;>I$ulW4QyGAB(U1oJpk-#p=bDQs+ zEfkIUd^%kq-b66;T&u{H$5L6(uk`Df?zEFUY@uSi-MVdM^PhX+B7OmpmaVCEP1bH7 zKk$58|Nq4+%{ix6h#3Y=)cQ1M{efd5bEiJM{7`N2YZqII`Y-o)BtCqm^Z(3R?&Ggl z>Lyej`^)#fWzzh_XZsc!SXvaX=RbA$!#pmvXP3U@W;IH&MHjAIYpl2Rs68lU{uE0H zyurx8a1@w41H2iTL>N#LHZ0YG5;iJ;r&LffN7ss+)IiA^0c?RxxK^Y@j%)%bNg_K8 clq3=0Fp!CwKm)v4*+BBlK)4e~UkAGy09`dfUjP6A literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/jar-file4/jar.json b/regression/cbmc-java/jar-file4/jar.json new file mode 100644 index 00000000000..09df8008b8c --- /dev/null +++ b/regression/cbmc-java/jar-file4/jar.json @@ -0,0 +1,12 @@ +{ + "jar": + [ + "A.jar", + "B.jar" + ], + "classFiles": + [ + "jarfile3$A.class", + "jarfile3.class" + ] +} diff --git a/regression/cbmc-java/jar-file4/test.desc b/regression/cbmc-java/jar-file4/test.desc new file mode 100644 index 00000000000..5c34bdcd5a8 --- /dev/null +++ b/regression/cbmc-java/jar-file4/test.desc @@ -0,0 +1,10 @@ +CORE +C.jar +--function jarfile3.f --java-cp-include-files "@jar.json" +^EXIT=10$ +^SIGNAL=0$ +.*SUCCESS$ +.*FAILURE$ +^VERIFICATION FAILED +-- +^warning: ignoring From f6d9f3bebc16ed3f70e6446e4a357c751d884c49 Mon Sep 17 00:00:00 2001 From: Vlastimil Zeman Date: Fri, 10 Mar 2017 11:58:17 +0000 Subject: [PATCH 40/67] Support for Linux based on musl-libc. Change `#ifdef __linux__` and `#if defined(__linux__)` when it really means *linux with glibc*. To avoid failures and be more specific it is now adding `defined(__GLIBC__)` to check if `glibc` is present. --- regression/cpp/enum8/test.desc | 2 +- scripts/minisat-2.2.1-patch | 12 ++++++++++++ src/util/memory_info.cpp | 2 +- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/regression/cpp/enum8/test.desc b/regression/cpp/enum8/test.desc index a003b07b93c..f935f5ace1b 100644 --- a/regression/cpp/enum8/test.desc +++ b/regression/cpp/enum8/test.desc @@ -1,6 +1,6 @@ CORE main.cpp - +--std=c++11 ^EXIT=0$ ^SIGNAL=0$ -- diff --git a/scripts/minisat-2.2.1-patch b/scripts/minisat-2.2.1-patch index ec0fa3e439d..f00ea308d59 100644 --- a/scripts/minisat-2.2.1-patch +++ b/scripts/minisat-2.2.1-patch @@ -196,3 +196,15 @@ diff -urN minisat-2.2.1/minisat/utils/ParseUtils.h minisat-2.2.1.patched/minisat int operator * () const { return (pos >= size) ? EOF : buf[pos]; } void operator ++ () { pos++; assureLookahead(); } +diff -urN minisat-2.2.1/minisat/utils/System.h minisat-2.2.1.patched/minisat/utils/System.h +--- minisat-2.2.1/minisat/utils/System.h 2017-02-21 18:23:22.727464369 +0000 ++++ minisat-2.2.1.patched/minisat/utils/System.h 2017-02-21 18:23:14.451343361 +0000 +@@ -21,7 +21,7 @@ + #ifndef Minisat_System_h + #define Minisat_System_h + +-#if defined(__linux__) ++#if defined(__linux__) && defined(__GLIBC__) + #include + #endif + diff --git a/src/util/memory_info.cpp b/src/util/memory_info.cpp index cb8b0161252..af4f2ef1d52 100644 --- a/src/util/memory_info.cpp +++ b/src/util/memory_info.cpp @@ -39,7 +39,7 @@ Function: memory_info void memory_info(std::ostream &out) { - #ifdef __linux__ + #if defined(__linux__) && defined(__GLIBC__) // NOLINTNEXTLINE(readability/identifiers) struct mallinfo m = mallinfo(); out << " non-mmapped space allocated from system: " << m.arena << "\n"; From 50c28c36171ffbb8c46ad4047d869cd80c5813ff Mon Sep 17 00:00:00 2001 From: Vlastimil Zeman Date: Fri, 10 Mar 2017 12:03:46 +0000 Subject: [PATCH 41/67] Add test for Alpine linux (musl-libc). - new environment in matrix that run compilation in alpine docker container. - reordering matrix environments from the longest run to the shortest run time. - rewrite of `script` to be able to run compilation in a container if needed. --- .travis.yml | 51 +++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/.travis.yml b/.travis.yml index 2f1c8103990..d74ec93f7e3 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,35 @@ language: cpp -sudo: false - matrix: include: + + # Alpine Linux with musl-libc using g++ + - os: linux + sudo: required + compiler: gcc + services: + - docker + before_install: + - docker pull diffblue/cbmc-builder:alpine + env: + - PRE_COMMAND="docker run -v ${TRAVIS_BUILD_DIR}:/cbmc diffblue/cbmc-builder:alpine" + - COMPILER=g++ + + # OS X using g++ + - os: osx + sudo: false + compiler: gcc + env: COMPILER=g++ + + # OS X using clang++ + - os: osx + sudo: false + compiler: clang + env: COMPILER=clang++ + + # Ubuntu Linux with glibc using g++-5 - os: linux + sudo: false compiler: gcc addons: apt: @@ -18,7 +43,10 @@ matrix: - mkdir bin ; ln -s /usr/bin/gcc-5 bin/gcc # env: COMPILER=g++-5 SAN_FLAGS="-fsanitize=undefined -fno-sanitize-recover -fno-omit-frame-pointer" env: COMPILER=g++-5 + + # Ubuntu Linux with glibc using clang++-3.7 - os: linux + sudo: false compiler: clang addons: apt: @@ -34,18 +62,17 @@ matrix: - mkdir bin ; ln -s /usr/bin/clang-3.7 bin/gcc # env: COMPILER=clang++-3.7 SAN_FLAGS="-fsanitize=undefined -fno-sanitize-recover=undefined,integer -fno-omit-frame-pointer" env: COMPILER=clang++-3.7 - - os: osx - compiler: gcc - env: COMPILER=g++ - - os: osx - compiler: clang - env: COMPILER=clang++ + - env: NAME="CPP-LINT" script: scripts/travis_lint.sh || true script: - if [ -L bin/gcc ] ; then export PATH=$PWD/bin:$PATH ; fi ; - make -C src minisat2-download && - make -C src CXX=$COMPILER CXXFLAGS="-Wall -O2 -g -Werror -Wno-deprecated-register -pedantic -Wno-sign-compare" -j2 && - env UBSAN_OPTIONS=print_stacktrace=1 make -C regression test && - make -C src CXX=$COMPILER CXXFLAGS=$FLAGS -j2 cegis.dir clobber.dir memory-models.dir musketeer.dir + COMMAND="make -C src minisat2-download" && + eval ${PRE_COMMAND} ${COMMAND} && + COMMAND="make -C src CXX=$COMPILER CXXFLAGS=\"-Wall -O2 -g -Werror -Wno-deprecated-register -pedantic -Wno-sign-compare\" -j2" && + eval ${PRE_COMMAND} ${COMMAND} && + COMMAND="env UBSAN_OPTIONS=print_stacktrace=1 make -C regression test" && + eval ${PRE_COMMAND} ${COMMAND} && + COMMAND="make -C src CXX=$COMPILER CXXFLAGS=$FLAGS -j2 cegis.dir clobber.dir memory-models.dir musketeer.dir" && + eval ${PRE_COMMAND} ${COMMAND} From b473638813d33a3439f45f6768f092bd29ac3bec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Fri, 10 Mar 2017 11:18:52 +0100 Subject: [PATCH 42/67] take comments into account --- src/java_bytecode/jar_file.cpp | 14 ++++--- src/java_bytecode/jar_file.h | 9 ++-- src/java_bytecode/java_bytecode_language.cpp | 43 ++++++++++++-------- src/java_bytecode/java_class_loader.h | 1 + 4 files changed, 38 insertions(+), 29 deletions(-) diff --git a/src/java_bytecode/jar_file.cpp b/src/java_bytecode/jar_file.cpp index 0f45af67d33..0980e1466ea 100644 --- a/src/java_bytecode/jar_file.cpp +++ b/src/java_bytecode/jar_file.cpp @@ -8,11 +8,11 @@ Author: Daniel Kroening, kroening@kroening.com #include #include -#include #include -#include "jar_file.h" + +#include #include -#include +#include "jar_file.h" /*******************************************************************\ Function: jar_filet::open @@ -54,9 +54,11 @@ void jar_filet::open( get_message_handler(), json_cp_config)) throw "cannot read JSON input configuration for JAR loading"; - assert(json_cp_config.is_object() && "JSON has wrong format"); + if(!json_cp_config.is_object()) + throw "the JSON file has a wrong format"; jsont include_files=json_cp_config["classFiles"]; - assert(include_files.is_array() && "JSON has wrong format"); + if(!include_files.is_array()) + throw "the JSON file has a wrong format"; for(const jsont &file_entry : include_files.array) { assert(file_entry.is_string()); @@ -84,7 +86,7 @@ void jar_filet::open( add_file|=std::regex_match(file_name, string_matcher, regex_matcher); // load .class file only if it is in the match set else - add_file|=set_matcher.count(file_name)>0; + add_file|=set_matcher.find(file_name)!=set_matcher.end(); if(add_file) { index.push_back(file_name); diff --git a/src/java_bytecode/jar_file.h b/src/java_bytecode/jar_file.h index a1ff04bb933..c168b8b4199 100644 --- a/src/java_bytecode/jar_file.h +++ b/src/java_bytecode/jar_file.h @@ -22,14 +22,13 @@ class jar_filet:public messaget { public: jar_filet():mz_ok(false) { } - inline explicit jar_filet(const std::string &file_name) { } ~jar_filet(); void open(std::string &java_cp_include_files, const std::string &); // Test for error; 'true' means we are good. - inline explicit operator bool() const { return mz_ok; } + explicit operator bool() const { return mz_ok; } typedef std::vector indext; indext index; @@ -45,8 +44,6 @@ class jar_filet:public messaget protected: mz_zip_archive zip; bool mz_ok; - std::string matcher; - std::map index_map; }; class jar_poolt:public messaget @@ -56,9 +53,11 @@ class jar_poolt:public messaget { java_cp_include_files=_java_cp_include_files; } + jar_filet &operator()(const std::string &file_name) { - assert(!java_cp_include_files.empty() && "class regexp cannot be empty"); + if(java_cp_include_files.empty()) + throw "class regexp cannot be empty"; file_mapt::iterator it=file_map.find(file_name); if(it==file_map.end()) { diff --git a/src/java_bytecode/java_bytecode_language.cpp b/src/java_bytecode/java_bytecode_language.cpp index 923a7efcf8d..0e2eb25d0ec 100644 --- a/src/java_bytecode/java_bytecode_language.cpp +++ b/src/java_bytecode/java_bytecode_language.cpp @@ -56,29 +56,36 @@ void java_bytecode_languaget::get_language_options(const cmdlinet &cmd) lazy_methods_mode=LAZY_METHODS_MODE_CONTEXT_INSENSITIVE; else lazy_methods_mode=LAZY_METHODS_MODE_EAGER; + if(cmd.isset("java-cp-include-files")) - java_cp_include_files=cmd.get_value("java-cp-include-files"); - else - java_cp_include_files=".*"; - // load file list from JSON file - if(java_cp_include_files[0]=='@') { - jsont json_cp_config; - if(parse_json( - java_cp_include_files.substr(1), - get_message_handler(), - json_cp_config)) - throw "cannot read JSON input configuration for JAR loading"; - assert(json_cp_config.is_object() && "JSON has wrong format"); - jsont include_files=json_cp_config["jar"]; - assert(include_files.is_array() && "JSON has wrong format"); - // add jars from JSON config file to classpath - for(const jsont &file_entry : include_files.array) + java_cp_include_files=cmd.get_value("java-cp-include-files"); + // load file list from JSON file + if(java_cp_include_files[0]=='@') { - assert(file_entry.is_string() && has_suffix(file_entry.value, ".jar")); - config.java.classpath.push_back(file_entry.value); + jsont json_cp_config; + if(parse_json( + java_cp_include_files.substr(1), + get_message_handler(), + json_cp_config)) + throw "cannot read JSON input configuration for JAR loading"; + + if(!json_cp_config.is_object()) + throw "the JSON file has a wrong format"; + jsont include_files=json_cp_config["jar"]; + if(!include_files.is_array()) + throw "the JSON file has a wrong format"; + + // add jars from JSON config file to classpath + for(const jsont &file_entry : include_files.array) + { + assert(file_entry.is_string() && has_suffix(file_entry.value, ".jar")); + config.java.classpath.push_back(file_entry.value); + } } } + else + java_cp_include_files=".*"; } /*******************************************************************\ diff --git a/src/java_bytecode/java_class_loader.h b/src/java_bytecode/java_class_loader.h index e76d5894860..dfd57ac9ac7 100644 --- a/src/java_bytecode/java_class_loader.h +++ b/src/java_bytecode/java_class_loader.h @@ -20,6 +20,7 @@ class java_class_loadert:public messaget { public: java_bytecode_parse_treet &operator()(const irep_idt &); + void set_java_cp_include_files(std::string &java_cp_include_files) { jar_pool.set_java_cp_include_files(java_cp_include_files); From 53fad70f4408487780748985a02d5df32b96a39d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Fri, 10 Mar 2017 14:10:38 +0100 Subject: [PATCH 43/67] change from vector indices to map --- src/java_bytecode/jar_file.cpp | 36 +++++++++---------------- src/java_bytecode/jar_file.h | 6 ++--- src/java_bytecode/java_class_loader.cpp | 11 ++++---- src/java_bytecode/java_class_loader.h | 2 +- 4 files changed, 20 insertions(+), 35 deletions(-) diff --git a/src/java_bytecode/jar_file.cpp b/src/java_bytecode/jar_file.cpp index 0980e1466ea..07d7719e500 100644 --- a/src/java_bytecode/jar_file.cpp +++ b/src/java_bytecode/jar_file.cpp @@ -69,7 +69,6 @@ void jar_filet::open( std::size_t number_of_files= mz_zip_reader_get_num_files(&zip); - size_t filtered_index=0; for(std::size_t i=0; isecond; mz_zip_archive_file_stat file_stat; memset(&file_stat, 0, sizeof(file_stat)); mz_bool stat_ok=mz_zip_reader_file_stat(&zip, real_index, &file_stat); @@ -173,24 +174,11 @@ Function: jar_filet::get_manifest jar_filet::manifestt jar_filet::get_manifest() { - std::size_t i=0; - bool found=false; - - for(const auto &e : index) - { - if(e=="META-INF/MANIFEST.MF") - { - found=true; - break; - } - - i++; - } - - if(!found) + auto entry=filtered_jar.find("META-INF/MANIFEST.MF"); + if(entry==filtered_jar.end()) return manifestt(); - std::string dest=get_entry(i); + std::string dest=get_entry(entry->first); std::istringstream in(dest); manifestt manifest; diff --git a/src/java_bytecode/jar_file.h b/src/java_bytecode/jar_file.h index c168b8b4199..9407e711128 100644 --- a/src/java_bytecode/jar_file.h +++ b/src/java_bytecode/jar_file.h @@ -30,13 +30,11 @@ class jar_filet:public messaget // Test for error; 'true' means we are good. explicit operator bool() const { return mz_ok; } - typedef std::vector indext; - indext index; // map internal index to real index in jar central directory - typedef std::map filtered_jart; + typedef std::map filtered_jart; filtered_jart filtered_jar; - std::string get_entry(std::size_t i); + std::string get_entry(const irep_idt &); typedef std::map manifestt; manifestt get_manifest(); diff --git a/src/java_bytecode/java_class_loader.cpp b/src/java_bytecode/java_class_loader.cpp index dc4330aa00c..c8e6bbf5bb4 100644 --- a/src/java_bytecode/java_class_loader.cpp +++ b/src/java_bytecode/java_class_loader.cpp @@ -98,7 +98,7 @@ java_bytecode_parse_treet &java_class_loadert::get_parse_tree( debug() << "Getting class `" << class_name << "' from JAR " << jf << eom; - std::string data=jar_pool(jf).get_entry(jm_it->second.index); + std::string data=jar_pool(jf).get_entry(jm_it->second.class_file_name); std::istringstream istream(data); @@ -129,7 +129,7 @@ java_bytecode_parse_treet &java_class_loadert::get_parse_tree( debug() << "Getting class `" << class_name << "' from JAR " << cp << eom; - std::string data=jar_pool(cp).get_entry(jm_it->second.index); + std::string data=jar_pool(cp).get_entry(jm_it->second.class_file_name); std::istringstream istream(data); @@ -223,11 +223,10 @@ void java_class_loadert::read_jar_file(const irep_idt &file) debug() << "adding JAR file `" << file << "'" << eom; auto &jm=jar_map[file]; - std::size_t number_of_files=jar_file.index.size(); - for(std::size_t i=0; i Date: Thu, 2 Mar 2017 15:46:03 +0000 Subject: [PATCH 44/67] Restructuring such that the exceptions instrumentation is added in one pass over the goto-program --- src/goto-programs/goto_program_template.h | 8 + src/goto-programs/remove_exceptions.cpp | 286 +++++++----------- .../java_bytecode_convert_method.cpp | 22 +- src/util/std_code.h | 4 +- 4 files changed, 124 insertions(+), 196 deletions(-) diff --git a/src/goto-programs/goto_program_template.h b/src/goto-programs/goto_program_template.h index 77161fcb4d8..bd9cb39c73e 100644 --- a/src/goto-programs/goto_program_template.h +++ b/src/goto-programs/goto_program_template.h @@ -474,6 +474,14 @@ class goto_program_templatet instructions.clear(); } + targett get_end_function() + { + assert(!instructions.empty()); + targett end_function=--instructions.end(); + assert(end_function->is_end_function()); + return end_function; + } + //! Copy a full goto program, preserving targets void copy_from(const goto_program_templatet &src); diff --git a/src/goto-programs/remove_exceptions.cpp b/src/goto-programs/remove_exceptions.cpp index 4b4e5debe35..8bbbd79e165 100644 --- a/src/goto-programs/remove_exceptions.cpp +++ b/src/goto-programs/remove_exceptions.cpp @@ -41,28 +41,24 @@ class remove_exceptionst void add_exceptional_returns( const goto_functionst::function_mapt::iterator &); - void replace_throws( - const goto_functionst::function_mapt::iterator &); - - void instrument_function_calls( - const goto_functionst::function_mapt::iterator &); - - void instrument_exception_handlers( - const goto_functionst::function_mapt::iterator &); - void add_gotos( - const goto_functionst::function_mapt::iterator &); + void instrument_exception_handler( + const goto_functionst::function_mapt::iterator &, + const goto_programt::instructionst::iterator &); - void add_throw_gotos( + void instrument_throw( const goto_functionst::function_mapt::iterator &, const goto_programt::instructionst::iterator &, const stack_catcht &, std::vector &); - void add_function_call_gotos( + void instrument_function_call( const goto_functionst::function_mapt::iterator &, const goto_programt::instructionst::iterator &, const stack_catcht &, std::vector &); + + void instrument_exceptions( + const goto_functionst::function_mapt::iterator &); }; /*******************************************************************\ @@ -99,7 +95,7 @@ void remove_exceptionst::add_exceptional_returns( // function calls that may escape exceptions. However, this will // require multiple passes. bool add_exceptional_var=false; - Forall_goto_program_instructions(instr_it, goto_program) + forall_goto_program_instructions(instr_it, goto_program) if(instr_it->is_throw() || instr_it->is_function_call()) { add_exceptional_var=true; @@ -125,8 +121,7 @@ void remove_exceptionst::add_exceptional_returns( // initialize the exceptional return with NULL symbol_exprt lhs_expr_null=new_symbol.symbol_expr(); - exprt rhs_expr_null; - rhs_expr_null=null_pointer_exprt(pointer_typet(empty_typet())); + null_pointer_exprt rhs_expr_null((pointer_typet(empty_typet()))); goto_programt::targett t_null= goto_program.insert_before(goto_program.instructions.begin()); t_null->make_assignment(); @@ -141,106 +136,7 @@ void remove_exceptionst::add_exceptional_returns( /*******************************************************************\ -Function: remove_exceptionst::replace_throws - -Inputs: - -Outputs: - -Purpose: turns 'throw x' in function f into an assignment to f#exc_value - -\*******************************************************************/ - -void remove_exceptionst::replace_throws( - const goto_functionst::function_mapt::iterator &func_it) -{ - const irep_idt &function_id=func_it->first; - goto_programt &goto_program=func_it->second.body; - - if(goto_program.empty()) - return; - - Forall_goto_program_instructions(instr_it, goto_program) - { - if(instr_it->is_throw() && - symbol_table.has_symbol(id2string(function_id)+EXC_SUFFIX)) - { - assert(instr_it->code.operands().size()==1); - const symbolt &exc_symbol= - symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); - - // replace "throw x;" by "f#exception_value=x;" - symbol_exprt lhs_expr=exc_symbol.symbol_expr(); - // find the symbol corresponding to the thrown exceptions - exprt exc_expr=instr_it->code; - while(exc_expr.id()!=ID_symbol && exc_expr.has_operands()) - exc_expr=exc_expr.op0(); - - // add the assignment with the appropriate cast - code_assignt assignment(typecast_exprt(lhs_expr, exc_expr.type()), - exc_expr); - // now turn the `throw' into `assignment' - instr_it->type=ASSIGN; - instr_it->code=assignment; - } - } -} - -/*******************************************************************\ - -Function: remove_exceptionst::instrument_function_calls - -Inputs: - -Outputs: - -Purpose: after each function call g() in function f - adds f#exception_value=g#exception_value; - -\*******************************************************************/ - -void remove_exceptionst::instrument_function_calls( - const goto_functionst::function_mapt::iterator &func_it) -{ - const irep_idt &caller_id=func_it->first; - goto_programt &goto_program=func_it->second.body; - - if(goto_program.empty()) - return; - - Forall_goto_program_instructions(instr_it, goto_program) - { - if(instr_it->is_function_call()) - { - code_function_callt &function_call=to_code_function_call(instr_it->code); - const irep_idt &callee_id= - to_symbol_expr(function_call.function()).get_identifier(); - - // can exceptions escape? - if(symbol_table.has_symbol(id2string(callee_id)+EXC_SUFFIX) && - symbol_table.has_symbol(id2string(caller_id)+EXC_SUFFIX)) - { - const symbolt &callee= - symbol_table.lookup(id2string(callee_id)+EXC_SUFFIX); - const symbolt &caller= - symbol_table.lookup(id2string(caller_id)+EXC_SUFFIX); - - symbol_exprt rhs_expr=callee.symbol_expr(); - symbol_exprt lhs_expr=caller.symbol_expr(); - - goto_programt::targett t=goto_program.insert_after(instr_it); - t->make_assignment(); - t->source_location=instr_it->source_location; - t->code=code_assignt(lhs_expr, rhs_expr); - t->function=instr_it->function; - } - } - } -} - -/*******************************************************************\ - -Function: remove_exceptionst::instrument_exception_handlers +Function: remove_exceptionst::instrument_exception_handler Inputs: @@ -251,62 +147,52 @@ Purpose: at the beginning of each handler in function f \*******************************************************************/ -void remove_exceptionst::instrument_exception_handlers( - const goto_functionst::function_mapt::iterator &func_it) +void remove_exceptionst::instrument_exception_handler( + const goto_functionst::function_mapt::iterator &func_it, + const goto_programt::instructionst::iterator &instr_it) { const irep_idt &function_id=func_it->first; goto_programt &goto_program=func_it->second.body; - if(goto_program.empty()) - return; + assert(instr_it->type==CATCH && instr_it->code.has_operands()); - Forall_goto_program_instructions(instr_it, goto_program) + // retrieve the exception variable + const exprt &exception=instr_it->code.op0(); + + if(symbol_table.has_symbol(id2string(function_id)+EXC_SUFFIX)) { - // is this a handler - if(instr_it->type==CATCH && instr_it->code.has_operands()) - { - // retrieve the exception variable - const irept &exception=instr_it->code.op0(); + const symbolt &function_symbol= + symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); + // next we reset the exceptional return to NULL + symbol_exprt lhs_expr_null=function_symbol.symbol_expr(); + null_pointer_exprt rhs_expr_null((pointer_typet(empty_typet()))); - if(symbol_table.has_symbol(id2string(function_id)+EXC_SUFFIX)) - { - const symbolt &function_symbol= - symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); - // next we reset the exceptional return to NULL - symbol_exprt lhs_expr_null=function_symbol.symbol_expr(); - exprt rhs_expr_null; - rhs_expr_null=null_pointer_exprt(pointer_typet(empty_typet())); - - // add the assignment - goto_programt::targett t_null=goto_program.insert_after(instr_it); - t_null->make_assignment(); - t_null->source_location=instr_it->source_location; - t_null->code=code_assignt( - lhs_expr_null, - rhs_expr_null); - t_null->function=instr_it->function; - - // add the assignment exc=f#exception_value - symbol_exprt rhs_expr_exc=function_symbol.symbol_expr(); - - const exprt &lhs_expr_exc=static_cast(exception); - goto_programt::targett t_exc=goto_program.insert_after(instr_it); - t_exc->make_assignment(); - t_exc->source_location=instr_it->source_location; - t_exc->code=code_assignt( - typecast_exprt(lhs_expr_exc, rhs_expr_exc.type()), - rhs_expr_exc); - t_exc->function=instr_it->function; - } + // add the assignment + goto_programt::targett t_null=goto_program.insert_after(instr_it); + t_null->make_assignment(); + t_null->source_location=instr_it->source_location; + t_null->code=code_assignt( + lhs_expr_null, + rhs_expr_null); + t_null->function=instr_it->function; - instr_it->make_skip(); - } + // add the assignment exc=f#exception_value + symbol_exprt rhs_expr_exc=function_symbol.symbol_expr(); + + goto_programt::targett t_exc=goto_program.insert_after(instr_it); + t_exc->make_assignment(); + t_exc->source_location=instr_it->source_location; + t_exc->code=code_assignt( + typecast_exprt(exception, rhs_expr_exc.type()), + rhs_expr_exc); + t_exc->function=instr_it->function; } + instr_it->make_skip(); } /*******************************************************************\ -Function: remove_exceptionst::add_gotos_throw +Function: remove_exceptionst::instrument_throw Inputs: @@ -317,7 +203,7 @@ Purpose: instruments each throw with conditional GOTOS to the \*******************************************************************/ -void remove_exceptionst::add_throw_gotos( +void remove_exceptionst::instrument_throw( const goto_functionst::function_mapt::iterator &func_it, const goto_programt::instructionst::iterator &instr_it, const remove_exceptionst::stack_catcht &stack_catch, @@ -331,10 +217,7 @@ void remove_exceptionst::add_throw_gotos( assert(instr_it->code.operands().size()==1); // find the end of the function - goto_programt::targett end_function; - for(end_function=instr_it; - !end_function->is_end_function(); - end_function++) {} + goto_programt::targett end_function=goto_program.get_end_function(); if(end_function!=instr_it) { // jump to the end of the function @@ -345,6 +228,7 @@ void remove_exceptionst::add_throw_gotos( t_end->function=instr_it->function; } + // find the symbol corresponding to the caught exceptions const symbolt &exc_symbol= symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); @@ -383,22 +267,34 @@ void remove_exceptionst::add_throw_gotos( t_dead->source_location=instr_it->source_location; t_dead->function=instr_it->function; } + + // replace "throw x;" by "f#exception_value=x;" + exprt exc_expr=instr_it->code; + while(exc_expr.id()!=ID_symbol && exc_expr.has_operands()) + exc_expr=exc_expr.op0(); + + // add the assignment with the appropriate cast + code_assignt assignment(typecast_exprt(exc_thrown, exc_expr.type()), + exc_expr); + // now turn the `throw' into `assignment' + instr_it->type=ASSIGN; + instr_it->code=assignment; } /*******************************************************************\ -Function: remove_exceptionst::add_function_call_gotos +Function: remove_exceptionst::instrument_function_call Inputs: Outputs: Purpose: instruments each function call that may escape exceptions - with conditional GOTOS to the corresponding exception handlers + with conditional GOTOS to the corresponding exception handlers \*******************************************************************/ -void remove_exceptionst::add_function_call_gotos( +void remove_exceptionst::instrument_function_call( const goto_functionst::function_mapt::iterator &func_it, const goto_programt::instructionst::iterator &instr_it, const stack_catcht &stack_catch, @@ -407,6 +303,7 @@ void remove_exceptionst::add_function_call_gotos( assert(instr_it->type==FUNCTION_CALL); goto_programt &goto_program=func_it->second.body; + const irep_idt &function_id=func_it->first; // save the address of the next instruction goto_programt::instructionst::iterator next_it=instr_it; @@ -424,6 +321,18 @@ void remove_exceptionst::add_function_call_gotos( symbol_table.lookup(id2string(callee_id)+EXC_SUFFIX); symbol_exprt callee_exc=callee_exc_symbol.symbol_expr(); + // find the end of the function + goto_programt::targett end_function=goto_program.get_end_function(); + if(end_function!=instr_it) + { + // jump to the end of the function + // this will appear after the GOTO-based dynamic dispatch below + goto_programt::targett t_end=goto_program.insert_after(instr_it); + t_end->make_goto(end_function); + t_end->source_location=instr_it->source_location; + t_end->function=instr_it->function; + } + for(std::size_t i=stack_catch.size(); i-->0;) { for(std::size_t j=stack_catch[i].size(); j-->0;) @@ -464,43 +373,57 @@ void remove_exceptionst::add_function_call_gotos( t_null->source_location=instr_it->source_location; t_null->function=instr_it->function; t_null->guard=eq_null; + + // after each function call g() in function f + // adds f#exception_value=g#exception_value; + const symbolt &caller= + symbol_table.lookup(id2string(function_id)+EXC_SUFFIX); + const symbol_exprt &lhs_expr=caller.symbol_expr(); + + goto_programt::targett t=goto_program.insert_after(instr_it); + t->make_assignment(); + t->source_location=instr_it->source_location; + t->code=code_assignt(lhs_expr, callee_exc); + t->function=instr_it->function; } } /*******************************************************************\ -Function: remove_exceptionst::add_gotos +Function: remove_exceptionst::instrument_exceptions Inputs: Outputs: -Purpose: instruments each throw and function calls that may escape exceptions - with conditional GOTOS to the corresponding exception handlers +Purpose: instruments throws, function calls that may escape exceptions + and exception handlers. Additionally, it re-computes + the live-range of local variables in order to add DEAD instructions. \*******************************************************************/ -void remove_exceptionst::add_gotos( +void remove_exceptionst::instrument_exceptions( const goto_functionst::function_mapt::iterator &func_it) { stack_catcht stack_catch; // stack of try-catch blocks std::vector> stack_locals; // stack of local vars std::vector locals; - bool skip_dead=false; goto_programt &goto_program=func_it->second.body; if(goto_program.empty()) return; Forall_goto_program_instructions(instr_it, goto_program) { + // this flag is used to skip DEAD redeclaration if(!instr_it->labels.empty()) skip_dead=false; + if(instr_it->is_decl()) { code_declt decl=to_code_decl(instr_it->code); locals.push_back(decl.symbol()); } - if(instr_it->is_dead()) + else if(instr_it->is_dead()) { code_deadt dead=to_code_dead(instr_it->code); auto it=std::find(locals.begin(), @@ -569,19 +492,23 @@ void remove_exceptionst::add_gotos( } instr_it->make_skip(); } + // handler + else if(instr_it->type==CATCH && instr_it->code.has_operands()) + { + instrument_exception_handler(func_it, instr_it); + } else if(instr_it->type==THROW) { skip_dead=true; - add_throw_gotos(func_it, instr_it, stack_catch, locals); + instrument_throw(func_it, instr_it, stack_catch, locals); } else if(instr_it->type==FUNCTION_CALL) { - add_function_call_gotos(func_it, instr_it, stack_catch, locals); + instrument_function_call(func_it, instr_it, stack_catch, locals); } } } - /*******************************************************************\ Function: remove_exceptionst::operator() @@ -597,16 +524,9 @@ Function: remove_exceptionst::operator() void remove_exceptionst::operator()(goto_functionst &goto_functions) { Forall_goto_functions(it, goto_functions) - { add_exceptional_returns(it); - } Forall_goto_functions(it, goto_functions) - { - instrument_exception_handlers(it); - add_gotos(it); - instrument_function_calls(it); - replace_throws(it); - } + instrument_exceptions(it); } /*******************************************************************\ diff --git a/src/java_bytecode/java_bytecode_convert_method.cpp b/src/java_bytecode/java_bytecode_convert_method.cpp index bc13e61c1cf..678dfe13576 100644 --- a/src/java_bytecode/java_bytecode_convert_method.cpp +++ b/src/java_bytecode/java_bytecode_convert_method.cpp @@ -5,7 +5,7 @@ Module: JAVA Bytecode Language Conversion Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ -#define DEBUG + #ifdef DEBUG #include #endif @@ -1031,10 +1031,10 @@ codet java_bytecode_convert_methodt::convert_instructions( // we throw away the first statement in an exception handler // as we don't know if a function call had a normal or exceptional return - size_t e; - for(e=0; ehandler_pc) { exprt exc_var=variable( arg0, statement[0], @@ -1051,7 +1051,7 @@ codet java_bytecode_convert_methodt::convert_instructions( catch_handler_expr.get_sub().resize(1); catch_handler_expr.get_sub()[0]=exc_var; - codet catch_handler=code_expressiont(catch_handler_expr); + code_expressiont catch_handler(catch_handler_expr); code_labelt newlabel(label(std::to_string(cur_pc)), code_blockt()); @@ -1065,7 +1065,7 @@ codet java_bytecode_convert_methodt::convert_instructions( } } - if(e Date: Thu, 2 Mar 2017 16:53:29 +0000 Subject: [PATCH 45/67] Add jump to the end of the current function if a function call throws an exception for which there is no handler --- regression/cbmc-java/exceptions9/test.class | Bin 976 -> 976 bytes src/goto-programs/remove_exceptions.cpp | 29 ++---------------- .../java_bytecode_convert_method.cpp | 6 ++-- 3 files changed, 5 insertions(+), 30 deletions(-) diff --git a/regression/cbmc-java/exceptions9/test.class b/regression/cbmc-java/exceptions9/test.class index 42f38bdf8b411bc40f4fb15444a6d085cda2a375..ee137ed9bf6ccb8312157e118fe6f87aedaec1a9 100644 GIT binary patch delta 25 gcmcb>et~_13p1}OgCK)4gAjuXg9d}zet~_13p1}8gCK(ngAju%g9d~8labels.empty()) - skip_dead=false; - if(instr_it->is_decl()) { code_declt decl=to_code_decl(instr_it->code); locals.push_back(decl.symbol()); } - else if(instr_it->is_dead()) - { - code_deadt dead=to_code_dead(instr_it->code); - auto it=std::find(locals.begin(), - locals.end(), - dead.symbol()); - // avoid DEAD re-declarations - if(it==locals.end()) - { - if(skip_dead) - { - // this DEAD has been already added by a throw - instr_it->make_skip(); - } - } - else - { - locals.erase(it); - } - } - // it's a CATCH but not a handler + // it's a CATCH but not a handler (as it has no operands) else if(instr_it->type==CATCH && !instr_it->code.has_operands()) { if(instr_it->targets.empty()) // pop @@ -492,14 +468,13 @@ void remove_exceptionst::instrument_exceptions( } instr_it->make_skip(); } - // handler + // CATCH handler else if(instr_it->type==CATCH && instr_it->code.has_operands()) { instrument_exception_handler(func_it, instr_it); } else if(instr_it->type==THROW) { - skip_dead=true; instrument_throw(func_it, instr_it, stack_catch, locals); } else if(instr_it->type==FUNCTION_CALL) diff --git a/src/java_bytecode/java_bytecode_convert_method.cpp b/src/java_bytecode/java_bytecode_convert_method.cpp index 678dfe13576..3e9cebc116a 100644 --- a/src/java_bytecode/java_bytecode_convert_method.cpp +++ b/src/java_bytecode/java_bytecode_convert_method.cpp @@ -2083,7 +2083,7 @@ codet java_bytecode_convert_methodt::convert_instructions( // for each try-catch add a CATCH-PUSH instruction // each CATCH-PUSH records a list of all the handler labels // together with a list of all the exception ids - + // be aware of different try-catch blocks with the same starting pc std::size_t pos=0; std::size_t end_pc=0; @@ -2124,7 +2124,7 @@ codet java_bytecode_convert_methodt::convert_instructions( for(size_t i=0; i Date: Thu, 2 Mar 2017 16:59:39 +0000 Subject: [PATCH 46/67] Modified the expected goto-program for cbmc-java/virtual7 as exception handling instrumentation introduces new labels and GOTOs --- regression/cbmc-java/virtual7/test.desc | 1 - 1 file changed, 1 deletion(-) diff --git a/regression/cbmc-java/virtual7/test.desc b/regression/cbmc-java/virtual7/test.desc index 3846f5c4a69..2e196d82e8c 100644 --- a/regression/cbmc-java/virtual7/test.desc +++ b/regression/cbmc-java/virtual7/test.desc @@ -9,4 +9,3 @@ IF "java::D".*THEN GOTO [67] IF "java::C".*THEN GOTO [67] -- IF "java::A".*THEN GOTO -GOTO 9 From 4a446687be65bec3260dc26fe7f2cc4a292db4ee Mon Sep 17 00:00:00 2001 From: Cristina Date: Thu, 2 Mar 2017 17:13:47 +0000 Subject: [PATCH 47/67] + regression test for Java exception handling --- regression/cbmc-java/exceptions18/A.class | Bin 0 -> 241 bytes regression/cbmc-java/exceptions18/Test.class | Bin 0 -> 756 bytes regression/cbmc-java/exceptions18/Test.java | 23 +++++++++++++++++++ regression/cbmc-java/exceptions18/test.desc | 8 +++++++ 4 files changed, 31 insertions(+) create mode 100644 regression/cbmc-java/exceptions18/A.class create mode 100644 regression/cbmc-java/exceptions18/Test.class create mode 100644 regression/cbmc-java/exceptions18/Test.java create mode 100644 regression/cbmc-java/exceptions18/test.desc diff --git a/regression/cbmc-java/exceptions18/A.class b/regression/cbmc-java/exceptions18/A.class new file mode 100644 index 0000000000000000000000000000000000000000..eb37079f4ed73d57cc2b6947f9e46c6bcc1e8e5b GIT binary patch literal 241 zcmXX=Jxjzu5Pg$RlZ!?ytt{2z(%30N5Uqm6T}Z!)i|&!^9?3@hTULUFKfoU)&PE4j z-Usi&eE)oY0l30(3Ll3tj$-75=tgN}ZwdbSMMDVg%#$SKmD2KY9$GopqV3r^sZ1yO zMvThoe>1QzYT{~DUK7%-na55(C>Kv^Iob72yow9~LIRb9Q>Tkw=;vZHYpVu%|JKR9 tRYv0s9>3*=c)7wDF)J9I6JCCR-kEra`9_OLIAEUr1&|=)<>EFAy< literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/exceptions18/Test.class b/regression/cbmc-java/exceptions18/Test.class new file mode 100644 index 0000000000000000000000000000000000000000..1c2f3dba0083acf483f5b48a1fc3425e77f16268 GIT binary patch literal 756 zcmX|7O-~b16g_w5&Ac)cD71peSBs#fel!v60+j?zNH7%_5E2s;GOZ&H){ZGtqptfq z+_GjPi6(aMPjZ2t_gY=N`*H5Q=e&D=U48!vU<0cGd=xcG0UQ(qcv#lBsj(vPAII%D z-4eLvwIhLgn!Jt#6ZNR6n0{h4?&f_jnBwYKa9@ON8~t3 z5`jm195SnK8|;n2RC&+P%NM>qfew%3c01}Y`@~0nB1t#3$Y*Aaf7#eU8aCfO4?kE* z`|FY*I7qskX0#iduZ`={Z@Fbjnm=*?_?u z9#$x0S*8b_LzWD)3FIvEB&G&@QX#52Rdb*898p_6SKOMK`-;3<^M)Fme&rifPsuq( zHx)Z(RsS6R{=NPMrvt3uHoe2e9?-gWn`cx2e{VEBs%lIU&l4#ynx>t>0 Date: Mon, 13 Mar 2017 19:56:45 +0000 Subject: [PATCH 48/67] Invoked full_slicer after generic property intrumentation Invoked the full_slicer method just after generic property instrumentation so that CBMC can properly slice the program w.r.t. a given assertion in the program. Additionally, replaced returns from goto functions in goto_instrument_parse_options, as done similarly in cbmc_parse_options --- regression/goto-instrument/slice02/test.desc | 2 +- regression/goto-instrument/slice14/test.desc | 2 +- src/cbmc/cbmc_parse_options.cpp | 15 ++++++++------- .../goto_instrument_parse_options.cpp | 1 + 4 files changed, 11 insertions(+), 9 deletions(-) diff --git a/regression/goto-instrument/slice02/test.desc b/regression/goto-instrument/slice02/test.desc index 362da05d33c..2d61905c826 100644 --- a/regression/goto-instrument/slice02/test.desc +++ b/regression/goto-instrument/slice02/test.desc @@ -1,4 +1,4 @@ -KNOWNBUG +CORE main.c --pointer-check --full-slice ^EXIT=0$ diff --git a/regression/goto-instrument/slice14/test.desc b/regression/goto-instrument/slice14/test.desc index ef912633761..a2b36885fc7 100644 --- a/regression/goto-instrument/slice14/test.desc +++ b/regression/goto-instrument/slice14/test.desc @@ -1,4 +1,4 @@ -KNOWNBUG +CORE main.c --pointer-check --full-slice ^EXIT=10$ diff --git a/src/cbmc/cbmc_parse_options.cpp b/src/cbmc/cbmc_parse_options.cpp index 4c080b10ceb..e33e700e0ca 100644 --- a/src/cbmc/cbmc_parse_options.cpp +++ b/src/cbmc/cbmc_parse_options.cpp @@ -900,13 +900,6 @@ bool cbmc_parse_optionst::process_goto_program( // Similar removal of RTTI inspection: remove_instanceof(symbol_table, goto_functions); - // full slice? - if(cmdline.isset("full-slice")) - { - status() << "Performing a full slice" << eom; - full_slicer(goto_functions, ns); - } - // do partial inlining status() << "Partial Inlining" << eom; goto_partial_inline(goto_functions, ns, ui_message_handler); @@ -920,6 +913,14 @@ bool cbmc_parse_optionst::process_goto_program( // add generic checks status() << "Generic Property Instrumentation" << eom; goto_check(ns, options, goto_functions); + + // full slice? + if(cmdline.isset("full-slice")) + { + status() << "Performing a full slice" << eom; + full_slicer(goto_functions, ns); + } + // checks don't know about adjusted float expressions adjust_float_expressions(goto_functions, ns); diff --git a/src/goto-instrument/goto_instrument_parse_options.cpp b/src/goto-instrument/goto_instrument_parse_options.cpp index 209a5daeed1..594609ce8ce 100644 --- a/src/goto-instrument/goto_instrument_parse_options.cpp +++ b/src/goto-instrument/goto_instrument_parse_options.cpp @@ -1432,6 +1432,7 @@ void goto_instrument_parse_optionst::instrument_goto_program() // full slice? if(cmdline.isset("full-slice")) { + remove_returns(symbol_table, goto_functions); do_indirect_call_and_rtti_removal(); status() << "Performing a full slice" << eom; From 30fe7c8708c4431b2284ea030c97902d97663f11 Mon Sep 17 00:00:00 2001 From: Nathan Phillips Date: Tue, 14 Mar 2017 10:20:06 +0000 Subject: [PATCH 49/67] Added IDE files to .gitignore --- .gitignore | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/.gitignore b/.gitignore index dd06a376eff..cf449ea4f76 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,16 @@ # Local files generated by IDEs +.vs/* .vscode/* +~AutoRecover.* +*.sln +*.vcxproj* +scripts/__pycache__/* +src/goto-analyzer/taint_driver_scripts/.idea/* +/*.config +/*.creator +/*.creator.user +/*.files +/*.includes # compilation files *.lo From 5f272f790c0c60dc6007142c1f55a22392b5c050 Mon Sep 17 00:00:00 2001 From: Nathan Phillips Date: Tue, 14 Mar 2017 10:20:21 +0000 Subject: [PATCH 50/67] Remove unnecessary casts from json.h --- src/util/json.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/util/json.h b/src/util/json.h index 1c817e2c78a..c6ddd1b1d19 100644 --- a/src/util/json.h +++ b/src/util/json.h @@ -147,13 +147,13 @@ class json_arrayt:public jsont jsont &push_back(const jsont &json) { array.push_back(json); - return static_cast(array.back()); + return array.back(); } jsont &push_back() { array.push_back(jsont()); - return static_cast(array.back()); + return array.back(); } }; From 1855bcddf766026a99b2e0c7579a1149b3e278dd Mon Sep 17 00:00:00 2001 From: Nathan Phillips Date: Tue, 14 Mar 2017 10:20:58 +0000 Subject: [PATCH 51/67] Comment on potential gotcha Added comment on hard to track potential error caused by #define in irep_hash This could save external users time (internal users shouldn't encounter this as we don't use Boost) --- src/util/irep_hash.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/util/irep_hash.h b/src/util/irep_hash.h index 1674caaf906..b0d24221ff3 100644 --- a/src/util/irep_hash.h +++ b/src/util/irep_hash.h @@ -148,6 +148,8 @@ inline std::size_t basic_hash_finalize( return h1; } +// Boost uses the symbol hash_combine, if you're getting problems here then +// you've probably included a Boost header after this one #define hash_combine(h1, h2) \ basic_hash_combine(h1, h2) #define hash_finalize(h1, len) \ From 1a88570e1876e0139bbde0d49072e892dd8340d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matthias=20G=C3=BCdemann?= Date: Wed, 15 Mar 2017 09:23:54 +0100 Subject: [PATCH 52/67] adds java.lang.Class to load queue java.lang.Class can be used without explicit reference (cf. regression test classtest1), therefore it has to be added explicitly to the loading queue. --- regression/cbmc-java/classtest1/classtest1.class | Bin 0 -> 351 bytes regression/cbmc-java/classtest1/classtest1.java | 11 +++++++++++ regression/cbmc-java/classtest1/test.desc | 8 ++++++++ src/java_bytecode/java_class_loader.cpp | 2 ++ 4 files changed, 21 insertions(+) create mode 100644 regression/cbmc-java/classtest1/classtest1.class create mode 100644 regression/cbmc-java/classtest1/classtest1.java create mode 100644 regression/cbmc-java/classtest1/test.desc diff --git a/regression/cbmc-java/classtest1/classtest1.class b/regression/cbmc-java/classtest1/classtest1.class new file mode 100644 index 0000000000000000000000000000000000000000..e105964df9121fbb37757e0c5c9d7aee43077022 GIT binary patch literal 351 zcmYk2u};H442FLvX;O|rN)bp53@`--s!D8BU67b67>Zb!F5whim8Md1<-M3d3_Ji2 zg|HK(u-HETzdzsI_s{1SfNLBo1V|!`6g(V67!$&ot*o09{Pg095ZrEF3?W(A%G__) znW-OjR±Yg-YH)91xXzv@Y;t75WrwXKR98Ki=6l>XBmvX#kQtEuH?Tj%D^3Mk1- z-89ZLZh9r87z2a^)wg5pA|{ObJsk^YeCvQ80{9>q;~4SjlrwQ2T)u literal 0 HcmV?d00001 diff --git a/regression/cbmc-java/classtest1/classtest1.java b/regression/cbmc-java/classtest1/classtest1.java new file mode 100644 index 00000000000..532926c474d --- /dev/null +++ b/regression/cbmc-java/classtest1/classtest1.java @@ -0,0 +1,11 @@ +public class classtest1 +{ + static void main(String[] args) + { + g(classtest1.class); + } + static void g(Object c) + { + assert true; + } +} diff --git a/regression/cbmc-java/classtest1/test.desc b/regression/cbmc-java/classtest1/test.desc new file mode 100644 index 00000000000..f56857c7bf6 --- /dev/null +++ b/regression/cbmc-java/classtest1/test.desc @@ -0,0 +1,8 @@ +CORE +classtest1.class + +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/src/java_bytecode/java_class_loader.cpp b/src/java_bytecode/java_class_loader.cpp index c8e6bbf5bb4..db5f63b08b9 100644 --- a/src/java_bytecode/java_class_loader.cpp +++ b/src/java_bytecode/java_class_loader.cpp @@ -40,6 +40,8 @@ java_bytecode_parse_treet &java_class_loadert::operator()( queue.push("java.lang.Object"); // java.lang.String queue.push("java.lang.String"); + // add java.lang.Class + queue.push("java.lang.Class"); queue.push(class_name); while(!queue.empty()) From 92d589afe79f0b03f9ce86884a5babbad210b461 Mon Sep 17 00:00:00 2001 From: Cristina Date: Wed, 21 Dec 2016 17:53:13 +0000 Subject: [PATCH 53/67] Tag the exceptional return of the entry function as output --- src/java_bytecode/java_entry_point.cpp | 28 ++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/src/java_bytecode/java_entry_point.cpp b/src/java_bytecode/java_entry_point.cpp index 44a59091ba2..60678dadfa1 100644 --- a/src/java_bytecode/java_entry_point.cpp +++ b/src/java_bytecode/java_entry_point.cpp @@ -26,6 +26,7 @@ Author: Daniel Kroening, kroening@kroening.com #include #include +#include #include "java_entry_point.h" #include "java_object_factory.h" @@ -325,6 +326,24 @@ void java_record_outputs( init_code.move_to_operands(output); } } + + // record exceptional return variable as output + codet output(ID_output); + output.operands().resize(2); + + assert(symbol_table.has_symbol(id2string(function.name)+EXC_SUFFIX)); + + // retrieve the exception variable + const symbolt exc_symbol=symbol_table.lookup( + id2string(function.name)+EXC_SUFFIX); + + output.op0()=address_of_exprt( + index_exprt(string_constantt(exc_symbol.base_name), + from_integer(0, index_type()))); + output.op1()=exc_symbol.symbol_expr(); + output.add_source_location()=function.location; + + init_code.move_to_operands(output); } main_function_resultt get_main_symbol( @@ -591,6 +610,15 @@ bool java_entry_point( call_main.lhs()=return_symbol.symbol_expr(); } + // add the exceptional return value + auxiliary_symbolt exc_symbol; + exc_symbol.mode=ID_C; + exc_symbol.is_static_lifetime=false; + exc_symbol.name=id2string(symbol.name)+EXC_SUFFIX; + exc_symbol.base_name=id2string(symbol.name)+EXC_SUFFIX; + exc_symbol.type=typet(ID_pointer, empty_typet()); + symbol_table.add(exc_symbol); + exprt::operandst main_arguments= java_build_arguments( symbol, From 835277b01afe7c2ac35bab2ae6aed3977584afb6 Mon Sep 17 00:00:00 2001 From: thk123 Date: Wed, 15 Mar 2017 16:27:25 +0000 Subject: [PATCH 54/67] Fixed crash on non-ascii diff Sometimes the diff file would contain a unicode character. Since we were opening the file, this meant that unidiff was reading the file in the wrong format. By letting unidiff handle reading the file we slightly simplify the code and fix this problem. --- scripts/filter_lint_by_diff.py | 27 +++++++++++++-------------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/scripts/filter_lint_by_diff.py b/scripts/filter_lint_by_diff.py index 534c642a6ba..7a4c506e27e 100755 --- a/scripts/filter_lint_by_diff.py +++ b/scripts/filter_lint_by_diff.py @@ -11,20 +11,19 @@ added_lines = set() repository_root = sys.argv[2] -with open(sys.argv[1], "r") as f: - diff = unidiff.PatchSet(f) - for diff_file in diff: - filename = diff_file.target_file - # Skip files deleted in the tip (b side of the diff): - if filename == "/dev/null": - continue - assert filename.startswith("b/") - filename = os.path.join(repository_root, filename[2:]) - added_lines.add((filename, 0)) - for diff_hunk in diff_file: - for diff_line in diff_hunk: - if diff_line.line_type == "+": - added_lines.add((filename, diff_line.target_line_no)) +diff = unidiff.PatchSet.from_filename(sys.argv[1]) +for diff_file in diff: + filename = diff_file.target_file + # Skip files deleted in the tip (b side of the diff): + if filename == "/dev/null": + continue + assert filename.startswith("b/") + filename = os.path.join(repository_root, filename[2:]) + added_lines.add((filename, 0)) + for diff_hunk in diff_file: + for diff_line in diff_hunk: + if diff_line.line_type == "+": + added_lines.add((filename, diff_line.target_line_no)) for l in sys.stdin: bits = l.split(":") From 60d07823632a6a9eb98fb88fd5da9eef8f87d062 Mon Sep 17 00:00:00 2001 From: thk123 Date: Thu, 16 Mar 2017 17:21:18 +0000 Subject: [PATCH 55/67] Missing forward declaration This caused this to not compile if included before whatever brings in goto_modelt. --- src/goto-programs/show_symbol_table.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/goto-programs/show_symbol_table.h b/src/goto-programs/show_symbol_table.h index a7cc99ec9ba..6e3b387f863 100644 --- a/src/goto-programs/show_symbol_table.h +++ b/src/goto-programs/show_symbol_table.h @@ -11,6 +11,8 @@ Author: Daniel Kroening, kroening@kroening.com #include +class goto_modelt; + void show_symbol_table( const goto_modelt &, ui_message_handlert::uit ui); From e0905ae3f096e9e95404f4d73d73506d0a378597 Mon Sep 17 00:00:00 2001 From: Daniel Poetzl Date: Fri, 9 Dec 2016 18:05:42 +0000 Subject: [PATCH 56/67] map with sharing --- src/util/sharing_map.h | 832 ++++++++++++++++++++++++++++++++++++++++ src/util/sharing_node.h | 346 +++++++++++++++++ unit/Makefile | 10 +- unit/sharing_map.cpp | 336 ++++++++++++++++ unit/sharing_node.cpp | 129 +++++++ 5 files changed, 1652 insertions(+), 1 deletion(-) create mode 100644 src/util/sharing_map.h create mode 100644 src/util/sharing_node.h create mode 100644 unit/sharing_map.cpp create mode 100644 unit/sharing_node.cpp diff --git a/src/util/sharing_map.h b/src/util/sharing_map.h new file mode 100644 index 00000000000..23f08d0bb06 --- /dev/null +++ b/src/util/sharing_map.h @@ -0,0 +1,832 @@ +/*******************************************************************\ + +Module: Sharing map + +Author: Daniel Poetzl + +\*******************************************************************/ + +#ifndef CPROVER_UTIL_SHARING_MAP_H +#define CPROVER_UTIL_SHARING_MAP_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#define _sm_assert(b) assert(b) +//#define _sm_assert(b) + +#define SHARING_MAPT(R) \ + template \ + R sharing_mapt + +#define SHARING_MAPT2(CV, ST) \ + template \ + CV typename sharing_mapt::ST \ + sharing_mapt + +template < + class keyT, + class valueT, + class hashT=std::hash, + class predT=std::equal_to> +class sharing_mapt +{ +public: + friend void sharing_map_interface_test(); + friend void sharing_map_copy_test(); + friend void sharing_map_collision_test(); + friend void sharing_map_view_test(); + + ~sharing_mapt() + { + } + + typedef keyT key_type; + typedef valueT mapped_type; + typedef std::pair value_type; + + typedef hashT hash; + typedef predT key_equal; + + typedef sharing_mapt self_type; + typedef sharing_nodet node_type; + + typedef size_t size_type; + + typedef const std::pair const_find_type; + typedef const std::pair find_type; + + typedef std::vector keyst; + + typedef typename node_type::subt subt; + typedef typename node_type::containert containert; + + // key-value map + node_type map; + + // number of elements in the map + size_type num=0; + + // dummy element returned when no element was found + static mapped_type dummy; + + // compile-time configuration + + static const std::string not_found_msg; + + static const size_t bits; + static const size_t chunk; + + static const size_t mask; + static const size_t steps; + + // interface + + size_type erase( + const key_type &k, + const tvt &key_exists=tvt::unknown()); + + size_type erase_all( + const keyst &ks, + const tvt &key_exists=tvt::unknown()); // applies to all keys + + // return true if element was inserted + const_find_type insert( + const key_type &k, + const mapped_type &v, + const tvt &key_exists=tvt::unknown()); + + const_find_type insert( + const value_type &p, + const tvt &key_exists=tvt::unknown()); + + find_type place( + const key_type &k, + const mapped_type &v); + + find_type place( + const value_type &p); + + find_type find( + const key_type &k, + const tvt &key_exists=tvt::unknown()); + + const_find_type find(const key_type &k) const; + + mapped_type &at( + const key_type &k, + const tvt &key_exists=tvt::unknown()); + + const mapped_type &at(const key_type &k) const; + + mapped_type &operator[](const key_type &k); + + void swap(self_type &other) + { + map.swap(other.map); + + size_t tmp=num; + num=other.num; + other.num=tmp; + } + + size_type size() const + { + return num; + } + + bool empty() const + { + return num==0; + } + + void clear() + { + map.clear(); + num=0; + } + + bool has_key(const key_type &k) const + { + return get_leaf_node(k)!=nullptr; + } + + // views + + typedef std::pair view_itemt; + typedef std::vector viewt; + + class delta_view_itemt + { + public: + delta_view_itemt( + const bool in_both, + const key_type &k, + const mapped_type &m, + const mapped_type &other_m) : + in_both(in_both), + k(k), + m(m), + other_m(other_m) {} + + // if true key is in both maps, if false key is only in the map + // from which the view was obtained + const bool in_both; + + const key_type &k; + + const mapped_type &m; + const mapped_type &other_m; + }; + + typedef std::vector delta_viewt; + + void get_view(viewt &view) const; + + void get_delta_view( + const self_type &other, + delta_viewt &delta_view, + const bool only_common=true) const; + +protected: + // helpers + + node_type *get_container_node(const key_type &k); + const node_type *get_container_node(const key_type &k) const; + + const node_type *get_leaf_node(const key_type &k) const; + + void gather_all(const node_type &n, delta_viewt &delta_view) const; +}; + +/*******************************************************************\ + +Function: get_view + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT(void)::get_view(viewt &view) const +{ + assert(view.empty()); + + std::stack stack; + + if(empty()) + return; + + stack.push(&map); + + do + { + const node_type *n=stack.top(); + stack.pop(); + + if(n->is_container()) + { + for(const auto &child : n->get_container()) + { + view.push_back(view_itemt(child.get_key(), child.get_value())); + } + } + else + { + assert(n->is_internal()); + + for(const auto &child : n->get_sub()) + { + stack.push(&child.second); + } + } + } + while(!stack.empty()); +} + +/*******************************************************************\ + +Function: gather_all + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT(void)::gather_all(const node_type &n, delta_viewt &delta_view) + const +{ + std::stack stack; + stack.push(&n); + + do + { + const node_type *n=stack.top(); + stack.pop(); + + if(n->is_container()) + { + for(const auto &child : n->get_container()) + { + delta_view.push_back( + delta_view_itemt( + false, + child.get_key(), + child.get_value(), + dummy)); + } + } + else + { + assert(n->is_internal()); + + for(const auto &child : n->get_sub()) + { + stack.push(&child.second); + } + } + } + while(!stack.empty()); +} + +/*******************************************************************\ + +Function: get_delta_view + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT(void)::get_delta_view( + const self_type &other, + delta_viewt &delta_view, + const bool only_common) const +{ + assert(delta_view.empty()); + + typedef std::pair stack_itemt; + std::stack stack; + + if(empty()) + return; + + if(other.empty()) + { + if(!only_common) + { + gather_all(map, delta_view); + } + return; + } + + stack.push(stack_itemt(&map, &other.map)); + + do + { + const stack_itemt si=stack.top(); + stack.pop(); + + const node_type *n1=si.first; + const node_type *n2=si.second; + + if(n1->is_internal()) + { + _sn_assert(n2->is_internal()); + + for(const auto &child : n1->get_sub()) + { + const node_type *p; + + p=n2->find_child(child.first); + if(p==nullptr) + { + if(!only_common) + { + gather_all(child.second, delta_view); + } + } + else if(!child.second.shares_with(*p)) + { + stack.push(stack_itemt(&child.second, p)); + } + } + } + else if(n1->is_container()) + { + _sn_assert(n2->is_container()); + + for(const auto &l1 : n1->get_container()) + { + const key_type &k1=l1.get_key(); + bool found=false; + + for(const auto &l2 : n2->get_container()) + { + const key_type &k2=l2.get_key(); + + if(l1.shares_with(l2)) + { + found=true; + break; + } + + if(key_equal()(k1, k2)) + { + delta_view.push_back( + delta_view_itemt( + true, + k1, + l1.get_value(), + l2.get_value())); + + found=true; + break; + } + } + + if(!only_common && !found) + { + delta_view.push_back( + delta_view_itemt( + false, + l1.get_key(), + l1.get_value(), + dummy)); + } + } + } + else + { + assert(false); + } + } + while(!stack.empty()); +} + +/*******************************************************************\ + +Function: get_container_node + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, node_type *)::get_container_node(const key_type &k) +{ + size_t key=hash()(k); + node_type *p=↦ + + for(unsigned i=0; i>=chunk; + + p=p->add_child(bit); + } + + return p; +} + +/*******************************************************************\ + +Function: get_container_node + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(const, node_type *)::get_container_node(const key_type &k) const +{ + size_t key=hash()(k); + const node_type *p=↦ + + for(unsigned i=0; i>=chunk; + + p=p->find_child(bit); + if(p==nullptr) + return nullptr; + } + + assert(p->is_container()); + + return p; +} + +/*******************************************************************\ + +Function: get_leaf_node + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(const, node_type *)::get_leaf_node(const key_type &k) const +{ + const node_type *p=get_container_node(k); + if(p==nullptr) + return nullptr; + + p=p->find_leaf(k); + + return p; +} + +/*******************************************************************\ + +Function: erase + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, size_type)::erase( + const key_type &k, + const tvt &key_exists) +{ + assert(!key_exists.is_false()); + + // check if key exists + if(key_exists.is_unknown() && !has_key(k)) + return 0; + + node_type *del=nullptr; + unsigned del_bit; + + size_t key=hash()(k); + node_type *p=↦ + + for(unsigned i=0; i>=chunk; + + const subt &sub=as_const(p)->get_sub(); + if(sub.size()>1 || del==nullptr) + { + del=p; + del_bit=bit; + } + + p=p->add_child(bit); + } + + _sm_assert(p->is_container()); + + { + const containert &c=as_const(p)->get_container(); + + if(c.size()==1) + { + del->remove_child(del_bit); + num--; + return 1; + } + } + + containert &c=p->get_container(); + _sm_assert(c.size()>1); + p->remove_leaf(k); + num--; + + return 1; +} + +/*******************************************************************\ + +Function: erase_all + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, size_type)::erase_all( + const keyst &ks, + const tvt &key_exists) +{ + size_type cnt=0; + + for(const key_type &k : ks) + { + cnt+=erase(k, key_exists); + } + + return cnt; +} + +/*******************************************************************\ + +Function: insert + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, const_find_type)::insert( + const key_type &k, + const mapped_type &m, + const tvt &key_exists) +{ + _sn_assert(!key_exists.is_true()); + + if(key_exists.is_unknown()) + { + const node_type *p=as_const(this)->get_leaf_node(k); + if(p!=nullptr) + return const_find_type(p->get_value(), false); + } + + node_type *p=get_container_node(k); + _sn_assert(p!=nullptr); + + p=p->place_leaf(k, m); + num++; + + return const_find_type(as_const(p)->get_value(), true); +} + +/*******************************************************************\ + +Function: insert + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, const_find_type)::insert( + const value_type &p, + const tvt &key_exists) +{ + return insert(p.first, p.second, key_exists); +} + +/*******************************************************************\ + +Function: place + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, find_type)::place( + const key_type &k, + const mapped_type &m) +{ + node_type *c=get_container_node(k); + _sm_assert(c!=nullptr); + + node_type *p=c->find_leaf(k); + + if(p!=nullptr) + return find_type(p->get_value(), false); + + p=c->place_leaf(k, m); + num++; + + return find_type(p->get_value(), true); +} + +/*******************************************************************\ + +Function: place + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, find_type)::place( + const value_type &p) +{ + return place(p.first, p.second); +} + +/*******************************************************************\ + +Function: find + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, find_type)::find( + const key_type &k, + const tvt &key_exists) +{ + _sm_assert(!key_exists.is_false()); + + if(key_exists.is_unknown() && !has_key(k)) + return find_type(dummy, false); + + node_type *p=get_container_node(k); + _sm_assert(p!=nullptr); + + p=p->find_leaf(k); + _sm_assert(p!=nullptr); + + return find_type(p->get_value(), true); + +} + +/*******************************************************************\ + +Function: find + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, const_find_type)::find(const key_type &k) const +{ + const node_type *p=get_leaf_node(k); + + if(p==nullptr) + return const_find_type(dummy, false); + + return const_find_type(p->get_value(), true); +} + +/*******************************************************************\ + +Function: at + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, mapped_type &)::at( + const key_type &k, + const tvt &key_exists) +{ + find_type r=find(k, key_exists); + + if(!r.second) + throw std::out_of_range(not_found_msg); + + return r.first; +} + +/*******************************************************************\ + +Function: at + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(const, mapped_type &)::at(const key_type &k) const +{ + const_find_type r=find(k); + if(!r.second) + throw std::out_of_range(not_found_msg); + + return r.first; +} + +/*******************************************************************\ + +Function: operator[] + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +SHARING_MAPT2(, mapped_type &)::operator[](const key_type &k) +{ + return place(k, mapped_type()).first; +} + +// static constants + +SHARING_MAPT(const std::string)::not_found_msg="key not found"; + +// config +SHARING_MAPT(const size_t)::bits=18; +SHARING_MAPT(const size_t)::chunk=3; + +// derived config +SHARING_MAPT(const size_t)::mask=0xffff>>(16-chunk); +SHARING_MAPT(const size_t)::steps=bits/chunk; + +SHARING_MAPT2(, mapped_type)::dummy; + +#endif diff --git a/src/util/sharing_node.h b/src/util/sharing_node.h new file mode 100644 index 00000000000..1e3d29a413e --- /dev/null +++ b/src/util/sharing_node.h @@ -0,0 +1,346 @@ +/*******************************************************************\ + +Module: Sharing node + +Author: Daniel Poetzl + +\*******************************************************************/ + +#ifndef CPROVER_UTIL_SHARING_NODE_H +#define CPROVER_UTIL_SHARING_NODE_H + +#include +#include +#include +#include + +#define _sn_assert(b) assert(b) +//#define _sn_assert(b) + +template +const T *as_const(T *t) +{ + return t; +} + +template < + class keyT, + class valueT, + class predT=std::equal_to, + bool no_sharing=false> +class sharing_nodet +{ +public: + friend void sharing_node_test(); + + typedef keyT key_type; + typedef valueT mapped_type; + + typedef predT key_equal; + + typedef sharing_nodet self_type; + + typedef std::map subt; + typedef std::list containert; + + typedef const std::pair const_find_type; + typedef const std::pair find_type; + + sharing_nodet() : data(empty_data) + { + _sn_assert(data.use_count()>=2); + } + + sharing_nodet(const key_type &k, const mapped_type &m) : data(empty_data) + { + _sn_assert(data.use_count()>=2); + + dt &d=write(); + + _sn_assert(d.k==nullptr); + d.k=std::make_shared(k); + + _sn_assert(d.m==nullptr); + d.m.reset(new mapped_type(m)); + } + + sharing_nodet(const self_type &other) + { +#ifdef SM_NO_SHARING + data=std::make_shared
(*other.data); +#else + if(no_sharing) + { + data=std::make_shared
(*other.data); + } + else + { + data=other.data; + } +#endif + } + + // check type of node + + bool is_empty() const + { + _sn_assert(is_well_formed()); + return data==empty_data; + } + + bool is_internal() const + { + _sn_assert(is_well_formed()); + _sn_assert(!is_empty()); + return !get_sub().empty(); + } + + bool is_container() const + { + _sn_assert(is_well_formed()); + _sn_assert(!is_empty()); + return !get_container().empty(); + } + + bool is_leaf() const + { + _sn_assert(is_well_formed()); + _sn_assert(!is_empty()); + return read().is_leaf(); + } + + // accessors + + const key_type &get_key() const + { + _sn_assert(is_leaf()); + return *read().k; + } + + const mapped_type &get_value() const + { + _sn_assert(is_leaf()); + return *read().m; + } + + mapped_type &get_value() + { + _sn_assert(is_leaf()); + return *write().m; + } + + subt &get_sub() + { + return write().sub; + } + + const subt &get_sub() const + { + return read().sub; + } + + containert &get_container() + { + return write().con; + } + + const containert &get_container() const + { + return read().con; + } + + // internal nodes + + const self_type *find_child(const unsigned n) const + { + const subt &s=get_sub(); + typename subt::const_iterator it=s.find(n); + + if(it!=s.end()) + return &it->second; + + return nullptr; + } + + self_type *add_child(const unsigned n) + { + subt &s=get_sub(); + return &s[n]; + } + + void remove_child(const unsigned n) + { + subt &s=get_sub(); + size_t r=s.erase(n); + + _sn_assert(r==1); + } + + // container nodes + + const self_type *find_leaf(const key_type &k) const + { + const containert &c=get_container(); + + for(const auto &n : c) + { + if(key_equal()(n.get_key(), k)) + return &n; + } + + return nullptr; + } + + self_type *find_leaf(const key_type &k) + { + containert &c=get_container(); + + for(auto &n : c) + { + if(key_equal()(n.get_key(), k)) + return &n; + } + + return nullptr; + } + + // add leaf, key must not exist yet + self_type *place_leaf(const key_type &k, const mapped_type &m) + { + _sn_assert(as_const(this)->find_leaf(k)==nullptr); + + containert &c=get_container(); + c.push_back(self_type(k, m)); + + return &c.back(); + } + + // remove leaf, key must exist + void remove_leaf(const key_type &k) + { + containert &c=get_container(); + + for(typename containert::const_iterator it=c.begin(); + it!=c.end(); it++) + { + const self_type &n=*it; + + if(key_equal()(n.get_key(), k)) + { + c.erase(it); + return; + } + } + + assert(false); + } + + // misc + + void clear() + { + *this=self_type(); + } + + bool shares_with(const self_type &other) const + { + return data==other.data; + } + + void swap(self_type &other) + { + data.swap(other.data); + } + +protected: + class dt + { + public: + dt() {} + + dt(const dt &d) : k(d.k), sub(d.sub), con(d.con) + { + if(d.is_leaf()) + { + _sn_assert(m==nullptr); + m.reset(new mapped_type(*d.m)); + } + } + + bool is_leaf() const + { + _sn_assert(k==nullptr || m!=nullptr); + return k!=nullptr; + } + + std::shared_ptr k; + std::unique_ptr m; + + subt sub; + containert con; + }; + + const dt &read() const + { + return *data; + } + + dt &write() + { + detach(); + return *data; + } + + void detach() + { + _sn_assert(data.use_count()>0); + + if(data==empty_data) + data=std::make_shared
(); + else if(data.use_count()>1) + data=std::make_shared
(*data); + + _sn_assert(data.use_count()==1); + } + + bool is_well_formed() const + { + if(data==nullptr) + return false; + + const dt &d=*data; + + bool b; + + // empty node + b=data==empty_data; + // internal node + b|=d.k==nullptr && d.m==nullptr && get_container().empty() && + !get_sub().empty(); + // container node + b|=d.k==nullptr && d.m==nullptr && !get_container().empty() && + get_sub().empty(); + // leaf node + b|=d.k!=nullptr && d.m!=nullptr && get_container().empty() && + get_sub().empty(); + + return b; + } + + std::shared_ptr
data; + static std::shared_ptr
empty_data; + + // dummy node returned when node was not found + static sharing_nodet dummy; +}; + +template +std::shared_ptr::dt> + sharing_nodet::empty_data( + new sharing_nodet::dt()); + +template +sharing_nodet + sharing_nodet::dummy; + +#endif diff --git a/unit/Makefile b/unit/Makefile index 0b442445a0f..007ebd3c70d 100644 --- a/unit/Makefile +++ b/unit/Makefile @@ -1,6 +1,8 @@ SRC = cpp_parser.cpp cpp_scanner.cpp elf_reader.cpp float_utils.cpp \ ieee_float.cpp json.cpp miniBDD.cpp osx_fat_reader.cpp \ - smt2_parser.cpp wp.cpp string_utils.cpp + smt2_parser.cpp wp.cpp string_utils.cpp \ + sharing_map.cpp \ + sharing_node.cpp INCLUDES= -I ../src/ @@ -59,3 +61,9 @@ wp$(EXEEXT): wp$(OBJEXT) string_utils$(EXEEXT): string_utils$(OBJEXT) $(LINKBIN) +sharing_map$(EXEEXT): sharing_map$(OBJEXT) + $(LINKBIN) + +sharing_node$(EXEEXT): sharing_node$(OBJEXT) + $(LINKBIN) + diff --git a/unit/sharing_map.cpp b/unit/sharing_map.cpp new file mode 100644 index 00000000000..9911f460855 --- /dev/null +++ b/unit/sharing_map.cpp @@ -0,0 +1,336 @@ +#include +#include + +#include + +typedef sharing_mapt smt; + +// helpers +void fill(smt &sm) +{ + sm.insert("i", "0"); + sm.insert("j", "1"); + sm.insert("k", "2"); +} + +void fill2(smt &sm) +{ + sm.insert("l", "3"); + sm.insert("m", "4"); + sm.insert("n", "5"); +} + +// tests + +void sharing_map_interface_test() +{ + std::cout << "Running interface test" << std::endl; + + // empty map + { + smt sm; + + assert(sm.empty()); + assert(sm.size()==0); + assert(!sm.has_key("i")); + } + + // insert elements + { + smt sm; + + smt::const_find_type r1=sm.insert(std::make_pair("i", "0")); + assert(r1.second); + + smt::const_find_type r2=sm.insert("j", "1"); + assert(r2.second); + + smt::const_find_type r3=sm.insert(std::make_pair("i", "0")); + assert(!r3.second); + + assert(sm.size()==2); + assert(!sm.empty()); + } + + // place elements + { + smt sm1; + smt sm2(sm1); + + smt::find_type r1=sm1.place("i", "0"); + assert(r1.second); + assert(!sm2.has_key("i")); + + std::string &s1=r1.first; + s1="1"; + + assert(sm1.at("i")=="1"); + } + + // retrieve elements + { + smt sm; + sm.insert("i", "0"); + sm.insert("j", "1"); + + const smt &sm2=sm; + + std::string s; + s=sm2.at("i"); + assert(s=="0"); + + try { + sm2.at("k"); + assert(false); + } catch (...) {} + + s=sm2.at("j"); + assert(s=="1"); + + assert(sm.has_key("i")); + assert(sm.has_key("j")); + assert(!sm.has_key("k")); + + std::string &s2=sm.at("i"); + s2="3"; + assert(sm2.at("i")=="3"); + + assert(sm.size()==2); + + smt::find_type r=sm.find("i"); + assert(r.second); + r.first="4"; + assert(sm2.at("i")=="4"); + + smt::const_find_type rc=sm2.find("k"); + assert(!rc.second); + } + + // remove elements + { + smt sm; + sm.insert("i", "0"); + sm.insert("j", "1"); + + assert(sm.erase("k")==0); + assert(sm.size()==2); + + assert(sm.erase("i")==1); + assert(!sm.has_key("i")); + + assert(sm.erase("j")==1); + assert(!sm.has_key("j")); + + sm.insert("i", "0"); + sm.insert("j", "1"); + + smt sm3(sm); + + assert(sm.has_key("i")); + assert(sm.has_key("j")); + assert(sm3.has_key("i")); + assert(sm3.has_key("j")); + + sm.erase("i"); + + assert(!sm.has_key("i")); + assert(sm.has_key("j")); + + assert(sm3.has_key("i")); + assert(sm3.has_key("j")); + + sm3.erase("i"); + assert(!sm3.has_key("i")); + } + + // operator[] + { + smt sm; + + sm["i"]; + assert(sm.has_key("i")); + + sm["i"]="0"; + assert(sm.at("i")=="0"); + + sm["j"]="1"; + assert(sm.at("j")=="1"); + } +} + +void sharing_map_copy_test() +{ + std::cout << "Running copy test" << std::endl; + + smt sm1; + const smt &sm2=sm1; + + fill(sm1); + + assert(sm2.find("i").first=="0"); + assert(sm2.find("j").first=="1"); + assert(sm2.find("k").first=="2"); + + smt sm3=sm1; + const smt &sm4=sm3; + + assert(sm3.erase("l")==0); + assert(sm3.erase("i")==1); + + assert(!sm4.has_key("i")); + sm3.place("i", "3"); + assert(sm4.find("i").first=="3"); +} + +class some_keyt +{ +public: + some_keyt(size_t s) : s(s) + { + } + + size_t s; + + bool operator==(const some_keyt &other) const + { + return s==other.s; + } +}; + +class some_key_hash +{ +public: + size_t operator()(const some_keyt &k) const + { + return k.s & 0x3; + } +}; + +void sharing_map_collision_test() +{ + std::cout << "Running collision test" << std::endl; + + typedef sharing_mapt smt; + + smt sm; + + sm.insert(0, "a"); + sm.insert(8, "b"); + sm.insert(16, "c"); + + sm.insert(1, "d"); + sm.insert(2, "e"); + + sm.erase(8); + + assert(sm.has_key(0)); + assert(sm.has_key(16)); + + assert(sm.has_key(1)); + assert(sm.has_key(2)); + + assert(!sm.has_key(8)); +} + +void sharing_map_view_test() +{ + std::cout << "Running view test" << std::endl; + + // view test + { + smt sm; + + fill(sm); + + smt::viewt view; + sm.get_view(view); + + assert(view.size()==3); + } + + // delta view test (no sharing, same keys) + { + smt sm1; + fill(sm1); + + smt sm2; + fill(sm2); + + smt::delta_viewt delta_view; + + sm1.get_delta_view(sm2, delta_view); + assert(delta_view.size()==3); + + delta_view.clear(); + sm1.get_delta_view(sm2, delta_view, false); + assert(delta_view.size()==3); + } + + // delta view test (all shared, same keys) + { + smt sm1; + fill(sm1); + + smt sm2(sm1); + + smt::delta_viewt delta_view; + + sm1.get_delta_view(sm2, delta_view); + assert(delta_view.size()==0); + + delta_view.clear(); + sm1.get_delta_view(sm2, delta_view, false); + assert(delta_view.size()==0); + } + + // delta view test (some sharing, same keys) + { + smt sm1; + fill(sm1); + + smt sm2(sm1); + auto r=sm2.find("i"); + assert(r.second); + r.first="3"; + + smt::delta_viewt delta_view; + + sm1.get_delta_view(sm2, delta_view); + assert(delta_view.size()>0); // not everything is shared + assert(delta_view.size()<3); // there is some sharing + + delta_view.clear(); + sm1.get_delta_view(sm2, delta_view, false); + assert(delta_view.size()>0); // not everything is shared + assert(delta_view.size()<3); // there is some sharing + } + + // delta view test (no sharing, different keys) + { + smt sm1; + fill(sm1); + + smt sm2; + fill2(sm2); + + smt::delta_viewt delta_view; + + sm1.get_delta_view(sm2, delta_view); + assert(delta_view.size()==0); + + delta_view.clear(); + sm1.get_delta_view(sm2, delta_view, false); + assert(delta_view.size()==3); + } +} + +int main() +{ + sharing_map_interface_test(); + sharing_map_copy_test(); + sharing_map_collision_test(); + sharing_map_view_test(); + + return 0; +} + diff --git a/unit/sharing_node.cpp b/unit/sharing_node.cpp new file mode 100644 index 00000000000..2d256b8dd45 --- /dev/null +++ b/unit/sharing_node.cpp @@ -0,0 +1,129 @@ +#include +#include + +#include + +void sharing_node_test() +{ + std::cout << "Running sharing node test" << std::endl; + + typedef sharing_nodet snt; + + // internal node test + { + snt sn1; + const snt &sn2=sn1; + + const snt *p2; + + assert(sn1.is_empty()); + + sn1.add_child(0); + sn1.add_child(1); + sn1.add_child(2); + + assert(!sn2.is_empty()); + assert(sn2.is_internal()); + assert(!sn2.is_container()); + assert(!sn2.is_leaf()); + + assert(sn2.get_sub().size()==3); + + p2=sn2.find_child(0); + assert(p2!=nullptr); + + p2=sn1.find_child(0); + assert(p2!=nullptr); + + p2=sn2.find_child(3); + assert(p2==nullptr); + + p2=sn1.find_child(3); + assert(p2==nullptr); + + sn1.remove_child(0); + assert(sn2.get_sub().size()==2); + + sn1.clear(); + assert(sn2.is_empty()); + } + + // container node test + { + snt sn1; + + snt *p1; + const snt *p2; + + sn1.add_child(0); + sn1.add_child(1); + + p1=sn1.add_child(2); + p2=p1; + + assert(p1->find_leaf("a")==nullptr); + assert(p2->find_leaf("a")==nullptr); + + p1->place_leaf("a", "b"); + assert(p2->get_container().size()==1); + p1->place_leaf("c", "d"); + assert(p2->get_container().size()==2); + + assert(p2->is_container()); + + p1->remove_leaf("a"); + assert(p2->get_container().size()==1); + } + + // copy test 1 + { + snt sn1; + snt sn2; + + sn2=sn1; + assert(sn1.data.use_count()==3); + assert(sn2.data.use_count()==3); + + sn1.add_child(0); + assert(sn1.data.use_count()==1); + // the newly created node is empty as well + assert(sn2.data.use_count()==3); + + sn2=sn1; + assert(sn2.data.use_count()==2); + } + + // copy test 2 + { + snt sn1; + const snt &sn1c=sn1; + snt *p; + + p=sn1.add_child(0); + p->place_leaf("x", "y"); + + p=sn1.add_child(1); + p->place_leaf("a", "b"); + p->place_leaf("c", "d"); + + snt sn2; + const snt &sn2c=sn2; + sn2=sn1; + + assert(sn1.is_internal()); + assert(sn2.is_internal()); + + sn1.remove_child(0); + assert(sn1c.get_sub().size()==1); + + assert(sn2c.get_sub().size()==2); + } +} + +int main() +{ + sharing_node_test(); + + return 0; +} + From 1ca2b70d362e338a522be27e61c0c30b9a800253 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sat, 18 Mar 2017 21:13:08 +0000 Subject: [PATCH 57/67] make tests pass on 32-bit systems --- regression/cbmc/Malloc23/test.desc | 4 ++-- regression/cbmc/byte_update2/main.c | 2 +- regression/cbmc/byte_update3/main.c | 2 +- regression/cbmc/byte_update4/main.c | 2 +- regression/cbmc/byte_update5/main.c | 2 +- regression/cbmc/byte_update6/main.c | 2 +- regression/cbmc/byte_update7/main.c | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/regression/cbmc/Malloc23/test.desc b/regression/cbmc/Malloc23/test.desc index 9e34fa7f422..4bd6cbdc141 100644 --- a/regression/cbmc/Malloc23/test.desc +++ b/regression/cbmc/Malloc23/test.desc @@ -5,8 +5,8 @@ main.c ^SIGNAL=0$ pointer outside dynamic object bounds in \*p: FAILURE pointer outside dynamic object bounds in \*p: FAILURE -pointer outside dynamic object bounds in p2\[\(signed long int\)1\]: FAILURE -pointer outside dynamic object bounds in p2\[\(signed long int\)0\]: FAILURE +pointer outside dynamic object bounds in p2\[.*1\]: FAILURE +pointer outside dynamic object bounds in p2\[.*0\]: FAILURE \*\* 4 of 36 failed \(3 iterations\) -- ^warning: ignoring diff --git a/regression/cbmc/byte_update2/main.c b/regression/cbmc/byte_update2/main.c index 12493e4267c..cee6e19ecc4 100644 --- a/regression/cbmc/byte_update2/main.c +++ b/regression/cbmc/byte_update2/main.c @@ -6,7 +6,7 @@ int main(int argc, char** argv) { if(argc != 2) return 0; - unsigned long x[argc]; + unsigned long long x[argc]; x[0]=0x0102030405060708; x[1]=0x1112131415161718; diff --git a/regression/cbmc/byte_update3/main.c b/regression/cbmc/byte_update3/main.c index 6d9b3c293c0..e20eb6588c3 100644 --- a/regression/cbmc/byte_update3/main.c +++ b/regression/cbmc/byte_update3/main.c @@ -13,7 +13,7 @@ int main(int argc, char** argv) { x[3]=0x0708; x[4]=0x090a; - unsigned long* alias=(unsigned long*)(((char*)x)+0); + unsigned long long* alias=(unsigned long long*)(((char*)x)+0); *alias=0xf1f2f3f4f5f6f7f8; unsigned char* alias2=(unsigned char*)x; diff --git a/regression/cbmc/byte_update4/main.c b/regression/cbmc/byte_update4/main.c index 0285f3058fe..2866b20a0ff 100644 --- a/regression/cbmc/byte_update4/main.c +++ b/regression/cbmc/byte_update4/main.c @@ -18,7 +18,7 @@ int main(int argc, char** argv) { x[8]=0x09; x[9]=0x0a; - unsigned long* alias=(unsigned long*)(((char*)x)+1); + unsigned long long* alias=(unsigned long long*)(((char*)x)+1); *alias=0xf1f2f3f4f5f6f7f8; unsigned char* alias2=(unsigned char*)x; diff --git a/regression/cbmc/byte_update5/main.c b/regression/cbmc/byte_update5/main.c index e2f9da4defc..fc698a20143 100644 --- a/regression/cbmc/byte_update5/main.c +++ b/regression/cbmc/byte_update5/main.c @@ -13,7 +13,7 @@ int main(int argc, char** argv) { x[3]=0x0708; x[4]=0x090a; - unsigned long* alias=(unsigned long*)(((char*)x)+1); + unsigned long long* alias=(unsigned long long*)(((char*)x)+1); *alias=0xf1f2f3f4f5f6f7f8; unsigned char* alias2=(unsigned char*)x; diff --git a/regression/cbmc/byte_update6/main.c b/regression/cbmc/byte_update6/main.c index cb92364572d..d0e3680b83a 100644 --- a/regression/cbmc/byte_update6/main.c +++ b/regression/cbmc/byte_update6/main.c @@ -6,7 +6,7 @@ int main(int argc, char** argv) { if(argc != 2) return 0; - unsigned long x[argc]; + unsigned long long x[argc]; x[0]=0x0102030405060708; x[1]=0x1112131415161718; diff --git a/regression/cbmc/byte_update7/main.c b/regression/cbmc/byte_update7/main.c index 599df60afd7..35690acc90d 100644 --- a/regression/cbmc/byte_update7/main.c +++ b/regression/cbmc/byte_update7/main.c @@ -6,7 +6,7 @@ int main(int argc, char** argv) { if(argc != 2) return 0; - unsigned long x[argc]; + unsigned long long x[argc]; x[0]=0x0102030405060708; x[1]=0x1112131415161718; From 6bbe8313ca2694e904426563d855c7f3b92b1cce Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sat, 18 Mar 2017 21:20:45 +0000 Subject: [PATCH 58/67] make tests pass on 32-bit systems --- regression/cbmc-java/VarLengthArrayTrace1/test.desc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/regression/cbmc-java/VarLengthArrayTrace1/test.desc b/regression/cbmc-java/VarLengthArrayTrace1/test.desc index 14ee7eb85a8..77b1aeea6d8 100644 --- a/regression/cbmc-java/VarLengthArrayTrace1/test.desc +++ b/regression/cbmc-java/VarLengthArrayTrace1/test.desc @@ -3,7 +3,7 @@ VarLengthArrayTrace1.class --trace ^EXIT=10$ ^SIGNAL=0$ -dynamic_3_array\[1l\]=10 +dynamic_3_array\[1.*\]=10 -- ^warning: ignoring assignment removed From f0824193a80f0467bf492604684bf8fb457a7dd9 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sat, 18 Mar 2017 22:13:05 +0000 Subject: [PATCH 59/67] compilation instructions --- COMPILING | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/COMPILING b/COMPILING index 60579fe9f3b..70d94dc8b4c 100644 --- a/COMPILING +++ b/COMPILING @@ -10,10 +10,10 @@ environments: - Solaris 11 -- FreeBSD 10 or 11 +- FreeBSD 11 - Cygwin - (We recommend the i686-pc-mingw32-g++ cross compiler, version 4.7 or above.) + (We recommend the i686-pc-mingw32-g++ cross compiler, version 5.4 or above.) - Microsoft's Visual Studio version 12 (2013), version 14 (2015), or version 15 (older versions won't work) @@ -29,16 +29,16 @@ COMPILATION ON LINUX We assume that you have a Debian/Ubuntu or Red Hat-like distribution. 0) You need a C/C++ compiler, Flex and Bison, and GNU make. - The GNU Make needs to be version 3.81 or higher. On Debian-like - distributions, do + The GNU Make needs to be version 3.81 or higher. + On Debian-like distributions, do - apt-get install g++ gcc flex bison make git libz-dev libwww-perl patch libzip-dev + apt-get install g++-6 gcc flex bison make git libz-dev libwww-perl patch libzip-dev On Red Hat/Fedora or derivates, do yum install gcc gcc-c++ flex bison perl-libwww-perl patch - Note that you need g++ version 4.9 or newer. + Note that you need g++ version 5.2 or newer. 1) As a user, get the CBMC source via @@ -57,7 +57,7 @@ COMPILATION ON SOLARIS 11 1) As root, get the necessary development tools: pkg install system/header developer/lexer/flex developer/parser/bison developer/versioning/git - pkg install --accept developer/gcc-49 + pkg install --accept developer/gcc-5 2) As a user, get the CBMC source via @@ -83,8 +83,8 @@ COMPILATION ON SOLARIS 11 It will mis-optimize MiniSat2. -COMPILATION ON FREEBSD 10/11 ----------------------------- +COMPILATION ON FREEBSD 11 +------------------------- 1) As root, get the necessary tools: From 4b1b62729a844cfddfd7e3c3b1bb2c080cb2e742 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sun, 19 Mar 2017 10:16:31 +0000 Subject: [PATCH 60/67] we don't use libzip any more --- COMPILING | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/COMPILING b/COMPILING index 70d94dc8b4c..93fc65c2938 100644 --- a/COMPILING +++ b/COMPILING @@ -32,7 +32,7 @@ We assume that you have a Debian/Ubuntu or Red Hat-like distribution. The GNU Make needs to be version 3.81 or higher. On Debian-like distributions, do - apt-get install g++-6 gcc flex bison make git libz-dev libwww-perl patch libzip-dev + apt-get install g++-6 gcc flex bison make git libwww-perl patch On Red Hat/Fedora or derivates, do From f9689685ca2e084c0dc49941a5d7f3f3a5108bc6 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sun, 19 Mar 2017 11:10:15 +0000 Subject: [PATCH 61/67] convenient zero factories for floating point and fixed point types --- src/util/fixedbv.h | 9 +++++++++ src/util/ieee_float.h | 7 +++++++ 2 files changed, 16 insertions(+) diff --git a/src/util/fixedbv.h b/src/util/fixedbv.h index 14e5946c445..8354e0bef7c 100644 --- a/src/util/fixedbv.h +++ b/src/util/fixedbv.h @@ -46,6 +46,10 @@ class fixedbvt { } + explicit fixedbvt(const fixedbv_spect &_spec):spec(_spec), v(0) + { + } + explicit fixedbvt(const constant_exprt &expr); void from_integer(const mp_integer &i); @@ -68,6 +72,11 @@ class fixedbvt return v==0; } + static fixedbvt zero(const fixedbv_typet &type) + { + return fixedbvt(fixedbv_spect(type)); + } + void negate(); fixedbvt &operator/=(const fixedbvt &other); diff --git a/src/util/ieee_float.h b/src/util/ieee_float.h index c051351e30d..20239cd92aa 100644 --- a/src/util/ieee_float.h +++ b/src/util/ieee_float.h @@ -169,6 +169,13 @@ class ieee_floatt infinity_flag=false; } + static ieee_floatt zero(const floatbv_typet &type) + { + ieee_floatt result(type); + result.make_zero(); + return result; + } + void make_NaN(); void make_plus_infinity(); void make_minus_infinity(); From d03aa42d0a673413330911c2490d91a90b6fc0c8 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sun, 19 Mar 2017 11:16:46 +0000 Subject: [PATCH 62/67] re-added missing inline keywords --- src/solvers/miniBDD/miniBDD.inc | 40 ++++++++++++++++----------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/src/solvers/miniBDD/miniBDD.inc b/src/solvers/miniBDD/miniBDD.inc index a48f56770cd..091725ed333 100644 --- a/src/solvers/miniBDD/miniBDD.inc +++ b/src/solvers/miniBDD/miniBDD.inc @@ -2,21 +2,21 @@ // inline functions -mini_bddt::mini_bddt():node(0) +inline mini_bddt::mini_bddt():node(0) { } -mini_bddt::mini_bddt(const mini_bddt &x):node(x.node) +inline mini_bddt::mini_bddt(const mini_bddt &x):node(x.node) { if(is_initialized()) node->add_reference(); } -mini_bddt::mini_bddt(class mini_bdd_nodet *_node):node(_node) +inline mini_bddt::mini_bddt(class mini_bdd_nodet *_node):node(_node) { if(is_initialized()) node->add_reference(); } -mini_bddt &mini_bddt::operator=(const mini_bddt &x) +inline mini_bddt &mini_bddt::operator=(const mini_bddt &x) { assert(&x!=this); clear(); @@ -28,56 +28,56 @@ mini_bddt &mini_bddt::operator=(const mini_bddt &x) return *this; } -mini_bddt::~mini_bddt() +inline mini_bddt::~mini_bddt() { clear(); } -bool mini_bddt::is_constant() const +inline bool mini_bddt::is_constant() const { assert(is_initialized()); return node->node_number<=1; } -bool mini_bddt::is_true() const +inline bool mini_bddt::is_true() const { assert(is_initialized()); return node->node_number==1; } -bool mini_bddt::is_false() const +inline bool mini_bddt::is_false() const { assert(is_initialized()); return node->node_number==0; } -unsigned mini_bddt::var() const +inline unsigned mini_bddt::var() const { assert(is_initialized()); return node->var; } -unsigned mini_bddt::node_number() const +inline unsigned mini_bddt::node_number() const { assert(is_initialized()); return node->node_number; } -const mini_bddt &mini_bddt::low() const +inline const mini_bddt &mini_bddt::low() const { assert(is_initialized()); assert(node->node_number>=2); return node->low; } -const mini_bddt &mini_bddt::high() const +inline const mini_bddt &mini_bddt::high() const { assert(is_initialized()); assert(node->node_number>=2); return node->high; } -void mini_bddt::clear() +inline void mini_bddt::clear() { if(is_initialized()) { @@ -86,7 +86,7 @@ void mini_bddt::clear() } } -mini_bdd_nodet::mini_bdd_nodet( +inline mini_bdd_nodet::mini_bdd_nodet( class mini_bdd_mgrt *_mgr, unsigned _var, unsigned _node_number, const mini_bddt &_low, const mini_bddt &_high): @@ -96,33 +96,33 @@ mini_bdd_nodet::mini_bdd_nodet( { } -mini_bdd_mgrt::var_table_entryt::var_table_entryt( +inline mini_bdd_mgrt::var_table_entryt::var_table_entryt( const std::string &_label):label(_label) { } -const mini_bddt &mini_bdd_mgrt::True() const +inline const mini_bddt &mini_bdd_mgrt::True() const { return true_bdd; } -const mini_bddt &mini_bdd_mgrt::False() const +inline const mini_bddt &mini_bdd_mgrt::False() const { return false_bdd; } -void mini_bdd_nodet::add_reference() +inline void mini_bdd_nodet::add_reference() { reference_counter++; } -mini_bdd_mgrt::reverse_keyt::reverse_keyt( +inline mini_bdd_mgrt::reverse_keyt::reverse_keyt( unsigned _var, const mini_bddt &_low, const mini_bddt &_high): var(_var), low(_low.node->node_number), high(_high.node->node_number) { } -std::size_t mini_bdd_mgrt::number_of_nodes() +inline std::size_t mini_bdd_mgrt::number_of_nodes() { return nodes.size()-free.size(); } From f04d40a29938fc21bb90c87f090a09f3a7b9d24e Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sun, 19 Mar 2017 11:17:09 +0000 Subject: [PATCH 63/67] removed dependency on linking module --- src/solvers/smt1/smt1_conv.cpp | 6 ++---- src/solvers/smt2/smt2_conv.cpp | 8 ++------ src/util/simplify_expr.cpp | 8 ++------ 3 files changed, 6 insertions(+), 16 deletions(-) diff --git a/src/solvers/smt1/smt1_conv.cpp b/src/solvers/smt1/smt1_conv.cpp index 493271afd27..d7c89ed8921 100644 --- a/src/solvers/smt1/smt1_conv.cpp +++ b/src/solvers/smt1/smt1_conv.cpp @@ -21,8 +21,6 @@ Author: Daniel Kroening, kroening@kroening.com #include -#include - #include #include #include @@ -1555,7 +1553,7 @@ void smt1_convt::convert_typecast( convert_expr(src, true); out << " "; convert_expr( - zero_initializer(src_type, expr.source_location(), ns), + from_integer(0, src_type), true); out << "))"; } @@ -1584,7 +1582,7 @@ void smt1_convt::convert_typecast( convert_expr(src, true); out << " "; convert_expr( - zero_initializer(src_type, expr.source_location(), ns), + from_integer(0, src_type), true); out << ")) "; // not, = out << " bv1[" << to_width << "]"; diff --git a/src/solvers/smt2/smt2_conv.cpp b/src/solvers/smt2/smt2_conv.cpp index d6fcd8f5b89..badc8646993 100644 --- a/src/solvers/smt2/smt2_conv.cpp +++ b/src/solvers/smt2/smt2_conv.cpp @@ -22,8 +22,6 @@ Author: Daniel Kroening, kroening@kroening.com #include -#include - #include #include #include @@ -2089,8 +2087,7 @@ void smt2_convt::convert_typecast(const typecast_exprt &expr) out << "(not (= "; convert_expr(src); out << " "; - convert_expr( - zero_initializer(src_type, expr.source_location(), ns)); + convert_expr(from_integer(0, src_type)); out << "))"; } else if(src_type.id()==ID_floatbv) @@ -2116,8 +2113,7 @@ void smt2_convt::convert_typecast(const typecast_exprt &expr) out << "(not (= "; convert_expr(src); out << " "; - convert_expr( - zero_initializer(src_type, expr.source_location(), ns)); + convert_expr(from_integer(0, src_type)); out << ")) "; // not, = out << " (_ bv1 " << to_width << ")"; out << " (_ bv0 " << to_width << ")"; diff --git a/src/util/simplify_expr.cpp b/src/util/simplify_expr.cpp index 31ca2171549..837138258d0 100644 --- a/src/util/simplify_expr.cpp +++ b/src/util/simplify_expr.cpp @@ -32,8 +32,6 @@ Author: Daniel Kroening, kroening@kroening.com #include "endianness_map.h" #include "simplify_utils.h" -#include - // #define DEBUGX #ifdef DEBUGX @@ -277,8 +275,7 @@ bool simplify_exprt::simplify_typecast(exprt &expr) inequality.id(op_type.id()==ID_floatbv?ID_ieee_float_notequal:ID_notequal); inequality.add_source_location()=expr.source_location(); inequality.lhs()=expr.op0(); - inequality.rhs()= - zero_initializer(expr.op0().type(), expr.source_location(), ns); + inequality.rhs()=from_integer(0, op_type); assert(inequality.rhs().is_not_nil()); simplify_node(inequality); expr.swap(inequality); @@ -294,8 +291,7 @@ bool simplify_exprt::simplify_typecast(exprt &expr) inequality.id(op_type.id()==ID_floatbv?ID_ieee_float_notequal:ID_notequal); inequality.add_source_location()=expr.source_location(); inequality.lhs()=expr.op0(); - inequality.rhs()= - zero_initializer(expr.op0().type(), expr.source_location(), ns); + inequality.rhs()=from_integer(0, op_type); assert(inequality.rhs().is_not_nil()); simplify_node(inequality); expr.op0()=inequality; From 7a8961e0d0fba1903fe2142f63c1f30b34c3ed32 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sun, 19 Mar 2017 11:28:49 +0000 Subject: [PATCH 64/67] avoid a warning --- src/util/language_file.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/util/language_file.h b/src/util/language_file.h index d3184d48697..4380a346353 100644 --- a/src/util/language_file.h +++ b/src/util/language_file.h @@ -87,7 +87,7 @@ class language_filest:public messaget bool has_lazy_method(const irep_idt &id) { - return lazy_method_map.count(id); + return lazy_method_map.count(id)!=0; } // The method must have been added to the symbol table and registered From 775bbef2ad22d41d9c69d449942524e0e201eb6e Mon Sep 17 00:00:00 2001 From: Daniel Poetzl Date: Mon, 20 Feb 2017 18:56:23 +0000 Subject: [PATCH 65/67] new option --no-caching for use with inlining to disable caching of intermediate results --- regression/goto-instrument/inline_13/main.c | 18 +++++++++++ .../goto-instrument/inline_13/test.desc | 8 +++++ regression/goto-instrument/inline_14/main.c | 23 +++++++++++++ .../goto-instrument/inline_14/test.desc | 8 +++++ .../goto_instrument_parse_options.cpp | 9 ++++-- .../goto_instrument_parse_options.h | 2 +- src/goto-programs/goto_inline.cpp | 13 +++++--- src/goto-programs/goto_inline.h | 9 ++++-- src/goto-programs/goto_inline_class.cpp | 32 ++++++++++++++++++- src/goto-programs/goto_inline_class.h | 10 ++++-- 10 files changed, 119 insertions(+), 13 deletions(-) create mode 100644 regression/goto-instrument/inline_13/main.c create mode 100644 regression/goto-instrument/inline_13/test.desc create mode 100644 regression/goto-instrument/inline_14/main.c create mode 100644 regression/goto-instrument/inline_14/test.desc diff --git a/regression/goto-instrument/inline_13/main.c b/regression/goto-instrument/inline_13/main.c new file mode 100644 index 00000000000..825cf41adf1 --- /dev/null +++ b/regression/goto-instrument/inline_13/main.c @@ -0,0 +1,18 @@ + +int x; + +void g() +{ + x = 1; +} + +void f() +{ + g(); +} + +int main() +{ + f(); +} + diff --git a/regression/goto-instrument/inline_13/test.desc b/regression/goto-instrument/inline_13/test.desc new file mode 100644 index 00000000000..675022c3d73 --- /dev/null +++ b/regression/goto-instrument/inline_13/test.desc @@ -0,0 +1,8 @@ +CORE +main.c +--function-inline main --log - +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/regression/goto-instrument/inline_14/main.c b/regression/goto-instrument/inline_14/main.c new file mode 100644 index 00000000000..058c25c43b9 --- /dev/null +++ b/regression/goto-instrument/inline_14/main.c @@ -0,0 +1,23 @@ + +int x; + +void h() +{ + x = 1; +} + +void g() +{ + h(); +} + +void f() +{ + g(); +} + +int main() +{ + f(); +} + diff --git a/regression/goto-instrument/inline_14/test.desc b/regression/goto-instrument/inline_14/test.desc new file mode 100644 index 00000000000..77c30406741 --- /dev/null +++ b/regression/goto-instrument/inline_14/test.desc @@ -0,0 +1,8 @@ +CORE +main.c +--function-inline main --log - --no-caching +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/src/goto-instrument/goto_instrument_parse_options.cpp b/src/goto-instrument/goto_instrument_parse_options.cpp index 594609ce8ce..b5486355277 100644 --- a/src/goto-instrument/goto_instrument_parse_options.cpp +++ b/src/goto-instrument/goto_instrument_parse_options.cpp @@ -1052,6 +1052,8 @@ void goto_instrument_parse_optionst::instrument_goto_program() std::string function=cmdline.get_value("function-inline"); assert(!function.empty()); + bool caching=!cmdline.isset("no-caching"); + do_indirect_call_and_rtti_removal(); status() << "Inlining calls of function `" << function << "'" << eom; @@ -1063,7 +1065,8 @@ void goto_instrument_parse_optionst::instrument_goto_program() function, ns, ui_message_handler, - true); + true, + caching); } else { @@ -1076,7 +1079,8 @@ void goto_instrument_parse_optionst::instrument_goto_program() function, ns, ui_message_handler, - true); + true, + caching); if(have_file) { @@ -1548,6 +1552,7 @@ void goto_instrument_parse_optionst::help() " --inline perform full inlining\n" " --partial-inline perform partial inlining\n" " --function-inline transitively inline all calls makes\n" // NOLINT(*) + " --no-caching disable caching of intermediate results during transitive function inlining\n" // NOLINT(*) " --log log in json format which code segments were inlined, use with --function-inline\n" // NOLINT(*) " --remove-function-pointers replace function pointers by case statement over function calls\n" // NOLINT(*) " --add-library add models of C library functions\n" diff --git a/src/goto-instrument/goto_instrument_parse_options.h b/src/goto-instrument/goto_instrument_parse_options.h index 1db5f0bdb4d..d3efb975767 100644 --- a/src/goto-instrument/goto_instrument_parse_options.h +++ b/src/goto-instrument/goto_instrument_parse_options.h @@ -53,7 +53,7 @@ Author: Daniel Kroening, kroening@kroening.com "(show-struct-alignment)(interval-analysis)(show-intervals)" \ "(show-uninitialized)(show-locations)" \ "(full-slice)(reachability-slice)(slice-global-inits)" \ - "(inline)(partial-inline)(function-inline):(log):" \ + "(inline)(partial-inline)(function-inline):(log):(no-caching)" \ "(remove-function-pointers)" \ "(show-claims)(show-properties)(property):" \ "(show-symbol-table)(show-points-to)(show-rw-set)" \ diff --git a/src/goto-programs/goto_inline.cpp b/src/goto-programs/goto_inline.cpp index 830798c289e..efe049ec146 100644 --- a/src/goto-programs/goto_inline.cpp +++ b/src/goto-programs/goto_inline.cpp @@ -273,13 +273,15 @@ void goto_function_inline( const irep_idt function, const namespacet &ns, message_handlert &message_handler, - bool adjust_function) + bool adjust_function, + bool caching) { goto_inlinet goto_inline( goto_functions, ns, message_handler, - adjust_function); + adjust_function, + caching); goto_functionst::function_mapt::iterator f_it= goto_functions.function_map.find(function); @@ -327,13 +329,15 @@ jsont goto_function_inline_and_log( const irep_idt function, const namespacet &ns, message_handlert &message_handler, - bool adjust_function) + bool adjust_function, + bool caching) { goto_inlinet goto_inline( goto_functions, ns, message_handler, - adjust_function); + adjust_function, + caching); goto_functionst::function_mapt::iterator f_it= goto_functions.function_map.find(function); @@ -349,6 +353,7 @@ jsont goto_function_inline_and_log( // gather all calls goto_inlinet::inline_mapt inline_map; + // create empty call list goto_inlinet::call_listt &call_list=inline_map[f_it->first]; goto_programt &goto_program=goto_function.body; diff --git a/src/goto-programs/goto_inline.h b/src/goto-programs/goto_inline.h index 33566319100..5d3dd54fa6d 100644 --- a/src/goto-programs/goto_inline.h +++ b/src/goto-programs/goto_inline.h @@ -50,20 +50,23 @@ void goto_function_inline( goto_modelt &goto_model, const irep_idt function, message_handlert &message_handler, - bool adjust_function=false); + bool adjust_function=false, + bool caching=true); void goto_function_inline( goto_functionst &goto_functions, const irep_idt function, const namespacet &ns, message_handlert &message_handler, - bool adjust_function=false); + bool adjust_function=false, + bool caching=true); jsont goto_function_inline_and_log( goto_functionst &goto_functions, const irep_idt function, const namespacet &ns, message_handlert &message_handler, - bool adjust_function=false); + bool adjust_function=false, + bool caching=true); #endif // CPROVER_GOTO_PROGRAMS_GOTO_INLINE_H diff --git a/src/goto-programs/goto_inline_class.cpp b/src/goto-programs/goto_inline_class.cpp index 5afb49f7ae3..c6193248b9b 100644 --- a/src/goto-programs/goto_inline_class.cpp +++ b/src/goto-programs/goto_inline_class.cpp @@ -682,6 +682,12 @@ void goto_inlinet::expand_function_call( function, arguments, constrain); + + if(!caching) + { + inline_log.cleanup(cached.body); + cache.erase(identifier); + } } else { @@ -1146,6 +1152,29 @@ void goto_inlinet::output_inline_map( /*******************************************************************\ +Function: output_cache + + Inputs: + + Outputs: + + Purpose: + +\*******************************************************************/ + +void goto_inlinet::output_cache(std::ostream &out) const +{ + for(auto it=cache.begin(); it!=cache.end(); it++) + { + if(it!=cache.begin()) + out << ", "; + + out << it->first << "\n"; + } +} + +/*******************************************************************\ + Function: cleanup Inputs: @@ -1257,8 +1286,9 @@ void goto_inlinet::goto_inline_logt::copy_from( assert(it1->location_number==it2->location_number); log_mapt::const_iterator l_it=log_map.find(it1); - if(l_it!=log_map.end()) + if(l_it!=log_map.end()) // a segment starts here { + // as 'to' is a fresh copy assert(log_map.find(it2)==log_map.end()); goto_inline_log_infot info=l_it->second; diff --git a/src/goto-programs/goto_inline_class.h b/src/goto-programs/goto_inline_class.h index 495ce7d9155..e043bf48807 100644 --- a/src/goto-programs/goto_inline_class.h +++ b/src/goto-programs/goto_inline_class.h @@ -24,11 +24,13 @@ class goto_inlinet:public messaget goto_functionst &goto_functions, const namespacet &ns, message_handlert &message_handler, - bool adjust_function): + bool adjust_function, + bool caching=true): messaget(message_handler), goto_functions(goto_functions), ns(ns), - adjust_function(adjust_function) + adjust_function(adjust_function), + caching(caching) { } @@ -64,6 +66,8 @@ class goto_inlinet:public messaget std::ostream &out, const inline_mapt &inline_map); + void output_cache(std::ostream &out) const; + // call after goto_functions.update()! jsont output_inline_log_json() { @@ -127,6 +131,8 @@ class goto_inlinet:public messaget const namespacet &ns; const bool adjust_function; + const bool caching; + goto_inline_logt inline_log; void goto_inline_nontransitive( From 0f0ab68e310a1530076bc584c6fe445f8ca46622 Mon Sep 17 00:00:00 2001 From: Daniel Poetzl Date: Mon, 20 Feb 2017 19:14:24 +0000 Subject: [PATCH 66/67] progress output --- regression/goto-instrument/inline_15/main.c | 23 +++++++++++++++++++ .../goto-instrument/inline_15/test.desc | 8 +++++++ src/goto-programs/goto_inline_class.cpp | 13 +++++++++++ 3 files changed, 44 insertions(+) create mode 100644 regression/goto-instrument/inline_15/main.c create mode 100644 regression/goto-instrument/inline_15/test.desc diff --git a/regression/goto-instrument/inline_15/main.c b/regression/goto-instrument/inline_15/main.c new file mode 100644 index 00000000000..058c25c43b9 --- /dev/null +++ b/regression/goto-instrument/inline_15/main.c @@ -0,0 +1,23 @@ + +int x; + +void h() +{ + x = 1; +} + +void g() +{ + h(); +} + +void f() +{ + g(); +} + +int main() +{ + f(); +} + diff --git a/regression/goto-instrument/inline_15/test.desc b/regression/goto-instrument/inline_15/test.desc new file mode 100644 index 00000000000..9e1da6adc9c --- /dev/null +++ b/regression/goto-instrument/inline_15/test.desc @@ -0,0 +1,8 @@ +CORE +main.c +--function-inline main --log - --no-caching --verbosity 9 +^EXIT=0$ +^SIGNAL=0$ +^VERIFICATION SUCCESSFUL$ +-- +^warning: ignoring diff --git a/src/goto-programs/goto_inline_class.cpp b/src/goto-programs/goto_inline_class.cpp index c6193248b9b..ed423a35629 100644 --- a/src/goto-programs/goto_inline_class.cpp +++ b/src/goto-programs/goto_inline_class.cpp @@ -683,8 +683,16 @@ void goto_inlinet::expand_function_call( arguments, constrain); + progress() << "Inserting " << identifier << " into caller" << eom; + progress() << "Number of instructions: " + << cached.body.instructions.size() << eom; + if(!caching) { + progress() << "Removing " << identifier << " from cache" << eom; + progress() << "Number of instructions: " + << cached.body.instructions.size() << eom; + inline_log.cleanup(cached.body); cache.erase(identifier); } @@ -950,6 +958,11 @@ const goto_inlinet::goto_functiont &goto_inlinet::goto_inline_transitive( goto_functiont &cached=cache[identifier]; assert(cached.body.empty()); + + progress() << "Creating copy of " << identifier << eom; + progress() << "Number of instructions: " + << goto_function.body.instructions.size() << eom; + cached.copy_from(goto_function); // location numbers not changed inline_log.copy_from(goto_function.body, cached.body); From a7663cb99706409181b75683aebc22bf36066b65 Mon Sep 17 00:00:00 2001 From: Daniel Kroening Date: Sun, 19 Mar 2017 17:18:34 +0000 Subject: [PATCH 67/67] increased version number to 5.7 --- src/cbmc/version.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/cbmc/version.h b/src/cbmc/version.h index d7a7a08a8ed..017ded44272 100644 --- a/src/cbmc/version.h +++ b/src/cbmc/version.h @@ -1,6 +1,6 @@ #ifndef CPROVER_CBMC_VERSION_H #define CPROVER_CBMC_VERSION_H -#define CBMC_VERSION "5.6" +#define CBMC_VERSION "5.7" #endif // CPROVER_CBMC_VERSION_H