diff --git a/.coveragerc b/.coveragerc
new file mode 100644
index 0000000..05cf3e7
--- /dev/null
+++ b/.coveragerc
@@ -0,0 +1,38 @@
+# ----------------------------------------------------------------------------
+# Copyright 2019 ARM Limited or its affiliates
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ----------------------------------------------------------------------------
+
+# https://coverage.readthedocs.io/en/latest/config.html
+
+[report]
+# Regexes for lines to exclude from consideration
+exclude_lines =
+ # Have to re-enable the standard pragma
+ pragma: no cover
+
+ # Don't complain about missing debug-only code:
+ def __repr__
+ if self\.debug
+
+ # Don't complain if tests don't hit defensive assertion code:
+ raise AssertionError
+ raise NotImplementedError
+ raise argparse.ArgumentTypeError
+
+ # Don't complain if non-runnable code isn't run:
+ if 0:
+ if __name__ == .__main__.:
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..df00ec3
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,15 @@
+
+.idea/
+*.pyc
+*.so
+build/
+*.egg-info/
+venv/
+dist/
+.coverage
+htmlcov/
+.tox/
+.python-version
+tests/mtool/test_data/
+.manifest-dev-tool/
+.vscode/
diff --git a/.pylintrc b/.pylintrc
new file mode 100644
index 0000000..78b80da
--- /dev/null
+++ b/.pylintrc
@@ -0,0 +1,577 @@
+[MASTER]
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code.
+extension-pkg-whitelist=manifesttool.armbsdiff
+
+# Add files or directories to the blacklist. They should be base names, not
+# paths.
+ignore=venv
+
+# Add files or directories matching the regex patterns to the blacklist. The
+# regex matches against base names, not paths.
+ignore-patterns=manifest_schema_v.*\.py
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
+# number of processors available to use.
+jobs=1
+
+# Control the amount of potential inferred values when inferring a single
+# object. This can help the performance when dealing with large functions or
+# complex, nested conditions.
+limit-inference-results=100
+
+# List of plugins (as comma separated values of python modules names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Specify a configuration file.
+#rcfile=
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages.
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED.
+confidence=
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once). You can also use "--disable=all" to
+# disable everything first and then reenable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use "--disable=all --enable=classes
+# --disable=W".
+disable=print-statement,
+ parameter-unpacking,
+ unpacking-in-except,
+ old-raise-syntax,
+ backtick,
+ long-suffix,
+ old-ne-operator,
+ old-octal-literal,
+ import-star-module-level,
+ non-ascii-bytes-literal,
+ raw-checker-failed,
+ bad-inline-option,
+ locally-disabled,
+ file-ignored,
+ suppressed-message,
+ useless-suppression,
+ deprecated-pragma,
+ use-symbolic-message-instead,
+ apply-builtin,
+ basestring-builtin,
+ buffer-builtin,
+ cmp-builtin,
+ coerce-builtin,
+ execfile-builtin,
+ file-builtin,
+ long-builtin,
+ raw_input-builtin,
+ reduce-builtin,
+ standarderror-builtin,
+ unicode-builtin,
+ xrange-builtin,
+ coerce-method,
+ delslice-method,
+ getslice-method,
+ setslice-method,
+ no-absolute-import,
+ old-division,
+ dict-iter-method,
+ dict-view-method,
+ next-method-called,
+ metaclass-assignment,
+ indexing-exception,
+ raising-string,
+ reload-builtin,
+ oct-method,
+ hex-method,
+ nonzero-method,
+ cmp-method,
+ input-builtin,
+ round-builtin,
+ intern-builtin,
+ unichr-builtin,
+ map-builtin-not-iterating,
+ zip-builtin-not-iterating,
+ range-builtin-not-iterating,
+ filter-builtin-not-iterating,
+ using-cmp-argument,
+ eq-without-hash,
+ div-method,
+ idiv-method,
+ rdiv-method,
+ exception-message-attribute,
+ invalid-str-codec,
+ sys-max-int,
+ bad-python3-import,
+ deprecated-string-function,
+ deprecated-str-translate-call,
+ deprecated-itertools-function,
+ deprecated-types-field,
+ next-method-defined,
+ dict-items-not-iterating,
+ dict-keys-not-iterating,
+ dict-values-not-iterating,
+ deprecated-operator-function,
+ deprecated-urllib-function,
+ xreadlines-attribute,
+ deprecated-sys-function,
+ exception-escape,
+ comprehension-escape,
+ too-many-arguments,
+ too-many-locals,
+ missing-docstring,
+ duplicate-code,
+ too-many-public-methods
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[REPORTS]
+
+# Python expression which should return a note less than 10 (10 is the highest
+# note). You have access to the variables errors warning, statement which
+# respectively contain the number of errors / warnings messages and the total
+# number of statements analyzed. This is used by the global evaluation report
+# (RP0004).
+evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details.
+#msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio). You can also give a reporter class, e.g.
+# mypackage.mymodule.MyReporterClass.
+output-format=text
+
+# Tells whether to display a full report or only the messages.
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=sys.exit
+
+
+[LOGGING]
+
+# Format style used to check logging format string. `old` means using %
+# formatting, while `new` is for `{}` formatting.
+logging-format-style=old
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format.
+logging-modules=logging
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes.
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: none. To make it working
+# install python-enchant package..
+spelling-dict=
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to indicated private dictionary in
+# --spelling-private-dict-file option instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+ XXX,
+ TODO
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether missing members accessed in mixin class should be ignored. A
+# mixin class is detected if its name ends with "mixin" (case insensitive).
+ignore-mixin-members=yes
+
+# Tells whether to warn about missing members when the owner of the attribute
+# is inferred to be None.
+ignore-none=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis. It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid defining new builtins when possible.
+additional-builtins=
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+ _cb
+
+# A regular expression matching the name of dummy variables (i.e. expected to
+# not be used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore.
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )??$
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
+# tab).
+indent-string=' '
+
+# Maximum number of characters on a single line.
+max-line-length=100
+
+# Maximum number of lines in a module.
+max-module-lines=1000
+
+# List of optional constructs for which whitespace checking is disabled. `dict-
+# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
+# `trailing-comma` allows a space between comma and closing bracket: (a, ).
+# `empty-line` allows space-only lines.
+no-space-check=trailing-comma,
+ dict-separator
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[SIMILARITIES]
+
+# Ignore comments when computing similarities.
+ignore-comments=yes
+
+# Ignore docstrings when computing similarities.
+ignore-docstrings=yes
+
+# Ignore imports when computing similarities.
+ignore-imports=no
+
+# Minimum lines number of a similarity.
+min-similarity-lines=15
+
+
+[BASIC]
+
+# Naming style matching correct argument names.
+argument-naming-style=snake_case
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style.
+#argument-rgx=
+
+# Naming style matching correct attribute names.
+attr-naming-style=snake_case
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style.
+#attr-rgx=
+
+# Bad variable names which should always be refused, separated by a comma.
+bad-names=foo,
+ bar,
+ baz,
+ toto,
+ tutu,
+ tata
+
+# Naming style matching correct class attribute names.
+class-attribute-naming-style=any
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style.
+#class-attribute-rgx=
+
+# Naming style matching correct class names.
+class-naming-style=PascalCase
+
+# Regular expression matching correct class names. Overrides class-naming-
+# style.
+#class-rgx=
+
+# Naming style matching correct constant names.
+const-naming-style=UPPER_CASE
+
+# Regular expression matching correct constant names. Overrides const-naming-
+# style.
+#const-rgx=
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=1000
+
+# Naming style matching correct function names.
+function-naming-style=snake_case
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style.
+#function-rgx=
+
+# Good variable names which should always be accepted, separated by a comma.
+good-names=i,
+ j,
+ k,
+ ex,
+ Run,
+ _,
+ fh,
+ logger
+
+# Include a hint for the correct naming format with invalid-name.
+include-naming-hint=no
+
+# Naming style matching correct inline iteration names.
+inlinevar-naming-style=any
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style.
+#inlinevar-rgx=
+
+# Naming style matching correct method names.
+method-naming-style=snake_case
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style.
+#method-rgx=
+
+# Naming style matching correct module names.
+module-naming-style=snake_case
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style.
+#module-rgx=
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+# These decorators are taken in consideration only for invalid-name.
+property-classes=abc.abstractproperty
+
+# Naming style matching correct variable names.
+variable-naming-style=snake_case
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style.
+#variable-rgx=
+
+
+[STRING]
+
+# This flag controls whether the implicit-str-concat-in-sequence should
+# generate a warning on implicit string concatenation in sequences defined over
+# several lines.
+check-str-concat-over-line-jumps=no
+
+
+[IMPORTS]
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Deprecated modules which should not be used, separated by a comma.
+deprecated-modules=optparse,tkinter.tix
+
+# Create a graph of external dependencies in the given file (report RP0402 must
+# not be disabled).
+ext-import-graph=
+
+# Create a graph of every (i.e. internal and external) dependencies in the
+# given file (report RP0402 must not be disabled).
+import-graph=
+
+# Create a graph of internal dependencies in the given file (report RP0402 must
+# not be disabled).
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+
+[CLASSES]
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+ __new__,
+ setUp
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+ _fields,
+ _replace,
+ _source,
+ _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=cls
+
+
+[DESIGN]
+
+# Maximum number of arguments for function / method.
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in an if statement.
+max-bool-expr=5
+
+# Maximum number of branch for function / method body.
+max-branches=12
+
+# Maximum number of locals for function / method body.
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body.
+max-returns=6
+
+# Maximum number of statements in function / method body.
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when being caught. Defaults to
+# "BaseException, Exception".
+overgeneral-exceptions=BaseException,
+ Exception
diff --git a/LICENSE b/LICENSE
index 59cd3f8..147745e 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,165 +1,15 @@
-Apache License
-Version 2.0, January 2004
-http://www.apache.org/licenses/
+Copyright 2019 ARM Limited or its affiliates
-TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+SPDX-License-Identifier: Apache-2.0
-1. Definitions.
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
-"License" shall mean the terms and conditions for use, reproduction, and
-distribution as defined by Sections 1 through 9 of this document.
+ http://www.apache.org/licenses/LICENSE-2.0
-"Licensor" shall mean the copyright owner or entity authorized by the copyright
-owner that is granting the License.
-
-"Legal Entity" shall mean the union of the acting entity and all other entities
-that control, are controlled by, or are under common control with that entity.
-For the purposes of this definition, "control" means (i) the power, direct or
-indirect, to cause the direction or management of such entity, whether by
-contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
-outstanding shares, or (iii) beneficial ownership of such entity.
-
-"You" (or "Your") shall mean an individual or Legal Entity exercising
-permissions granted by this License.
-
-"Source" form shall mean the preferred form for making modifications, including
-but not limited to software source code, documentation source, and configuration
-files.
-
-"Object" form shall mean any form resulting from mechanical transformation or
-translation of a Source form, including but not limited to compiled object code,
-generated documentation, and conversions to other media types.
-
-"Work" shall mean the work of authorship, whether in Source or Object form, made
-available under the License, as indicated by a copyright notice that is included
-in or attached to the work (an example is provided in the Appendix below).
-
-"Derivative Works" shall mean any work, whether in Source or Object form, that
-is based on (or derived from) the Work and for which the editorial revisions,
-annotations, elaborations, or other modifications represent, as a whole, an
-original work of authorship. For the purposes of this License, Derivative Works
-shall not include works that remain separable from, or merely link (or bind by
-name) to the interfaces of, the Work and Derivative Works thereof.
-
-"Contribution" shall mean any work of authorship, including the original version
-of the Work and any modifications or additions to that Work or Derivative Works
-thereof, that is intentionally submitted to Licensor for inclusion in the Work
-by the copyright owner or by an individual or Legal Entity authorized to submit
-on behalf of the copyright owner. For the purposes of this definition,
-"submitted" means any form of electronic, verbal, or written communication sent
-to the Licensor or its representatives, including but not limited to
-communication on electronic mailing lists, source code control systems, and
-issue tracking systems that are managed by, or on behalf of, the Licensor for
-the purpose of discussing and improving the Work, but excluding communication
-that is conspicuously marked or otherwise designated in writing by the copyright
-owner as "Not a Contribution."
-
-"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
-of whom a Contribution has been received by Licensor and subsequently
-incorporated within the Work.
-
-2. Grant of Copyright License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable copyright license to reproduce, prepare Derivative Works of,
-publicly display, publicly perform, sublicense, and distribute the Work and such
-Derivative Works in Source or Object form.
-
-3. Grant of Patent License.
-
-Subject to the terms and conditions of this License, each Contributor hereby
-grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
-irrevocable (except as stated in this section) patent license to make, have
-made, use, offer to sell, sell, import, and otherwise transfer the Work, where
-such license applies only to those patent claims licensable by such Contributor
-that are necessarily infringed by their Contribution(s) alone or by combination
-of their Contribution(s) with the Work to which such Contribution(s) was
-submitted. If You institute patent litigation against any entity (including a
-cross-claim or counterclaim in a lawsuit) alleging that the Work or a
-Contribution incorporated within the Work constitutes direct or contributory
-patent infringement, then any patent licenses granted to You under this License
-for that Work shall terminate as of the date such litigation is filed.
-
-4. Redistribution.
-
-You may reproduce and distribute copies of the Work or Derivative Works thereof
-in any medium, with or without modifications, and in Source or Object form,
-provided that You meet the following conditions:
-
-You must give any other recipients of the Work or Derivative Works a copy of
-this License; and
-You must cause any modified files to carry prominent notices stating that You
-changed the files; and
-You must retain, in the Source form of any Derivative Works that You distribute,
-all copyright, patent, trademark, and attribution notices from the Source form
-of the Work, excluding those notices that do not pertain to any part of the
-Derivative Works; and
-If the Work includes a "NOTICE" text file as part of its distribution, then any
-Derivative Works that You distribute must include a readable copy of the
-attribution notices contained within such NOTICE file, excluding those notices
-that do not pertain to any part of the Derivative Works, in at least one of the
-following places: within a NOTICE text file distributed as part of the
-Derivative Works; within the Source form or documentation, if provided along
-with the Derivative Works; or, within a display generated by the Derivative
-Works, if and wherever such third-party notices normally appear. The contents of
-the NOTICE file are for informational purposes only and do not modify the
-License. You may add Your own attribution notices within Derivative Works that
-You distribute, alongside or as an addendum to the NOTICE text from the Work,
-provided that such additional attribution notices cannot be construed as
-modifying the License.
-You may add Your own copyright statement to Your modifications and may provide
-additional or different license terms and conditions for use, reproduction, or
-distribution of Your modifications, or for any such Derivative Works as a whole,
-provided Your use, reproduction, and distribution of the Work otherwise complies
-with the conditions stated in this License.
-
-5. Submission of Contributions.
-
-Unless You explicitly state otherwise, any Contribution intentionally submitted
-for inclusion in the Work by You to the Licensor shall be under the terms and
-conditions of this License, without any additional terms or conditions.
-Notwithstanding the above, nothing herein shall supersede or modify the terms of
-any separate license agreement you may have executed with Licensor regarding
-such Contributions.
-
-6. Trademarks.
-
-This License does not grant permission to use the trade names, trademarks,
-service marks, or product names of the Licensor, except as required for
-reasonable and customary use in describing the origin of the Work and
-reproducing the content of the NOTICE file.
-
-7. Disclaimer of Warranty.
-
-Unless required by applicable law or agreed to in writing, Licensor provides the
-Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
-including, without limitation, any warranties or conditions of TITLE,
-NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
-solely responsible for determining the appropriateness of using or
-redistributing the Work and assume any risks associated with Your exercise of
-permissions under this License.
-
-8. Limitation of Liability.
-
-In no event and under no legal theory, whether in tort (including negligence),
-contract, or otherwise, unless required by applicable law (such as deliberate
-and grossly negligent acts) or agreed to in writing, shall any Contributor be
-liable to You for damages, including any direct, indirect, special, incidental,
-or consequential damages of any character arising as a result of this License or
-out of the use or inability to use the Work (including but not limited to
-damages for loss of goodwill, work stoppage, computer failure or malfunction, or
-any and all other commercial damages or losses), even if such Contributor has
-been advised of the possibility of such damages.
-
-9. Accepting Warranty or Additional Liability.
-
-While redistributing the Work or Derivative Works thereof, You may choose to
-offer, and charge a fee for, acceptance of support, warranty, indemnity, or
-other liability obligations and/or rights consistent with this License. However,
-in accepting such obligations, You may act only on Your own behalf and on Your
-sole responsibility, not on behalf of any other Contributor, and only if You
-agree to indemnify, defend, and hold each Contributor harmless for any liability
-incurred by, or claims asserted against, such Contributor by reason of your
-accepting any such warranty or additional liability.
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
diff --git a/MANIFEST.in b/MANIFEST.in
index 8afbefe..f702bce 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,2 +1,6 @@
include README.md
+include changelog.md
include requirements.txt
+include bsdiff/*.h
+include manifesttool/dev_tool/actions/code_template.txt
+include manifesttool/mtool/manifest-input-schema.json
diff --git a/README.md b/README.md
index e333451..5a2681d 100644
--- a/README.md
+++ b/README.md
@@ -1,533 +1,658 @@
-## Update manifest creation
+# Device Management manifest CLI tool
-### Manifest tool
+This document explains how to install and use the manifest tool.
-The manifest tool creates and parses manifest files. You can use it as a command-line utility or Python package.
+- [Manifest tool overview](#manifest-tool-overview)
+- [Installing the manifest tool](#installing-the-manifest-tool)
+- [Using the manifest tool](#using-the-manifest-tool)
+- [Developer workflow example](#developer-workflow-example)
+- [Troubleshooting](#troubleshooting)
-### Installation
+**Note:** Please see the [changelog](./changelog.md) for the list of all changes between release versions.
-The manifest tool is compatible both with Python 2.7.11 and later and with Python 3.5.1 and later.
+## Manifest tool overview
+Device Management lets you perform Firmware Over-the-Air (FOTA) updates
+on managed devices.
-There are 4 options for installing the manifest tool, but all use `pip`:
+On the device side, the firmware update process begins when the device
+receives an update manifest. The OEM (original equipment manufacturer)
+or update author cryptographically signs the manifest with a private key
+paired to a public key that exists on the device, enabling the device to
+authenticate the manifest before it accepts the firmware update.
-1. Install from PyPi with pip.
+Device Management supports:
- ```
- $ pip install manifest-tool
- ```
+* Full updates - Deliver new firmware and install it on the device.
+* Delta updates - The manifest tool executes a diff algorithm that
+ produces a small delta patch file. The nano client constructs a new
+ firmware image based on the delta patch file and the firmware
+ currently present on the device. This technique saves traffic
+ bandwidth.
-1. Install from GitHub over HTTPS.
+The `manifest-tool` Python package includes these command line tools:
- ```
- $ pip install git+https://github.com/ARMmbed/manifest-tool.git
- ```
+- [`manifest-tool`](#manifest-tool) - Creates manifest files.
+- [`manifest-delta-tool`](#manifest-delta-tool) - Generates delta patch
+ files.
+- [`manifest-dev-tool`](#manifest-dev-tool) - A developer tool for
+ running a simplified update campaign.
-1. Install from GitHub over SSH.
+## Installing the manifest tool
- ```
- $ pip install git+ssh://git@github.com/ARMmbed/manifest-tool.git
- ```
+We recommend installing the `manifest-tool` Python package in a
+[Python virtual environment](#creating-a-virtual-environment).
-1. Install from a local copy of this repository.
+### Installing from PyPi
- ```
- $ pip install .
- ```
-
-**Note:** This repository includes `setup.py`, but it does not work on all systems. Please use `pip` for the best experience.
-
-See [Debugging Installation](#debugging-installation) if these steps do not work.
+**Prerequisites:**
-### Set up the Device Management Python SDK (optional)
+* [Python 3.5 or higher](https://www.python.org/downloads/).
+* [pip (Python Package Installer)](https://pip.pypa.io/en/stable/).
+* Internet connectivity
-You can use the SDKs to automate uploading your manifest to Device Management (as detailed below); this requires installing the SDKs. If you do not want to install the SDKs, use the Update service API or Device Management Portal to upload the manifest.
+**To install the manifest tool from [PyPi](https://pypi.org/), run:**
-Install the the Python SDK directly from GitHub:
```
- $ pip install git+https://github.com/ARMmbed/mbed-cloud-sdk-python.git
+pip install manifest-tool
```
-### Workflow
+### Installing from local source tree
-The Update client workflow has three stages:
+**Prerequisites:**
-1. Send a payload to an update medium, for example a web service, a removable storage device or a broadcast system.
-1. Create a manifest for that payload. The manifest includes the hash and size of the payload along with its URI on the update medium.
-1. Send that manifest to an update medium.
+* [Python 3.5 or later](https://www.python.org/downloads/).
+* [pip (Python Package Installer)](https://pip.pypa.io/en/stable/).
+* Native toolchain:
+ * GCC/Clang for Linux/MacOS.
+ * Microsoft Visual Studio 2017 or later for Windows.
-### Quick Start
+**To install the manifest tool from the local source tree, run:**
-In a new project that will support the Update client, run the following command:
-
-```
-$ manifest-tool init -d "" -m "" -a "" -S ""
-```
+1. Clone the ARMmbed/manifest-tool repository to your machine:
-Note that you do not need to enter `-S` for the production environment.
+ ```
+ $ git clone git@github.com:ARMmbed/manifest-tool.git ./manifest-tool
+ ```
-The manifest tool is able to use the Device Management Python SDK to upload firmware and manifests to Device Management. If you do not require this feature, you can call `manifest-tool init` with fewer arguments:
+1. Run:
-```
-$ manifest-tool init -d "" -m ""
-```
+ ```
+ $ pip install
+ ```
-This will create several files:
-* A certificate in `.update-certificates/default.der`.
-* A matching private key in `.update-certificates/default.key.pem`.
-* A set of default settings in `.manifest_tool.json`.
-* Device Management settings in `.mbed_cloud_config.json`.
+ Where `` is the path to the local source tree.
-The default settings include:
-* A unique vendor identifier, based on the domain name supplied to `init`.
-* A unique model identifier, based on the vendor identifier and the model name supplied to `init`.
-* The path of the certificate and private key.
+**Note:** Run `$ pip install -e ` to install the package in Python setuptools development mode. For more information, please see the [setuptools development mode documentation](https://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode).
-If you do not want to enter the subject information for your certificate (country, state, city, organization and so on), add the `-q` flag to the command above.
+### Creating a virtual environment
-**Note:** The certificate created in `manifest-tool init` is not suitable for production. You should avoid using it except in testing and development. To create a certificate for production purposes, please use an air-gapped computer or a Hardware Security Module. You should conduct a security review on your manifest signing infrastructure, since it is the core of the security guarantees for Update client.
+The `virtualenv` tool creates isolated Python environments, which are
+useful in overcoming Python package collision issues when you work on
+multiple projects. For more information, please see the
+[Python documentation](https://docs.python.org/tutorial/venv.html).
-#### Single-device update
-Once you have run `manifest-tool init`, you can perform updates on a single device by:
+**To create a virtual environment, run:**
-```sh
-$ manifest-tool update device -p -D
+```shell
+$ virtualenv -p python3 venv
```
-This will perform several actions:
-1. Upload the payload to Device Management.
-1. Hash the payload and create a manifest that links to its location in Device Management.
-1. Create an update campaign for the supplied device ID, with the newly created manifest.
-1. Start the campaign.
-1. Wait for the campaign to complete.
-1. Delete the payload, manifest and update campaign out of Device Management.
-
-This allows development with a device for testing purposes.
+**To activate the virtual environment in the current shell, run:**
-#### Multidevice update
-
-If more than one device needs updating, you can use Device Management Portal to create device filters that can include many devices into an update campaign. First, you need a manifest. Once you have run `manifest-tool init`, you can create manifests by:
-
-```
-$ manifest-tool update prepare -p
+```shell
+$ source venv/bin/activate
```
-Optionally, a name and description for the payload and corresponding manifest can be provided:
-
-```
-$ manifest-tool update prepare -p -n -d \
- --manifest-name --manifest-description
-```
+## Using the manifest tool
-Both methods of creating a manifest use the defaults created in `manifest-tool init`. You can override each default using an input file or command-line arguments. See below for more details.
+This section explains how to use the CLI tools included in the
+`manifest-tool` Python package:
-Once `manifest-tool update prepare` has been executed the manifest file is automatically uploaded to Device Management and you can then create and start an update campaign using the Device Management portal.
+- [manifest-tool](#manifest-tool)
+- [manifest-delta-tool](#manifest-delta-tool)
+- [manifest-dev-tool](#manifest-dev-tool)
+- [Developer workflow example](#developer-workflow-example)
-### External signing tool
+### manifest-tool
-The documentation can be found [here](https://cloud.mbed.com/docs/current/updating-firmware/external-signing-tools.html).
+`manifest-tool` commands:
-### Debugging Installation
+- [`manifest-tool create`](#manifest-tool-create) - Creates manifests.
+- [`manifest-tool create-v1`](#manifest-tool-create-v1) - Creates V1
+ schema-compatible manifests.
+- [`manifest-tool parse`](#manifest-tool-parse) - Parses and verifies
+ existing manifest files.
+- [`manifest-tool schema`](#manifest-tool-schema) - Shows bundled input
+ validation schema.
+- [`manifest-tool public-key`](#manifest-tool-public-key) - Generates an
+ uncompressed public key.
-Some platforms require `python-dev` or `python3-dev` to install Python's cryptography library, which is a dependency of the manifest tool. For example, on Ubuntu, run:
+**Note:** Run `manifest-tool --help` for more information about all commands, or `manifest-tool --help` for more information about a specific command, including its parameters and how to use them.
-```sh
-$ sudo apt-get install python-dev
-```
+#### `manifest-tool create`
-### Advanced usage
+Creates a manifest. The manifest tool receives a configuration file
+describing the update type.
-The manifest tool allows for significantly more flexibility than the model above shows. You can override each of the defaults that `manifest-tool init` sets by using the command-line or an input file. The manifest tool supports a variety of commands. You can print a full list of commands by using `manifest-tool --help`.
+**Prerequisites**
+* An update private key and public key certificate.
-#### Advanced creation Prerequisites
+ Keep the private key secret because it allows installing new
+ firmware images on your devices.
-To create a manifest, you must provide an ECC certificate and private key. The certificate must be an ECC secp256r1 DER encoded certificate. Best practice is for an authority the target device trusts to sign this certificate.
+ Provision the public key to the device.
-The Update client on the target device must have this certificate available, or the certificate must be signed by a certificate that is available on the target device.
+ * To generate a private key, run:
-##### Creating a certificate for production use
+ ```shell
+ $ openssl ecparam -genkey -name prime256v1 -outform PEM -out my.pkey.pem
+ ```
-To use a certificate in production, please use a Hardware Security Module or an air-gapped computer to create the certificate. You can then use this device to create signatures for manifests. If you use certificate delegation, you can use the HSM or air-gapped computer to sign the delegated certificates. You should perform a security review on your signing infrastructure.
+ * To generate a public key in uncompressed point format (X9.62), use
+ the [`manifest-tool public-key`](#manifest-tool-public-key)
+ command.
-##### Creating a certificate for development use
+* Upload the new firmware binary to a server that the device you want to
+ update can reach, and obtain the URL for the uploaded firmware binary.
-**For testing and evaluation only**
+* A configuration file in JSON or YAML format.
-Providing a self-signed certificate is adequate for testing purposes. There are many methods for creating a self-signed certificate. The manifest tool provides two commands: `init` and `cert create`, which creates a self-signed certificate. OpenSSL can also produce one, but we do not recommended this on Mac OS X, due to the old version of OpenSSL that ships with it, nor on Windows, because you must install OpenSSL separately.
+ Configuration file format:
+ ```yaml
+ vendor: # One of "domain" or "vendor-id" fields are expected
+ domain: arm.com # FW owner domain. Expected to include a dot (".")
+ vendor-id: fa6b4a53d5ad5fdfbe9de663e4d41ffe # Valid vendor UUID
+ device: # One of "model-name" or "class-id" fields are expected
+ model-name: Smart Slippers # A device model name
+ vendor-id: fa6b4a53d5ad5fdfbe9de663e4d41ffe # Valid device-class UUID
-###### Creating a self-signed certificate with manifest-tool init
+ priority: 1 # Update priority as will be passed to authorization callback
+ # implemented by application on a device side
+ payload:
+ url: http://some-url.com/files?id=1234 # File storage URL for devices to
+ # acquire the FW candidate
+ file-path: ./my.fw.bin # Update candidate local file - for digest
+ # calculation & signing
+ format: raw-binary # one of following:
+ # raw-binary - for full image update
+ # arm-patch-stream - for differential update
+ component: MAIN # [Optional] Component name - only relevant for manifest v3 format.
+ # If omitted "MAIN" component name will be used for updating
+ # the main application image
+ sign-image: True # [Optional] Boolean field accepting True/False values - only
+ # relevant for manifest v3 format.
+ # When Set to True - 64 Bytes raw signature over the installed
+ # image will be added to the manifest.
+ # Image signature can be used for cases when device bootloader
+ # expects to work with signed images (e.g. secure-boot)
+ # When omitted False value is assumed
+ ```
+**Example**
+
+* For this configuration file, called `my.config.yaml`:
+
+ ```yaml
+ vendor:
+ domain: arm.com
+ device:
+ model-name: Smart Flip-flops
+ priority: 1
+ payload:
+ url: http://some-url.com/files?id=1234
+ file-path: ./my.fw.bin
+ format: raw-binary
+ ```
-Running `manifest-tool init` in a project for the first time also creates a self-signed certificate. If a certificate already exists in `.update-certificates/default.der`, then no certificate is created. If you already have a certificate and private key, you should pass those in to `manifest-tool init` using the `-c ` and `-k ` arguments.
+* Run:
-###### Creating a self-signed certificate with manifest-tool cert create
+ ```shell
+ manifest-tool create \
+ --config my.config.yml \
+ --key my.priv.key.pem \
+ --fw-version 1.2.3 \
+ --output my.manifest.bin
+ ```
-The manifest tool provides a certificate creation command, which creates a self-signed certificate:
+#### `manifest-tool create-v1`
-```
-manifest-tool cert create -V -K -o
-```
+Older versions of Device Management FOTA update client use manifest
+schema V1 and assume the public key is packaged in a x.509 certificate.
-In addition, you can provide subject arguments on the command-line to specify the country, state, locality, organization name and common name of the certificate's subject.
+**Prerequisites**
-###### Creating a self-signed certificate with OpenSSL
+* An update private key and public key certificate.
-Using OpenSSL, you can create a self-signed ECC certificate, but there are several caveats:
+ Keep the private key secret because it allows installing new
+ firmware images on your devices.
-* OpenSSL defaults to SHA1 on many platforms, which is unsecure.
-* On some platforms, it is not possible to specify SHA256.
-* OpenSSL does not support ECC on some platforms.
+ Provision the public key to the device.
-**Unless the version of OpenSSL your platform provides is at least 1.0.1, we do not recommend you use OpenSSL.**
+ * To generate a private key, run:
-In order to generate a self-signed certificate, follow these steps:
+ ```shell
+ $ openssl ecparam -genkey -name prime256v1 -outform PEM -out my.pkey.pem
+ ```
+ * To generate a public key x.509 certificate, run:
-```
-openssl ecparam -genkey -name prime256v1 -out key.pem
-openssl req -new -sha256 -key key.pem -out csr.csr
-openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -outform der -out certificate.der
-```
+ ```shell
+ $ openssl req -new -sha256 \
+ -key my.pkey.pem \
+ -inform PEM \
+ -out my.csr.csr
+ $ openssl req -x509 -sha256 \
+ -days 7300 \
+ -key my.pkey.pem \
+ -in my.csr.csr \
+ -outform der \
+ -out my.x509.certificate.der
+ ```
-**Note:** `prime256v1` is an alias for `secp256r1`.
+ **Note:** Device Management FOTA treats the x.509 certificate as a container **ONLY** and does not enforce its validity - expiration, chain of trust, and so on - although it may be validated by other Device Management components. For production, we recommend creating a certificate with a lifespan greater than the product's expected lifespan (for example, 20 years).
-Now, verify that OpenSSL used SHA256 to sign the certificate. Some OpenSSL installations ignore the `-sha256` parameter and create a SHA1 signature. This is a problem because of the deprecation of SHA1 due to weak security.
+**Example**
-```
-openssl req -in csr.csr -text -noout | grep -i "Signature.*SHA256"
-```
+* For this configuration file, called `my.config.yaml`:
-#### Examining a certificate
+ ```yaml
+ vendor:
+ domain: arm.com
+ device:
+ model-name: DUT.my.device
+ priority: 1
+ payload:
+ url: http://some-url.com/files?id=1234
+ file-path: ./my.fw.bin
+ format: raw-binary
+ ```
-To view the information in a certificate, use OpenSSL's x509 command:
+* Run:
-```
-openssl x509 -inform der -in certificate.der -text -noout
-```
+ ```shell
+ manifest-tool create-v1 \
+ --config my.config.yaml \
+ --key my.priv.key.pem \
+ --update-certificate my.x509.certificate.der \
+ --output my.manifest.bin
+ ```
-#### Obtaining a certificate fingerprint
+#### `manifest-tool parse`
-The manifest tool fingerprints certificates during the manifest creation process. If you used `manifest-tool init`, then it is not necessary to extract the fingerprint.
+Parses and validates existing manifest files.
-You can use OpenSSL to check the manifest-tool's output or to obtain the certificate fingerprint if `manifest-tool init` was not used:
+**Prerequisites**
-```
-openssl x509 -inform der -in certificate.der -sha256 -fingerprint -noout
-```
+* A manifest file (in our example `my.manifest.bin`).
+* Optionally, an update private key or public key or certificate to
+ validate the manifest signature.
-OpenSSL reports the fingerprint of the certificate:
+**Example**
-```
-SHA256 Fingerprint=00:01:02:03:04:05:06:07:08:09:0A:0B:0C:0D:0E:0F:10:11:12:13:14:15:16:17:18:19:1A:1B:1C:1D:1E:1F
+```shell
+$ manifest-tool parse \
+ --manifest my.manifest.bin \
+ --private-key my.priv.key.pem
+----- Manifest dump start -----
+Manifest:
+vendor-id=fa6b4a53d5ad5fdfbe9de663e4d41ffe
+class-id=3da0f138173350eba6f665498eace1b1
+update-priority=15
+payload-version=1572372313
+payload-digest=b5f07d6c646a7c014cc8c03d2c9caf066bd29006f1356eaeaf13b7d889d3502b
+payload-size=512
+payload-uri=https://my.server.com/some.file?new=1
+payload-format=raw-binary
+----- Manifest dump end -----
+2019-10-29 20:05:13,478 INFO Signature verified!
```
-When a C byte array is a requirement (for example, in the Update client's certificate manager), this must be converted to one, for example by finding all `:` and replacing with `, 0x`.
+#### `manifest-tool schema`
-```
-0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F
-```
+Prints the input validation JSON schema bundled with the current tool.
+The manifest tool contains an input validation schema, which you can use
+as a self-documenting tool to better understand and validate the
+manifest tool input configuration.
-This can be done in an automated way on systems that support the `sed` command. For example:
+**Example**
+```shell
+$ manifest-tool schema
```
-openssl x509 -inform der -in certificate.der -noout -fingerprint -sha256 | sed -e "s/.*=\(.*\)/\1/" | sed -e "s/:/, 0x/g" | sed -e "s/\(.*\)/uint8_t arm_uc_default_fingerprint[] = {0x\1};/"
-uint8_t arm_uc_default_fingerprint[] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F};
-```
+Output:
-To turn the certificate itself into a byte array, use `xxd` or a similar tool for printing hexadecimal values:
-
-```
-xxd -i certificate.der
+```json
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "Manifest-tool input validator",
+ "description": "This schema is used to validate the input arguments for manifest-tool",
+ "type": "object",
+ "required": [
+ "vendor",
+ "device",
+ "priority",
+ "payload"
+ ],
+ "properties": {
+ "vendor": {
+ "type": "object",
+ "properties": {
+ "domain": {
+ "$ref": "#/definitions/non_empty_string",
+ "description": "Vendor Domain",
+ "pattern": "\\w+(\\.\\w+)+"
+ },
+ "vendor-id": {
+ "$ref": "#/definitions/uuid_hex_string",
+ "description": "Vendor UUID"
+ },
+ "custom-data-path": {
+ "$ref": "#/definitions/non_empty_string",
+ "description": "Path to custom data file - must be accessible by the manifest-tool"
+ }
+ },
+ "oneOf": [
+ {"required": ["domain"]},
+ {"required": ["vendor-id"]}
+ ]
+ },
+ "device": {
+ "type": "object",
+ "properties": {
+ "model-name": {
+ "$ref": "#/definitions/non_empty_string",
+ "description": "Device model name"
+ },
+ "class-id": {
+ "$ref": "#/definitions/uuid_hex_string",
+ "description": "Device class UUID"
+ }
+ },
+ "oneOf": [
+ {"required": ["model-name"]},
+ {"required": ["class-id"]}
+ ]
+ },
+ "priority": {
+ "description": "Update priority",
+ "type": "integer"
+ },
+ "payload": {
+ "type": "object",
+ "required": [
+ "url",
+ "format",
+ "file-path"
+ ],
+ "properties": {
+ "format": {
+ "description": "Payload format type",
+ "enum": [
+ "raw-binary",
+ "arm-patch-stream"
+ ]
+ },
+ "url": {
+ "$ref": "#/definitions/non_empty_string",
+ "description": "Payload URL in the cloud storage"
+ },
+ "file-path": {
+ "$ref": "#/definitions/non_empty_string",
+ "description": "Path to payload file - must be accessible by the manifest-tool"
+ }
+ }
+ },
+ "component": {
+ "description": "Component name - only relevant for manifest v3",
+ "$ref": "#/definitions/non_empty_string"
+ },
+ "sign-image":{
+ "description": "Do sign installed image - only relevant for manifest v3. Required for devices with PKI image authentication in bootloader",
+ "type": "boolean"
+ }
+ },
+ "definitions": {
+ "non_empty_string": {
+ "type": "string",
+ "minLength": 1
+ },
+ "uuid_hex_string": {
+ "type": "string",
+ "pattern": "[0-9a-fA-F]{32}",
+ "description": "HEX encoded UUID string"
+ }
+ }
+}
```
-The manifest tool automates this process as part of the `init` command and places the output in `update_default_resources.c`.
-
-#### Creating manifests
+**Note:** This schema is an example captured for manifest-tool version 2.0. Make sure to execute the `manifest-tool schema` command on your machine to get the up-to-date schema for your installed tool version.
-There are three ways to provide data to the manifest tool. It parses a JSON input file, which can contain all of the information used to create the manifest. If information is missing from the input file, the manifest tool checks for a file that contains defaults in the current working directory (`.manifest_tool.json`). You can create this file most easily using `manifest-tool init`. The third way of providing data is command-line arguments; you can override many of the fields the manifest tool uses on the command-line.
+#### `manifest-tool public-key`
-Currently, you need manifests to use SHA256 for hashes, ECDSA signatures on the secp256r1 curve, with no encryption. The manifest tool calls this encryption mode `none-ecc-secp256r1-sha256`. Future versions of the manifest tool will add support for payload encryption.
+Creates a public key file containing a key in uncompressed point format
+(X9.62). Provisioning this file to the device enables the device to
+verify the manifest signature.
-**Note:** The Update client currently only supports binary payloads, so the payload type is assumed to be binary.
+**Example**
-##### Mode none-ecc-secp256r1-sha256
-
-###### Minimum requirements for none-ecc-secp256r1-sha256
+```shell
+manifest-tool public-key my.priv.key.pem --out my.pub.key.bin
+```
-The minimum requirements for creating a manifest with unencrypted payload are:
+### manifest-delta-tool
-* The cryptographic mode to use (none-ecc-secp256r1-sha256, in this case).
-* The payload URI.
-* One of:
- * The URI of a certificate to be used for signing the manifest.
- * A local file that is a certificate to be used for signing the manifest.
-* A local file that is the signing key for that certificate.
-* One of:
- * The vendor ID and device class ID.
- * The device ID.
+Use this tool to generate delta patch files for delta updates.
-###### What mode none-ecc-secp256r1-sha256 does
+Run `manifest-delta-tool --help` for more information about usage and
+arguments.
-In this mode, the manifest tool creates and signs a manifest; the payload is unencrypted. The target device(s) must already have the provided certificate or must provide a way to fetch that certificate.
+**Prerequisites**
-The manifest tool:
+* The firmware currently installed on the device and the updated
+ firmware image. Required for calculating the delta patch.
-1. Fetches and hashes the payload. It loads the payload from a local file.
-1. Fetches and fingerprints the certificate (either from the provided URI or the local file).
-1. Creates the inner part of the manifest, containing:
- 1. The provided IDs.
- 1. The payload URI.
- 1. The payload size.
- 1. The payload hash.
-1. Hashes the inner part of the manifest.
-1. Uses the hash and the certificate private key to sign the inner part of the manifest.
-1. Wraps the inner part, hash, signature, certificate fingerprint and certificate URI in the outer part of the manifest.
+**Example**
-###### Using mode none-ecc-secp256r1-sha256
+```shell
+$ manifest-delta-tool -c current_fw.bin -n new_fw.bin -o delta-patch.bin
+```
-When you invoke the manifest tool to create a manifest with encryption mode `none-ecc-secp256r1-sha256`, the information below must be provided. The manifest tool can find most of the information in more than one way. You can provide every item in the input file. Alternative options are provided in parentheses.
+**Note 1:** Compression block size has a direct impact on the amount of memory required by the device receiving the update. The device requires twice the amount of RAM in runtime to decompress and apply the patch.
-* The type of hashing, signing and encryption to use (calculated from mandatory inputs if absent).
-* Vendor ID (extracted from defaults if absent).
-* Class ID (extracted from defaults if absent).
-* Payload URI (overridden by `-u`).
-* Payload File (overridden by `-p`).
-* Description (defaults to empty).
-* Certificate used for signing (extracted from defaults if absent).
+**Note 2:** Compression block must be aligned with network (COAP/HTTP) buffer size used for download. Misalignment in sizes may result in device failure to process the delta patch file.
-###### Example 1:
+### manifest-dev-tool
-Providing all fields by using the input file:
+`manifest-dev-tool` is a developer tool for running a simplified update
+campaign.
-```JSON
-{
- "encryptionMode" : "none-ecc-secp256r1-sha256",
- "vendorId" : "",
- "classId" : "",
- "payloadUri" : "http://path.to/payload.bin",
- "payloadFile" : "/path/to/payload.bin",
- "description" : "Description of the update",
- "certificates": [
- { "uri": "http://path.to/certificate.der" , "file" : "/path/to/certificate.der" }
- ]
-}
-```
+Use `manifest-dev-tool` for development flows only.
-To create a manifest with this information, call the manifest tool:
+`manifest-dev-tool` commands:
+- [`manifest-dev-tool init`](#manifest-dev-tool-init) - Initializes the
+ developer environment.
+- [`manifest-dev-tool create`](#manifest-dev-tool-create) - Simplified
+ tool for creating manifests.
+- [`manifest-dev-tool create-v1`](#manifest-dev-tool-create-v1) -
+ Simplified tool for creating manifests using the V1 schema.
+- [`manifest-dev-tool update`](#manifest-dev-tool-update) - Lets you
+ perform end-to-end tests without leaving the command shell.
+- [`manifest-dev-tool update-v1`](#manifest-dev-tool-update-v1) - Lets
+ you perform end-to-end tests without leaving the command shell using a
+ V1-schema manifest.
-```sh
-$ manifest-tool create -i input.json -o output.manifest -k certificate_key.pem
-```
+**Note:** Run `manifest-dev-tool --help` for more information about all commands, or `manifest-dev-tool --help` for more information about a specific command, including its parameters and how to use them.
-###### Example 2:
+#### `manifest-dev-tool init`
-Providing no input file. Run this command one time in the root of the project:
+Initializes the developer environment:
+* Creates an update private key and a public key certificate.
+* Generates a `fota_dev_resources.c` file with symbols that allow
+ bypassing the provisioning step in the developer flow.
+* Creates configuration files, which you use when you run the
+ [`manifest-dev-tool create`](#manifest-dev-tool-create) and
+ [`manifest-dev-tool update`](#manifest-dev-tool-update) commands.
-```sh
-$ manifest-tool init -d "" -m ""
-```
+**Note:** Only use the credentials the `manifest-dev-tool` tool generates in the development flow.
-Then, use this command to prepare an update:
+**Example**
-```sh
-$ manifest-tool create -u -p -o
+```shell
+manifest-dev-tool init --force -a [API key from Device Management Portal]
```
-#### Manifest creation input file
-
-If a `.manifest_tool.json` file is present in the current working directory when you run `manifest-tool create`, `manifest-tool update prepare` or `manifest-tool update device`, the manifest tool loads default values from this file. It overrides these values with the contents of the manifest creation input file. Then, it uses any command-line options to override the contents of the manifest creation input file. If you have used `manifest-tool init` to initialize the current working directory and you use `manifest-tool create -p -u `, then the input file is optional.
+#### `manifest-dev-tool create`
-This means that all fields in the manifest creation input file are optional. However, the `.manifest_tool.json` defaults file, the manifest creation input file or the command-line must specify some fields:
+Creates developer manifest files without requiring an input
+configuration file.
-1. `vendorId`.
-1. `classId`.
-1. `payloadUri`.
-1. `payloadFile` or `payloadHash`.
-1. `certificateFingerprint` or `certificateFile`.
-1. `privateKey`.
+**Example**
-The manifest creation input file follows the JSON representation of the [manifest format v1 specification]. Because there is a significant quantity of nesting in the input fields, there are short-hands for most fields.
+```shell
+manifest-dev-tool create \
+ --payload-url http://test.pdmc.arm.com?fileId=1256 \
+ --payload-path new_fw.bin \
+ --fw-version 1.2.3 \
+ --output update-manifest.bin
+```
-Several parts in a nested structure comprise the manifest creation input file:
+**Note:** To run a delta update, create the file specified in the `--payload-path` argument using the [`manifest-delta-tool`](#manifest-delta-tool) command. The file has the same name but a `.yaml` suffix (in the example, `new-fw.yaml` instead of `new-fw.bin`).
-1. Signed resource.
- 1. Manifest.
- 1. Encryption info.
- 1. Payload info.
- 1. Signature block.
+**Note:** Add the `--sign-image` argument to update a device with a secure bootloader, which requires an image signature.
-##### Signed resource
+#### `manifest-dev-tool create-v1`
-The signed resource is the top level object in the input file. Because of this, its name does not appear. It contains only two objects:
+Creates developer manifest files in v1 format without requiring an input
+configuration file.
-1. Manifest.
-1. Signature block.
+**Example**
-```JSON
-{
- "resource" : {
- "resource" : {
- "manifest" :
- }
- },
- "signature" :
-}
+```shell
+manifest-dev-tool create-v1 \
+ --payload-url http://test.pdmc.arm.com?fileId=1256 \
+ --payload-path new-fw.bin \
+ --output update-manifest.bin
```
-* `manifest`: See the [Manifest] section.
-* `signature`: See the [Signature block] section.
+**Note:** To run a delta update, create the file specified in the `--payload-path` argument using the [`manifest-delta-tool`](#manifest-delta-tool) command. The file has the same name but a `.yaml` suffix (in the example, `new-fw.yaml` instead of `new-fw.bin`).
-If you wish to use short-hand parameters, you must place them at this level, within the `SignedResource` object (the un-named top-level JSON object). For example, to use the shorthand for specifying a payload hash, add the `payloadHash` short-hand as below:
+#### `manifest-dev-tool update`
-```JSON
-{
- "resource" : {
- "resource" : {
- "manifest" :
- }
- },
- "payloadHash" : ,
- "signature" :
-}
-```
+Same as [`manifest-dev-tool create`](#manifest-dev-tool-create) but also
+lets you interact with Device Management Portal to run a full update
+campaign on a single device.
-The full list of short-hand parameters is available in [Short-hand parameters].
+The command:
-##### Manifest
+1. Uploads the payload to Device Management Portal and obtains the URL.
+2. Creates a manifest file with the URL from the previous step and
+ obtains a manifest URL.
+3. Creates an update campaign with the manifest URL from the previous
+ step.
+4. Starts the update campaign if you pass the `--start-campaign` or
+ `--wait-for-completion` argument.
+5. If you pass the `--wait-for-completion` argument, the tool waits for
+ campaign completion for the time period specified by `--timeout` or
+ until the campaign reaches one of its terminating states in Device
+ Management Portal (`expired`, `userstopped`, or
+ `quotaallocationfailed`).
+6. If you pass the `--wait-for-completion` argument without the
+ `--no-cleanup` flag, the tool removes the uploaded test resources
+ from Device Management Portal before exiting. When you terminate the
+ tool, the tool skips the cleanup step.
-The manifest object contains several fields and one subobject.
+**Note:** [`manifest-dev-tool init`](#manifest-dev-tool-init) creates the directory you specify in `--cache-dir`.
-```JSON
-{
- "payload": ,
- "description": "Description of the update",
- "vendorId": ,
- "classId": ,
- "precursorDigest" : ,
- "applyImmediately": true,
- "priority" : ,
- "encryptionMode": {
- "enum": "none-ecc-secp256r1-sha256"
- },
- "vendorInfo":
-}
-```
+**Example**
-* `payload`: See the [Payload] section.
-* `description`: A free-text description of the payload. This should be small.
-* `vendorId`: Hex representation of the 128-bit RFC4122 GUID that represents the vendor.
-* `classId`: Hex representation of the 128-bit RFC4122 GUID that represents the device class that the update targets. Device classes can mean devices of a given type (for example, smart lights) or model numbers. This allows targeting of updates to particular groups of devices based on the attributes they share, where a device class represents each set of attributes. Because of this, each device can have multiple device classes. Device Management Update client only supports the use of device classes to represent model numbers/revisions.
-* `precursorDigest` - You can use this field in delta updates to specify the image that must already be present on the device for the delta update to produce the correct result.
-* `precursorFile` - A path to a local copy of the precursor. The manifest tool uses this file to calculate the `precursorDigest`. This is not needed if you specify the precursor hash.
-* `applyImmediately`: This is always assumed to be true. Device Management Update client does not currently implement it.
-* `priority` - The importance of the update. You can use this integer field to tell your application how important an update is, so that it can decide whether to use it or not. The meanings of the values of `priority` are application-defined. 0 typically means "mandatory" and increasing values have lower priority.
-* `encryptionMode`: Update client only supports two values:
- * `none-ecc-secp256r1-sha256`: SHA256 hashing, ECDSA signatures, using the secp256r1 curve. This does not use payload encryption (Update client only).
- * `none-psk-aes-128-ccm-sha256`: SHA256 hashing, manifest digest is authenticated with AES-CCM-128. This does not use payload encryption (Update Client Lite only).
-* `vendorInfo`: You can place proprietary information in this field. We recommend DER encoding because this allows you to reuse the Update client's general purpose DER parser.
+ ```shell
+ manifest-dev-tool update \
+ --payload-path my_mew_fw.bin \
+ --fw-version 1.2.3 \
+ --wait-for-completion
+ ```
-##### Payload
+**Note:** The tool creates the device filter for the campaign based on the unique `class-id` and `vendor-id` fields the [`manifest-dev-tool init`](#manifest-dev-tool-init) command generates.
-The payload section describes the payload object.
+#### `manifest-dev-tool update-v1`
-```JSON
-{
- "storageIdentifier": ,
- "reference": {
- "hash": ,
- "size": ,
- "uri": "http://path.to/payload",
- "file":
- }
-}
-```
+Same as [`manifest-dev-tool update`](#manifest-dev-tool-update) with a
+v1-format manifest.
-* `storageIdentifier`: A number that the device recognizes for where to store the payload.
-* `hash`: The SHA256 hash of the payload.
-* `size`: The size of the payload.
-* `uri`: The URI from which the target devices should acquire the payload.
-* `file`: A path to a local copy of the payload. The manifest tool uses this file to calculate the payload hash and payload size. This is not needed if you specify the payload hash and size in the input file.
-* `installedDigest`: You can use this field with delta updates to specify the result of applying an update. The digest in `reference` specifies the digest of the downloaded object. For delta updates, a second digest is needed to ensure that the result of any processing applied to the resource results in the correct payload image.
-* `installedSize`: You can use this field in delta updates to specify the size of an image after the delta update processing is applied.
-* `installedFile`: You can use this field to specify a path to a local copy of the desired result of a delta update. The manifest tool uses this file to calculate the `installedDigest` and `installedFile`. This is not needed if you specify `installedDigest` and `installedFile` in the input file.
+**Example**
-##### Signature block
+ ```shell
+ manifest-dev-tool update-v1 \
+ --payload-path my_mew_fw.bin \
+ --wait-for-completion
+ ```
-Use the signature block to select the certificate the device should use to verify the signature of the manifest.
+### Developer workflow example
-```JSON
-{
- "signatures": [
- {
- "certificates": [
- {
- "uri": "",
- "fingerprint": "",
- "file": "/path/to/certificate.der"
- }
- ]
- }
- ]
-}
-```
+1. Clone the https://github.com/ARMmbed/mbed-cloud-client-example
+ repository.
+2. From within the repository, execute:
-* `certificates`: A list of URI/fingerprint pairs. The first certificate in the list must match the private key that you provied to the manifest tool to sign the manifest, supplied through the `-k` command-line option. Each certificate must sign the certificate before it in the list. The last certificate in the list should be the root of trust in the device and can have an empty URI. Instead of a `fingerprint`, you can provide a `file` and the manifest tool will calculate the fingerprint. Note that Device Management Update client does not provide a mechanism to fetch certificates in this list. Implementing this feature requires the developer to override `arm_uc_kcm_cert_fetcher`. By default, Device Management Update client expects to have one certificate and that this certificate must verify all manifests.
+ ```
+ manifest-dev-tool init --force -a $MY_API_KEY
+ ```
+ The tool generates and compiles a `fota_dev_resources.c` file.
-##### Short-hand parameters
+1. Flash the bootloader and firmware to the device.
+1. Create a firmware update candidate.
-* `encryptionMode`: Sets the `encryptionMode` in `manifest`.
-* `payloadFile`: Sets the `file` in `payload`.
-* `payloadUri`: Sets the `uri` in `payload`.
-* `payloadHash`: Sets the `hash` in `payload`.
-* `payloadSize`: Sets the `size` in `payload`.
-* `vendorInfo`: Sets the `vendorInfo` in `manifest`.
-* `vendorId`: Sets the `vendorId` in `manifest`.
-* `classId`: Sets the `classId` in `manifest`.
-* `description`: Sets the `description` in `manifest`
-* `certificates`: Sets the `certificates` in `signature`.
-* `installedSize` : Sets the `installedSize` in `payload`
-* `installedDigest` : Sets the `installedDigest` in `payload`
-* `installedFile` : Sets the `installedFile` in `payload`
-* `priority` : Sets the `priority` in `manifest`
-* `precursorDigest` : Sets the `precursorDigest` in `manifest`
-* `precursorFile` : Sets the `precursorFile` in `manifest`
+ OR
+ Create a delta-patch:
+ ```
+ manifest-delta-tool -c curr_fw.bin -n new_fw.bin -o delta.bin
+ ```
-You can also override many of these parameters on the command-line. See `manifest-tool create --help` for more information.
+1. Issue an update:
-#### Parsing manifests
+ ```
+ manifest-dev-tool update --payload-path
+ new_fw.bin --wait-for-completion
+ ```
+ For a delta update, the payload is `delta.bin`.
-##### Command-line
+## Troubleshooting
-To convert a manifest to JSON:
+* **Getting more context on unexpected errors.**
-```sh
-manifest-tool parse -i input.manifest
-```
+ When the tool exits with a non-zero return code, it may be helpful to
+ get more context on the failure.
-To make the JSON more readable, use the `-j` flag.
+ **Solution:** execute the tool with the `--debug` flag at the top
+ argument parser level. For example:
-```sh
-manifest-tool parse -ji input.manifest
-```
+ ```
+ manifest-dev-tool --debug update
+ ```
-##### Python library
+* **`manifest-dev-tool update ... --wait-for-completion` takes longer than expected.**
-To convert a manifest file to a Python dictionary:
+ `manifest-dev-tool update` creates a unique `class-id` and
+ `vendor-id` generated per developer. Device Management expects a
+ single device with these properties to connect to Device Management
+ Portal.
-```
-import manifesttool.parse
+ In rare cases, during development, a device's `device-id` might
+ change after you re-flash it. This may result in two devices having
+ the same `class-id` and `vendor-id` in Device Management Portal. In
+ this scenario, Device Management will detect both devices and try to
+ update them both, although one of them no longer exists
-manifest = open('test0.manifest', 'rb').read()
-parsed_manifest = manifesttool.parse.parseManifest(manifest)
-print(parsed_manifest)
-```
+ **Solution:** Manually delete the unwanted device from Device
+ Management Portal. Alternatively, run `manifest-dev-tool update ...
+ --wait-for-completion` with `--device-id DEVICE_ID` to override the
+ default campaign filter and target a specific device by its ID.
-### Development
+* **Update fails and `manifest-dev-tool update ...
+ --wait-for-completion` cleans all resources.**
-Install all required packages, and create a virtual environment:
+ You might want to leave the resources (firmware image candidate,
+ update manifest and update campaign) on a service for further
+ investigation/retry.
-```
-pip2 install virtualenv
-mkdir -p ~/virtualenvs
-virtualenv ~/virtualenvs/manifest-tool
-source ~/virtualenvs/manifest-tool/bin/activate
-```
+ **Solution:** Execute `manifest-dev-tool update ...
+ --wait-for-completion` with the `--no-cleanup` flag.
diff --git a/bsdiff/bsdiff.c b/bsdiff/bsdiff.c
new file mode 100755
index 0000000..adfbed9
--- /dev/null
+++ b/bsdiff/bsdiff.c
@@ -0,0 +1,497 @@
+/*-
+ * Copyright 2003-2005 Colin Percival
+ * Copyright 2012 Matthew Endsley
+ * Copyright (c) 2018-2019 ARM Limited
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted providing that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "bsdiff.h"
+#include "varint.h"
+#include
+#include
+#include
+#include
+
+#include "lz4.h"
+
+#define MIN(x,y) (((x)<(y)) ? (x) : (y))
+
+
+//#define TRACING
+#ifdef TRACING
+#define log(...) printf(__VA_ARGS__)
+#else
+#define log(...)
+#endif
+
+
+static void split(int64_t *I, int64_t *V, int64_t start, int64_t len, int64_t h)
+{
+ int64_t i, j, k, x, tmp, jj, kk;
+
+ if (len < 16) {
+ for (k = start; k < start + len; k += j) {
+ j = 1;
+ x = V[I[k] + h];
+ for (i = 1; k + i < start + len; i++) {
+ if (V[I[k + i] + h] < x) {
+ x = V[I[k + i] + h];
+ j = 0;
+ };
+ if (V[I[k + i] + h] == x) {
+ tmp = I[k + j];
+ I[k + j] = I[k + i];
+ I[k + i] = tmp;
+ j++;
+ };
+ };
+ for (i = 0; i < j; i++){
+ V[I[k + i]] = k + j - 1;
+ }
+ if (j == 1){
+ I[k] = -1;
+ }
+ };
+ return;
+ };
+
+ x = V[I[start + len / 2] + h];
+ jj = 0;
+ kk = 0;
+ for (i = start; i < start + len; i++) {
+ if (V[I[i] + h] < x){
+ jj++;
+ }
+ if (V[I[i] + h] == x){
+ kk++;
+ }
+ };
+ jj += start;
+ kk += jj;
+
+ i = start;
+ j = 0;
+ k = 0;
+ while (i < jj) {
+ if (V[I[i] + h] < x) {
+ i++;
+ } else if (V[I[i] + h] == x) {
+ tmp = I[i];
+ I[i] = I[jj + j];
+ I[jj + j] = tmp;
+ j++;
+ } else {
+ tmp = I[i];
+ I[i] = I[kk + k];
+ I[kk + k] = tmp;
+ k++;
+ };
+ };
+
+ while (jj + j < kk) {
+ if (V[I[jj + j] + h] == x) {
+ j++;
+ } else {
+ tmp = I[jj + j];
+ I[jj + j] = I[kk + k];
+ I[kk + k] = tmp;
+ k++;
+ };
+ };
+
+ if (jj > start){
+ split(I, V, start, jj - start, h);
+ }
+
+ for (i = 0; i < kk - jj; i++){
+ V[I[jj + i]] = kk - 1;
+ }
+ if (jj == kk - 1){
+ I[jj] = -1;
+ }
+
+ if (start + len > kk){
+ split(I, V, kk, start + len - kk, h);
+ }
+}
+
+static void qsufsort(int64_t *I, int64_t *V, const uint8_t *old, int64_t oldsize)
+{
+ int64_t buckets[256];
+ int64_t i, h, len;
+
+ for (i = 0; i < 256; i++)
+ buckets[i] = 0;
+ for (i = 0; i < oldsize; i++)
+ buckets[old[i]]++;
+ for (i = 1; i < 256; i++)
+ buckets[i] += buckets[i - 1];
+ for (i = 255; i > 0; i--)
+ buckets[i] = buckets[i - 1];
+ buckets[0] = 0;
+
+ for (i = 0; i < oldsize; i++)
+ I[++buckets[old[i]]] = i;
+ I[0] = oldsize;
+ for (i = 0; i < oldsize; i++)
+ V[i] = buckets[old[i]];
+ V[oldsize] = 0;
+ for (i = 1; i < 256; i++)
+ if (buckets[i] == buckets[i - 1] + 1)
+ I[buckets[i]] = -1;
+ I[0] = -1;
+
+ for (h = 1; I[0] != -(oldsize + 1); h += h) {
+ len = 0;
+ for (i = 0; i < oldsize + 1;) {
+ if (I[i] < 0) {
+ len -= I[i];
+ i -= I[i];
+ } else {
+ if (len)
+ I[i - len] = -len;
+ len = V[I[i]] + 1 - i;
+ split(I, V, i, len, h);
+ i += len;
+ len = 0;
+ };
+ };
+ if (len)
+ I[i - len] = -len;
+ };
+
+ for (i = 0; i < oldsize + 1; i++)
+ I[V[i]] = i;
+}
+
+static int64_t matchlen(const uint8_t *old, int64_t oldsize, const uint8_t *new, int64_t newsize)
+{
+ int64_t i;
+
+ for (i = 0; (i < oldsize) && (i < newsize); i++)
+ if (old[i] != new[i])
+ break;
+
+ return i;
+}
+
+static int64_t search(const int64_t *I, const uint8_t *old, int64_t oldsize, const uint8_t *new, int64_t newsize,
+ int64_t st, int64_t en, int64_t *pos)
+{
+ int64_t x, y;
+
+ if (en - st < 2) {
+ x = matchlen(old + I[st], oldsize - I[st], new, newsize);
+ y = matchlen(old + I[en], oldsize - I[en], new, newsize);
+
+ if (x > y) {
+ *pos = I[st];
+ return x;
+ } else {
+ *pos = I[en];
+ return y;
+ }
+ };
+
+ x = st + (en - st) / 2;
+ if (memcmp(old + I[x], new, MIN(oldsize - I[x], newsize)) < 0) {
+ return search(I, old, oldsize, new, newsize, x, en, pos);
+ } else {
+ return search(I, old, oldsize, new, newsize, st, x, pos);
+ };
+}
+
+void offtout(int64_t x, uint8_t *buf)
+{
+ int64_t y;
+
+ if (x < 0)
+ y = -x;
+ else
+ y = x;
+
+ buf[0] = y % 256;
+ y -= buf[0];
+ y = y / 256;
+ buf[1] = y % 256;
+ y -= buf[1];
+ y = y / 256;
+ buf[2] = y % 256;
+ y -= buf[2];
+ y = y / 256;
+ buf[3] = y % 256;
+ y -= buf[3];
+ y = y / 256;
+ buf[4] = y % 256;
+ y -= buf[4];
+ y = y / 256;
+ buf[5] = y % 256;
+ y -= buf[5];
+ y = y / 256;
+ buf[6] = y % 256;
+ y -= buf[6];
+ y = y / 256;
+ buf[7] = y % 256;
+
+ if (x < 0)
+ buf[7] |= 0x80;
+}
+
+/**
+ * Write given buffer to stream in frames, with MAX_FRAME_SIZE as maximum deCompressBuffer and undeCompressBuffer size.
+ * Store the biggest deCompressBuffer frame size to max_deCompressBuffer_size, if it's bigger than current value.
+ * @return 0 on success, negative on error.
+ */
+static int writedeCompressBuffer(struct bsdiff_stream* stream, const void* buffer, int64_t length,
+ int64_t* max_deCompressBuffer_size, int64_t max_frame_size)
+{
+ int src_ptr;
+ char* temp;
+ int deCompressBuffer_size;
+ int written = 0;
+ uint8_t buf[8];
+
+ if (length == 0)
+ return 0;
+
+ temp = stream->malloc(max_frame_size);
+ src_ptr = (int)(MIN(length, max_frame_size));
+
+ do {
+ deCompressBuffer_size = LZ4_compress_destSize(buffer, temp, &src_ptr, (int)(max_frame_size));
+
+ if (deCompressBuffer_size == 0) {
+ stream->free(temp);
+ return -1;
+ }
+
+ int encodedSize = encode_unsigned_varint(deCompressBuffer_size, buf, sizeof(buf));
+
+ log("writedeCompressBuffer %llu compressedSize %u (var intS %u)\n", length, deCompressBuffer_size, encodedSize);
+ if (encodedSize <= 0) {
+ return encodedSize; // error in encoding
+ }
+ stream->write(stream, buf, encodedSize);
+
+ stream->write(stream, temp, deCompressBuffer_size);
+
+ buffer = (char*) buffer + src_ptr;
+ written += src_ptr;
+
+ src_ptr = (int)(MIN(length - written, max_frame_size));
+
+ if (deCompressBuffer_size > *max_deCompressBuffer_size){
+ *max_deCompressBuffer_size = deCompressBuffer_size;
+ }
+
+ } while (written != length);
+
+ stream->free(temp);
+ return 0;
+}
+
+struct bsdiff_request {
+ const uint8_t* old;
+ int64_t oldsize;
+ const uint8_t* new;
+ int64_t newsize;
+ struct bsdiff_stream* stream;
+ int64_t *I;
+ uint8_t *buffer;
+};
+
+static int bsdiff_internal(const struct bsdiff_request req, int64_t* max_deCompressBuffer_size,
+ const int64_t max_frame_size)
+{
+ int64_t *I, *V;
+ int64_t scan, pos, len;
+ int64_t lastscan, lastpos, lastoffset;
+ int64_t oldscore, scsc;
+ int64_t s, Sf, lenf, Sb, lenb;
+ int64_t overlap, Ss, lens;
+ int64_t i;
+ uint8_t *buffer;
+ uint8_t buf[8 * 3];
+
+ if ((V = req.stream->malloc((req.oldsize + 1) * sizeof(int64_t))) == NULL){
+ return -1;
+ }
+ I = req.I;
+
+ qsufsort(I, V, req.old, req.oldsize);
+ req.stream->free(V);
+
+ buffer = req.buffer;
+
+ /* Compute the differences, writing ctrl as we go */
+ scan = 0;
+ len = 0;
+ pos = 0;
+ lastscan = 0;
+ lastpos = 0;
+ lastoffset = 0;
+ while (scan < req.newsize) {
+ oldscore = 0;
+
+ for (scsc = scan += len; scan < req.newsize; scan++) {
+ len = search(I, req.old, req.oldsize, req.new + scan, req.newsize - scan, 0, req.oldsize, &pos);
+
+ for (; scsc < scan + len; scsc++)
+ if ((scsc + lastoffset < req.oldsize) && (req.old[scsc + lastoffset] == req.new[scsc]))
+ oldscore++;
+
+ if (((len == oldscore) && (len != 0)) || (len > oldscore + 8))
+ break;
+
+ if ((scan + lastoffset < req.oldsize) && (req.old[scan + lastoffset] == req.new[scan]))
+ oldscore--;
+ };
+
+ if ((len != oldscore) || (scan == req.newsize)) {
+ s = 0;
+ Sf = 0;
+ lenf = 0;
+ for (i = 0; (lastscan + i < scan) && (lastpos + i < req.oldsize);) {
+ if (req.old[lastpos + i] == req.new[lastscan + i])
+ s++;
+ i++;
+ if (s * 2 - i > Sf * 2 - lenf) {
+ Sf = s;
+ lenf = i;
+ };
+ };
+
+ lenb = 0;
+ if (scan < req.newsize) {
+ s = 0;
+ Sb = 0;
+ for (i = 1; (scan >= lastscan + i) && (pos >= i); i++) {
+ if (req.old[pos - i] == req.new[scan - i])
+ s++;
+ if (s * 2 - i > Sb * 2 - lenb) {
+ Sb = s;
+ lenb = i;
+ };
+ };
+ };
+
+ if (lastscan + lenf > scan - lenb) {
+ overlap = (lastscan + lenf) - (scan - lenb);
+ s = 0;
+ Ss = 0;
+ lens = 0;
+ for (i = 0; i < overlap; i++) {
+ if (req.new[lastscan + lenf - overlap + i] == req.old[lastpos + lenf - overlap + i])
+ s++;
+ if (req.new[scan - lenb + i] == req.old[pos - lenb + i])
+ s--;
+ if (s > Ss) {
+ Ss = s;
+ lens = i + 1;
+ };
+ };
+
+ lenf += lens - overlap;
+ lenb -= lens;
+ };
+
+ int64_t diff_str_len = lenf;
+ int64_t extra_str_len_y = (scan - lenb) - (lastscan + lenf);
+ int64_t old_file_ctrl_off_set_jump = (pos - lenb) - (lastpos + lenf);
+
+ int posInBuf = 0;
+ int encodedSize = encode_unsigned_varint(diff_str_len, &buf[posInBuf], 8);
+
+ assert(encodedSize > 0 && encodedSize <= 8);
+ posInBuf += encodedSize;
+
+ encodedSize = encode_unsigned_varint(extra_str_len_y, &buf[posInBuf], 8);
+ assert(encodedSize > 0 && encodedSize <= 8);
+ posInBuf += encodedSize;
+
+ encodedSize = encode_signed_varint(old_file_ctrl_off_set_jump, &buf[posInBuf], 8);
+ assert(encodedSize > 0 && encodedSize <= 8);
+ posInBuf += encodedSize;
+
+ log( "DIFF_STR_LEN_X: %lld EXTRA_STR_LEN_Y: %lld OLD_FILE_CTRL_OFF_SET_JUMP %lld (encoded to %i)\n",
+ lenf, (scan - lenb) - (lastscan + lenf), (pos - lenb) - (lastpos + lenf), posInBuf);
+
+ /* Write control data */
+ req.stream->write(req.stream, buf, posInBuf);
+
+ /* Write diff data */
+ for (i = 0; i < lenf; i++){
+ buffer[i] = req.new[lastscan + i] - req.old[lastpos + i];
+ }
+ if (writedeCompressBuffer(req.stream, buffer, lenf, max_deCompressBuffer_size, max_frame_size)) {
+ return -1;
+ }
+
+ /* Write extra data */
+ for (i = 0; i < (scan - lenb) - (lastscan + lenf); i++){
+ buffer[i] = req.new[lastscan + lenf + i];
+ }
+ if (writedeCompressBuffer(req.stream, buffer, (scan - lenb) - (lastscan + lenf), max_deCompressBuffer_size,
+ max_frame_size)) {
+ return -1;
+ }
+
+ lastscan = scan - lenb;
+ lastpos = pos - lenb;
+ lastoffset = pos - scan;
+ };
+ };
+
+ return 0;
+}
+
+int bsdiff(const uint8_t* old, int64_t oldsize, const uint8_t* new, int64_t newsize, struct bsdiff_stream* stream,
+ int64_t* max_deCompressBuffer_size, const int64_t max_frame_size)
+{
+ int result;
+ struct bsdiff_request req;
+
+ if ((req.I = stream->malloc((oldsize + 1) * sizeof(int64_t))) == NULL) {
+ return -1;
+ }
+
+ if ((req.buffer = stream->malloc(newsize + 1)) == NULL) {
+ stream->free(req.I);
+ return -1;
+ }
+
+ req.old = old;
+ req.oldsize = oldsize;
+ req.new = new;
+ req.newsize = newsize;
+ req.stream = stream;
+
+ result = bsdiff_internal(req, max_deCompressBuffer_size, max_frame_size);
+
+ stream->free(req.buffer);
+ stream->free(req.I);
+
+ return result;
+}
+
diff --git a/bsdiff/bsdiff.h b/bsdiff/bsdiff.h
new file mode 100755
index 0000000..e5d0723
--- /dev/null
+++ b/bsdiff/bsdiff.h
@@ -0,0 +1,51 @@
+/*-
+ * Copyright 2003-2005 Colin Percival
+ * Copyright 2012 Matthew Endsley
+ * Copyright (c) 2018-2019 ARM Limited
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted providing that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef BSDIFF_H
+#define BSDIFF_H
+
+# include
+# include
+
+struct bsdiff_stream {
+ void* opaque;
+ void* (*malloc)(size_t size);
+ void (*free)(void* ptr);
+ int (*write)(struct bsdiff_stream* stream, const void* buffer,
+ uint64_t size);
+};
+
+int bsdiff(
+ const uint8_t* old, int64_t oldsize,
+ const uint8_t* new, int64_t newsize,
+ struct bsdiff_stream* stream,
+ int64_t* max_deCompressBuffer_size,
+ const int64_t max_frame_size
+);
+
+#endif
diff --git a/bsdiff/bsdiff_helper.c b/bsdiff/bsdiff_helper.c
new file mode 100644
index 0000000..40be4e1
--- /dev/null
+++ b/bsdiff/bsdiff_helper.c
@@ -0,0 +1,189 @@
+// ----------------------------------------------------------------------------
+// Copyright 2019 ARM Ltd.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// ----------------------------------------------------------------------------
+#include "common.h"
+#include "bsdiff.h"
+#include "bsdiff_helper.h"
+#include
+#include
+#include
+#include
+
+//#ifdef __unix
+//#if defined(__gnuc__)
+#if !defined(__CYGWIN__) && !defined(_WIN32)
+#define fopen_s(pFile, filename, mode) ((*(pFile)) = fopen((filename), (mode))) == NULL
+#endif
+
+#define ERR(msg) do { \
+ deliver_error(msg); \
+ status = -1; \
+ goto end; \
+ } while(0)
+
+void offtout(int64_t x, uint8_t *buf);
+
+static int file_write(struct bsdiff_stream* stream, const void* buffer,
+ uint64_t size) {
+ return fwrite(buffer, sizeof(uint8_t), size, (FILE*) stream->opaque) == size ? 0 : -1;
+}
+
+
+int do_diff(
+ const char* old_fw_img,
+ const char* new_fw_img,
+ const char* delta_file,
+ int64_t max_frame_size
+)
+{
+ int status = 0;
+ uint8_t *old_data = NULL;
+ uint8_t *new_data = NULL;
+ size_t old_size = 0;
+ size_t new_size = 0;
+ uint8_t buf[24] = {0};
+ FILE *delta_fp = NULL;
+ FILE *old_fp = NULL;
+ FILE *new_fp = NULL;
+
+ int64_t max_deCompressBuffer_size = 0;
+ int64_t patch_file_size = 0;
+
+ /* --------------- Load old FW -------------------------------------------*/
+ {
+ if (fopen_s(&old_fp, old_fw_img, "rb")){
+ ERR("Failed to open old FW image");
+ }
+
+ fseek(old_fp, 0L, SEEK_END);
+ old_size = ftell(old_fp);
+ if (0 >= old_size) {
+ ERR("Malformed old FW image");
+ }
+ fseek(old_fp, 0L, SEEK_SET);
+
+ /* Allocate oldsize+1 bytes instead of oldsize bytes to ensure
+ that we never try to malloc(0) and get a NULL pointer */
+ old_data = malloc(old_size + 1);
+ if (NULL == old_data){
+ ERR("Failed to allocate memory for old FW image");
+ }
+
+ if (1 != fread(old_data, old_size, 1, old_fp)) {
+ ERR("Failed to read old FW image");
+ }
+
+ }
+ /* -------------- Load new FW --------------------------------------------*/
+ {
+ if (fopen_s(&new_fp, new_fw_img, "rb")){
+ ERR("Failed to open new FW image");
+ }
+
+ fseek(new_fp, 0L, SEEK_END);
+ new_size = ftell(new_fp);
+ if (0 >= new_size) {
+ ERR("Malformed new FW image");
+ }
+ fseek(new_fp, 0L, SEEK_SET);
+
+ /* Allocate newsize+1 bytes instead of newsize bytes to ensure
+ that we never try to malloc(0) and get a NULL pointer */
+ new_data = malloc(new_size + 1);
+ if (NULL == new_data){
+ ERR("Failed to allocate memory for new FW image");
+ }
+
+ if (1 != fread(new_data, new_size, 1, new_fp)) {
+ ERR("Failed to read new FW image");
+ }
+
+ }
+
+ /* ------------------- Create the patch file -----------------------------*/
+ if (fopen_s(&delta_fp, delta_file, "wb")) {
+ ERR("Failed to create delta file");
+ }
+
+ /* Write header (signature+newsize+max undeCompressBuffer+maxdeCompressBuffer)*/
+ offtout(new_size, buf);
+ offtout(max_frame_size, buf + 8);
+ offtout(max_deCompressBuffer_size, buf + 16);
+ if (
+ (1 != fwrite(FILE_MAGIC, FILE_MAGIC_LEN, 1, delta_fp)) ||
+ (1 != fwrite(buf, sizeof(buf), 1, delta_fp))
+ ) {
+ ERR("Failed to write header");
+ }
+
+ struct bsdiff_stream stream = {
+ .malloc = malloc,
+ .free = free,
+ .write = file_write,
+ .opaque = delta_fp
+
+ };
+ if (bsdiff(old_data, old_size, new_data, new_size, &stream, &max_deCompressBuffer_size,
+ max_frame_size)) {
+ ERR("bsdiff failed");
+ }
+
+ /* Go back to header and fill the maxdeCompressBuffer properly */
+ offtout(max_deCompressBuffer_size, buf);
+ fseek(delta_fp, 32, SEEK_SET);
+ if (fwrite(buf, 1, 8, delta_fp) != 8) {
+ ERR("Failed to write maxdeCompressBuffer");
+ }
+
+ fseek(delta_fp, 0, SEEK_END);
+ patch_file_size = ftell(delta_fp);
+
+end:
+ if (0 == status){
+ printf(
+ "Wrote diff file %s, size %lld. Max undeCompressBuffer frame size was %lld, max deCompressBuffer frame size was %lld.\n",
+ delta_file, patch_file_size, max_frame_size,
+ max_deCompressBuffer_size
+ );
+ }
+
+ if (old_fp){
+ fclose(old_fp);
+ }
+
+ if (new_fp){
+ fclose(new_fp);
+ }
+
+ if (delta_fp){
+ fclose(delta_fp);
+ }
+
+ if(old_data){
+ free(old_data);
+ }
+ if (new_data){
+ free(new_data);
+ }
+
+ return status;
+}
+
+const char *bsdiff_get_version(void)
+{
+ return FILE_MAGIC;
+}
diff --git a/bsdiff/bsdiff_helper.h b/bsdiff/bsdiff_helper.h
new file mode 100644
index 0000000..6425d86
--- /dev/null
+++ b/bsdiff/bsdiff_helper.h
@@ -0,0 +1,36 @@
+// ----------------------------------------------------------------------------
+// Copyright 2019 ARM Ltd.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// ----------------------------------------------------------------------------
+
+#ifndef DELTA_TOOL_INTERNAL_BSDIFF_BSDIFF_HELPER_H_
+#define DELTA_TOOL_INTERNAL_BSDIFF_BSDIFF_HELPER_H_
+
+void deliver_error(const char *msg);
+
+int do_diff(
+ const char* old_fw_img,
+ const char* new_fw_img,
+ const char* delta_file,
+ int64_t max_frame_size
+);
+
+
+const char *bsdiff_get_version(void);
+
+
+
+#endif /* DELTA_TOOL_INTERNAL_BSDIFF_BSDIFF_HELPER_H_ */
diff --git a/bsdiff/bsdiff_python.c b/bsdiff/bsdiff_python.c
new file mode 100644
index 0000000..21aaefb
--- /dev/null
+++ b/bsdiff/bsdiff_python.c
@@ -0,0 +1,90 @@
+// ----------------------------------------------------------------------------
+// Copyright 2019 ARM Ltd.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// ----------------------------------------------------------------------------
+
+#include
+
+#include "common.h"
+#include "bsdiff.h"
+#include "bsdiff_helper.h"
+
+#define MODULE_NAME "armbsdiff"
+
+void deliver_error(const char *msg){
+ PyErr_SetString(PyExc_RuntimeError, msg);
+}
+
+static PyObject *armbsdiff_get_version(PyObject *self, PyObject *args) {
+ const char *version = bsdiff_get_version();
+
+ return Py_BuildValue("s", version);
+}
+
+
+static PyObject *armbsdiff_generate(PyObject *self, PyObject *args) {
+ const char* old_fw_img = NULL;
+ const char* new_fw_img = NULL;
+ const char* delta_file = NULL;
+ int64_t max_frame_size = 0;
+
+ if (!PyArg_ParseTuple(args, "sssL", &old_fw_img, &new_fw_img, &delta_file, &max_frame_size)) {
+ return NULL;
+ }
+
+ int status = do_diff(old_fw_img, new_fw_img, delta_file, max_frame_size);
+ if (0 != status) {
+ return NULL; // flag an error
+ }
+ Py_RETURN_NONE;
+}
+
+
+// Method definition object for this extension
+static PyMethodDef armbsdiff_methods[] = {
+ { "get_version", (PyCFunction)armbsdiff_get_version, METH_NOARGS, "Get bsdiff version" },
+ { "generate", (PyCFunction)armbsdiff_generate, METH_VARARGS, "Generate delta patch" },
+ { NULL, NULL, 0, NULL }
+};
+
+#if PY_MAJOR_VERSION >= 3
+
+static struct PyModuleDef moduledef = {
+ PyModuleDef_HEAD_INIT,
+ MODULE_NAME,
+ NULL,
+ 0,
+ armbsdiff_methods,
+};
+
+PyMODINIT_FUNC PyInit_armbsdiff(void)
+{
+ PyObject *module = PyModule_Create(&moduledef);
+ return module;
+}
+
+
+
+#else
+
+PyMODINIT_FUNC initarmbsdiff(void)
+{
+ Py_InitModule(MODULE_NAME, armbsdiff_methods);
+ return;
+}
+
+#endif //PY_MAJOR_VERSION >= 3
+
diff --git a/bsdiff/common.h b/bsdiff/common.h
new file mode 100644
index 0000000..aa3b012
--- /dev/null
+++ b/bsdiff/common.h
@@ -0,0 +1,27 @@
+// ----------------------------------------------------------------------------
+// Copyright 2019 ARM Ltd.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// ----------------------------------------------------------------------------
+
+#ifndef DELTA_TOOL_INTERNAL_INCLUDE_COMMON_H_
+#define DELTA_TOOL_INTERNAL_INCLUDE_COMMON_H_
+
+#define FILE_MAGIC "PELION/BSDIFF001" // BSDIFF version
+#define FILE_MAGIC_LEN (sizeof(FILE_MAGIC) - 1) // without the null termination
+
+#define MAX_FRAME_SIZE_DEFAULT 512
+
+#endif /* DELTA_TOOL_INTERNAL_INCLUDE_COMMON_H_ */
diff --git a/bsdiff/import.sh b/bsdiff/import.sh
new file mode 100755
index 0000000..48a44b3
--- /dev/null
+++ b/bsdiff/import.sh
@@ -0,0 +1,41 @@
+#!/bin/bash -e
+# ----------------------------------------------------------------------------
+# Copyright 2019 ARM Limited or its affiliates
+#
+# SPDX-License-Identifier: Apache-2.0
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ----------------------------------------------------------------------------
+
+
+DELTA_TOOL_DIR=${1:?"missing delta-tool directory path"}
+SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
+
+declare -a BSDIFF_FILES=(
+ "$DELTA_TOOL_DIR/bsdiff/bsdiff.c"
+ "$DELTA_TOOL_DIR/bsdiff/bsdiff.h"
+ "$DELTA_TOOL_DIR/bsdiff/bsdiff_helper.c"
+ "$DELTA_TOOL_DIR/bsdiff/bsdiff_helper.h"
+ "$DELTA_TOOL_DIR/bsdiff/common.h"
+ "$DELTA_TOOL_DIR/bsdiff/lz4.c"
+ "$DELTA_TOOL_DIR/bsdiff/lz4.h"
+ "$DELTA_TOOL_DIR/bsdiff/varint.c"
+ "$DELTA_TOOL_DIR/bsdiff/varint.h"
+)
+
+for file in "${BSDIFF_FILES[@]}"
+do
+ cp -v $file $SCRIPT_DIR
+done
+
+echo "Imported from delta-tool at hash: $(git -C $DELTA_TOOL_DIR rev-parse HEAD)" > $SCRIPT_DIR/import_ref.txt
\ No newline at end of file
diff --git a/bsdiff/import_ref.txt b/bsdiff/import_ref.txt
new file mode 100644
index 0000000..721ae19
--- /dev/null
+++ b/bsdiff/import_ref.txt
@@ -0,0 +1 @@
+Imported from delta-tool at hash: f2029f7867d37023cbf6dc5957c73b669d68a2a4
diff --git a/bsdiff/lz4.c b/bsdiff/lz4.c
new file mode 100755
index 0000000..a299a72
--- /dev/null
+++ b/bsdiff/lz4.c
@@ -0,0 +1,1972 @@
+/*
+ LZ4 - Fast LZ compression algorithm
+ Copyright (C) 2011-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ You can contact the author at :
+ - LZ4 homepage : http://www.lz4.org
+ - LZ4 source repository : https://github.com/lz4/lz4
+*/
+
+
+/*-************************************
+* Tuning parameters
+**************************************/
+/*
+ * LZ4_HEAPMODE :
+ * Select how default compression functions will allocate memory for their hash table,
+ * in memory stack (0:default, fastest), or in memory heap (1:requires malloc()).
+ */
+#ifndef LZ4_HEAPMODE
+# define LZ4_HEAPMODE 0
+#endif
+
+/*
+ * ACCELERATION_DEFAULT :
+ * Select "acceleration" for LZ4_compress_fast() when parameter value <= 0
+ */
+#define ACCELERATION_DEFAULT 1
+
+
+/*-************************************
+* CPU Feature Detection
+**************************************/
+/* LZ4_FORCE_MEMORY_ACCESS
+ * By default, access to unaligned memory is controlled by `memcpy()`, which is safe and portable.
+ * Unfortunately, on some target/compiler combinations, the generated assembly is sub-optimal.
+ * The below switch allow to select different access method for improved performance.
+ * Method 0 (default) : use `memcpy()`. Safe and portable.
+ * Method 1 : `__packed` statement. It depends on compiler extension (ie, not portable).
+ * This method is safe if your compiler supports it, and *generally* as fast or faster than `memcpy`.
+ * Method 2 : direct access. This method is portable but violate C standard.
+ * It can generate buggy code on targets which assembly generation depends on alignment.
+ * But in some circumstances, it's the only known way to get the most performance (ie GCC + ARMv6)
+ * See https://fastcompression.blogspot.fr/2015/08/accessing-unaligned-memory.html for details.
+ * Prefer these methods in priority order (0 > 1 > 2)
+ */
+#ifndef LZ4_FORCE_MEMORY_ACCESS /* can be defined externally */
+# if defined(__GNUC__) && \
+ ( defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || defined(__ARM_ARCH_6K__) \
+ || defined(__ARM_ARCH_6Z__) || defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__) )
+# define LZ4_FORCE_MEMORY_ACCESS 2
+# elif (defined(__INTEL_COMPILER) && !defined(_WIN32)) || defined(__GNUC__)
+# define LZ4_FORCE_MEMORY_ACCESS 1
+# endif
+#endif
+
+/*
+ * LZ4_FORCE_SW_BITCOUNT
+ * Define this parameter if your target system or compiler does not support hardware bit count
+ */
+#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for WinCE doesn't support Hardware bit count */
+# define LZ4_FORCE_SW_BITCOUNT
+#endif
+
+
+
+/*-************************************
+* Dependency
+**************************************/
+#define LZ4_STATIC_LINKING_ONLY
+#define LZ4_DISABLE_DEPRECATE_WARNINGS /* due to LZ4_decompress_safe_withPrefix64k */
+#include "lz4.h"
+/* see also "memory routines" below */
+
+
+/*-************************************
+* Compiler Options
+**************************************/
+#ifdef _MSC_VER /* Visual Studio */
+# include
+# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */
+# pragma warning(disable : 4293) /* disable: C4293: too large shift (32-bits) */
+#endif /* _MSC_VER */
+
+#ifndef LZ4_FORCE_INLINE
+# ifdef _MSC_VER /* Visual Studio */
+# define LZ4_FORCE_INLINE static __forceinline
+# else
+# if defined (__cplusplus) || defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 */
+# ifdef __GNUC__
+# define LZ4_FORCE_INLINE static inline __attribute__((always_inline))
+# else
+# define LZ4_FORCE_INLINE static inline
+# endif
+# else
+# define LZ4_FORCE_INLINE static
+# endif /* __STDC_VERSION__ */
+# endif /* _MSC_VER */
+#endif /* LZ4_FORCE_INLINE */
+
+/* LZ4_FORCE_O2_GCC_PPC64LE and LZ4_FORCE_O2_INLINE_GCC_PPC64LE
+ * Gcc on ppc64le generates an unrolled SIMDized loop for LZ4_wildCopy,
+ * together with a simple 8-byte copy loop as a fall-back path.
+ * However, this optimization hurts the decompression speed by >30%,
+ * because the execution does not go to the optimized loop
+ * for typical compressible data, and all of the preamble checks
+ * before going to the fall-back path become useless overhead.
+ * This optimization happens only with the -O3 flag, and -O2 generates
+ * a simple 8-byte copy loop.
+ * With gcc on ppc64le, all of the LZ4_decompress_* and LZ4_wildCopy
+ * functions are annotated with __attribute__((optimize("O2"))),
+ * and also LZ4_wildCopy is forcibly inlined, so that the O2 attribute
+ * of LZ4_wildCopy does not affect the compression speed.
+ */
+#if defined(__PPC64__) && defined(__LITTLE_ENDIAN__) && defined(__GNUC__)
+# define LZ4_FORCE_O2_GCC_PPC64LE __attribute__((optimize("O2")))
+# define LZ4_FORCE_O2_INLINE_GCC_PPC64LE __attribute__((optimize("O2"))) LZ4_FORCE_INLINE
+#else
+# define LZ4_FORCE_O2_GCC_PPC64LE
+# define LZ4_FORCE_O2_INLINE_GCC_PPC64LE static
+#endif
+
+#if (defined(__GNUC__) && (__GNUC__ >= 3)) || (defined(__INTEL_COMPILER) && (__INTEL_COMPILER >= 800)) || defined(__clang__)
+# define expect(expr,value) (__builtin_expect ((expr),(value)) )
+#else
+# define expect(expr,value) (expr)
+#endif
+
+#ifndef likely
+#define likely(expr) expect((expr) != 0, 1)
+#endif
+#ifndef unlikely
+#define unlikely(expr) expect((expr) != 0, 0)
+#endif
+
+
+/*-************************************
+* Memory routines
+**************************************/
+#include /* malloc, calloc, free */
+#define ALLOC(s) malloc(s)
+#define ALLOC_AND_ZERO(s) calloc(1,s)
+#define FREEMEM(p) free(p)
+#include /* memset, memcpy */
+#define MEM_INIT(p,v,s) memset((p),(v),(s))
+
+
+/*-************************************
+* Basic Types
+**************************************/
+#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
+# include
+ typedef uint8_t BYTE;
+ typedef uint16_t U16;
+ typedef uint32_t U32;
+ typedef int32_t S32;
+ typedef uint64_t U64;
+ typedef uintptr_t uptrval;
+#else
+ typedef unsigned char BYTE;
+ typedef unsigned short U16;
+ typedef unsigned int U32;
+ typedef signed int S32;
+ typedef unsigned long long U64;
+ typedef size_t uptrval; /* generally true, except OpenVMS-64 */
+#endif
+
+#if defined(__x86_64__)
+ typedef U64 reg_t; /* 64-bits in x32 mode */
+#else
+ typedef size_t reg_t; /* 32-bits in x32 mode */
+#endif
+
+/*-************************************
+* Reading and writing into memory
+**************************************/
+static unsigned LZ4_isLittleEndian(void)
+{
+ const union { U32 u; BYTE c[4]; } one = { 1 }; /* don't use static : performance detrimental */
+ return one.c[0];
+}
+
+
+#if defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==2)
+/* lie to the compiler about data alignment; use with caution */
+
+static U16 LZ4_read16(const void* memPtr) { return *(const U16*) memPtr; }
+static U32 LZ4_read32(const void* memPtr) { return *(const U32*) memPtr; }
+static reg_t LZ4_read_ARCH(const void* memPtr) { return *(const reg_t*) memPtr; }
+
+static void LZ4_write16(void* memPtr, U16 value) { *(U16*)memPtr = value; }
+static void LZ4_write32(void* memPtr, U32 value) { *(U32*)memPtr = value; }
+
+#elif defined(LZ4_FORCE_MEMORY_ACCESS) && (LZ4_FORCE_MEMORY_ACCESS==1)
+
+/* __pack instructions are safer, but compiler specific, hence potentially problematic for some compilers */
+/* currently only defined for gcc and icc */
+typedef union { U16 u16; U32 u32; reg_t uArch; } __attribute__((packed)) unalign;
+
+static U16 LZ4_read16(const void* ptr) { return ((const unalign*)ptr)->u16; }
+static U32 LZ4_read32(const void* ptr) { return ((const unalign*)ptr)->u32; }
+static reg_t LZ4_read_ARCH(const void* ptr) { return ((const unalign*)ptr)->uArch; }
+
+static void LZ4_write16(void* memPtr, U16 value) { ((unalign*)memPtr)->u16 = value; }
+static void LZ4_write32(void* memPtr, U32 value) { ((unalign*)memPtr)->u32 = value; }
+
+#else /* safe and portable access through memcpy() */
+
+static U16 LZ4_read16(const void* memPtr)
+{
+ U16 val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+static U32 LZ4_read32(const void* memPtr)
+{
+ U32 val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+static reg_t LZ4_read_ARCH(const void* memPtr)
+{
+ reg_t val; memcpy(&val, memPtr, sizeof(val)); return val;
+}
+
+static void LZ4_write16(void* memPtr, U16 value)
+{
+ memcpy(memPtr, &value, sizeof(value));
+}
+
+static void LZ4_write32(void* memPtr, U32 value)
+{
+ memcpy(memPtr, &value, sizeof(value));
+}
+
+#endif /* LZ4_FORCE_MEMORY_ACCESS */
+
+
+static U16 LZ4_readLE16(const void* memPtr)
+{
+ if (LZ4_isLittleEndian()) {
+ return LZ4_read16(memPtr);
+ } else {
+ const BYTE* p = (const BYTE*)memPtr;
+ return (U16)((U16)p[0] + (p[1]<<8));
+ }
+}
+
+static void LZ4_writeLE16(void* memPtr, U16 value)
+{
+ if (LZ4_isLittleEndian()) {
+ LZ4_write16(memPtr, value);
+ } else {
+ BYTE* p = (BYTE*)memPtr;
+ p[0] = (BYTE) value;
+ p[1] = (BYTE)(value>>8);
+ }
+}
+
+/* customized variant of memcpy, which can overwrite up to 8 bytes beyond dstEnd */
+LZ4_FORCE_O2_INLINE_GCC_PPC64LE
+void LZ4_wildCopy(void* dstPtr, const void* srcPtr, void* dstEnd)
+{
+ BYTE* d = (BYTE*)dstPtr;
+ const BYTE* s = (const BYTE*)srcPtr;
+ BYTE* const e = (BYTE*)dstEnd;
+
+ do { memcpy(d,s,8); d+=8; s+=8; } while (d=1)
+# include
+#else
+# ifndef assert
+# define assert(condition) ((void)0)
+# endif
+#endif
+
+#define LZ4_STATIC_ASSERT(c) { enum { LZ4_static_assert = 1/(int)(!!(c)) }; } /* use after variable declarations */
+
+#if defined(LZ4_DEBUG) && (LZ4_DEBUG>=2)
+# include
+static int g_debuglog_enable = 1;
+# define DEBUGLOG(l, ...) { \
+ if ((g_debuglog_enable) && (l<=LZ4_DEBUG)) { \
+ fprintf(stderr, __FILE__ ": "); \
+ fprintf(stderr, __VA_ARGS__); \
+ fprintf(stderr, " \n"); \
+ } }
+#else
+# define DEBUGLOG(l, ...) {} /* disabled */
+#endif
+
+
+/*-************************************
+* Common functions
+**************************************/
+static unsigned LZ4_NbCommonBytes (reg_t val)
+{
+ if (LZ4_isLittleEndian()) {
+ if (sizeof(val)==8) {
+# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ unsigned long r = 0;
+ _BitScanForward64( &r, (U64)val );
+ return (int)(r>>3);
+# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ return (__builtin_ctzll((U64)val) >> 3);
+# else
+ static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2,
+ 0, 3, 1, 3, 1, 4, 2, 7,
+ 0, 2, 3, 6, 1, 5, 3, 5,
+ 1, 3, 4, 4, 2, 5, 6, 7,
+ 7, 0, 1, 2, 3, 3, 4, 6,
+ 2, 6, 5, 5, 3, 4, 5, 6,
+ 7, 1, 2, 4, 6, 4, 4, 5,
+ 7, 2, 6, 5, 7, 6, 7, 7 };
+ return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58];
+# endif
+ } else /* 32 bits */ {
+# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ unsigned long r;
+ _BitScanForward( &r, (U32)val );
+ return (int)(r>>3);
+# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ return (__builtin_ctz((U32)val) >> 3);
+# else
+ static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0,
+ 3, 2, 2, 1, 3, 2, 0, 1,
+ 3, 3, 1, 2, 2, 2, 2, 0,
+ 3, 1, 2, 0, 1, 0, 1, 1 };
+ return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27];
+# endif
+ }
+ } else /* Big Endian CPU */ {
+ if (sizeof(val)==8) { /* 64-bits */
+# if defined(_MSC_VER) && defined(_WIN64) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ unsigned long r = 0;
+ _BitScanReverse64( &r, val );
+ return (unsigned)(r>>3);
+# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ return (__builtin_clzll((U64)val) >> 3);
+# else
+ static const U32 by32 = sizeof(val)*4; /* 32 on 64 bits (goal), 16 on 32 bits.
+ Just to avoid some static analyzer complaining about shift by 32 on 32-bits target.
+ Note that this code path is never triggered in 32-bits mode. */
+ unsigned r;
+ if (!(val>>by32)) { r=4; } else { r=0; val>>=by32; }
+ if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; }
+ r += (!val);
+ return r;
+# endif
+ } else /* 32 bits */ {
+# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ unsigned long r = 0;
+ _BitScanReverse( &r, (unsigned long)val );
+ return (unsigned)(r>>3);
+# elif (defined(__clang__) || (defined(__GNUC__) && (__GNUC__>=3))) && !defined(LZ4_FORCE_SW_BITCOUNT)
+ return (__builtin_clz((U32)val) >> 3);
+# else
+ unsigned r;
+ if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; }
+ r += (!val);
+ return r;
+# endif
+ }
+ }
+}
+
+#define STEPSIZE sizeof(reg_t)
+LZ4_FORCE_INLINE
+unsigned LZ4_count(const BYTE* pIn, const BYTE* pMatch, const BYTE* pInLimit)
+{
+ const BYTE* const pStart = pIn;
+
+ if (likely(pIn < pInLimit-(STEPSIZE-1))) {
+ reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
+ if (!diff) {
+ pIn+=STEPSIZE; pMatch+=STEPSIZE;
+ } else {
+ return LZ4_NbCommonBytes(diff);
+ } }
+
+ while (likely(pIn < pInLimit-(STEPSIZE-1))) {
+ reg_t const diff = LZ4_read_ARCH(pMatch) ^ LZ4_read_ARCH(pIn);
+ if (!diff) { pIn+=STEPSIZE; pMatch+=STEPSIZE; continue; }
+ pIn += LZ4_NbCommonBytes(diff);
+ return (unsigned)(pIn - pStart);
+ }
+
+ if ((STEPSIZE==8) && (pIn<(pInLimit-3)) && (LZ4_read32(pMatch) == LZ4_read32(pIn))) { pIn+=4; pMatch+=4; }
+ if ((pIn<(pInLimit-1)) && (LZ4_read16(pMatch) == LZ4_read16(pIn))) { pIn+=2; pMatch+=2; }
+ if ((pIn compression run slower on incompressible data */
+
+
+/*-************************************
+* Local Structures and types
+**************************************/
+typedef enum { notLimited = 0, limitedOutput = 1, fillOutput = 2 } limitedOutput_directive;
+typedef enum { clearedTable = 0, byPtr, byU32, byU16 } tableType_t;
+
+/**
+ * This enum distinguishes several different modes of accessing previous
+ * content in the stream.
+ *
+ * - noDict : There is no preceding content.
+ * - withPrefix64k : Table entries up to ctx->dictSize before the current blob
+ * blob being deCompressBuffer are valid and refer to the preceding
+ * content (of length ctx->dictSize), which is available
+ * contiguously preceding in memory the content currently
+ * being deCompressBuffer.
+ * - usingExtDict : Like withPrefix64k, but the preceding content is somewhere
+ * else in memory, starting at ctx->dictionary with length
+ * ctx->dictSize.
+ * - usingDictCtx : Like usingExtDict, but everything concerning the preceding
+ * content is in a separate context, pointed to by
+ * ctx->dictCtx. ctx->dictionary, ctx->dictSize, and table
+ * entries in the current context that refer to positions
+ * preceding the beginning of the current compression are
+ * ignored. Instead, ctx->dictCtx->dictionary and ctx->dictCtx
+ * ->dictSize describe the location and size of the preceding
+ * content, and matches are found by looking in the ctx
+ * ->dictCtx->hashTable.
+ */
+typedef enum { noDict = 0, withPrefix64k, usingExtDict, usingDictCtx } dict_directive;
+typedef enum { noDictIssue = 0, dictSmall } dictIssue_directive;
+
+
+/*-************************************
+* Local Utils
+**************************************/
+int LZ4_versionNumber (void) { return LZ4_VERSION_NUMBER; }
+const char* LZ4_versionString(void) { return LZ4_VERSION_STRING; }
+int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); }
+int LZ4_sizeofState() { return LZ4_STREAMSIZE; }
+
+
+/*-************************************
+* Internal Definitions used in Tests
+**************************************/
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize);
+
+int LZ4_decompress_safe_forceExtDict(const char* in, char* out, int inSize, int outSize, const void* dict, size_t dictSize);
+
+#if defined (__cplusplus)
+}
+#endif
+
+/*-******************************
+* Compression functions
+********************************/
+static U32 LZ4_hash4(U32 sequence, tableType_t const tableType)
+{
+ if (tableType == byU16)
+ return ((sequence * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1)));
+ else
+ return ((sequence * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG));
+}
+
+static U32 LZ4_hash5(U64 sequence, tableType_t const tableType)
+{
+ const U32 hashLog = (tableType == byU16) ? LZ4_HASHLOG+1 : LZ4_HASHLOG;
+ if (LZ4_isLittleEndian()) {
+ const U64 prime5bytes = 889523592379ULL;
+ return (U32)(((sequence << 24) * prime5bytes) >> (64 - hashLog));
+ } else {
+ const U64 prime8bytes = 11400714785074694791ULL;
+ return (U32)(((sequence >> 24) * prime8bytes) >> (64 - hashLog));
+ }
+}
+
+LZ4_FORCE_INLINE U32 LZ4_hashPosition(const void* const p, tableType_t const tableType)
+{
+ if ((sizeof(reg_t)==8) && (tableType != byU16)) return LZ4_hash5(LZ4_read_ARCH(p), tableType);
+ return LZ4_hash4(LZ4_read32(p), tableType);
+}
+
+static void LZ4_putIndexOnHash(U32 idx, U32 h, void* tableBase, tableType_t const tableType)
+{
+ switch (tableType)
+ {
+ default: /* fallthrough */
+ case clearedTable: /* fallthrough */
+ case byPtr: { /* illegal! */ assert(0); return; }
+ case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = idx; return; }
+ case byU16: { U16* hashTable = (U16*) tableBase; assert(idx < 65536); hashTable[h] = (U16)idx; return; }
+ }
+}
+
+static void LZ4_putPositionOnHash(const BYTE* p, U32 h,
+ void* tableBase, tableType_t const tableType,
+ const BYTE* srcBase)
+{
+ switch (tableType)
+ {
+ case clearedTable: { /* illegal! */ assert(0); return; }
+ case byPtr: { const BYTE** hashTable = (const BYTE**)tableBase; hashTable[h] = p; return; }
+ case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); return; }
+ case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); return; }
+ }
+}
+
+LZ4_FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase)
+{
+ U32 const h = LZ4_hashPosition(p, tableType);
+ LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase);
+}
+
+/* LZ4_getIndexOnHash() :
+ * Index of match position registered in hash table.
+ * hash position must be calculated by using base+index, or dictBase+index.
+ * Assumption 1 : only valid if tableType == byU32 or byU16.
+ * Assumption 2 : h is presumed valid (within limits of hash table)
+ */
+static U32 LZ4_getIndexOnHash(U32 h, const void* tableBase, tableType_t tableType)
+{
+ LZ4_STATIC_ASSERT(LZ4_MEMORY_USAGE > 2);
+ if (tableType == byU32) {
+ const U32* const hashTable = (const U32*) tableBase;
+ assert(h < (1U << (LZ4_MEMORY_USAGE-2)));
+ return hashTable[h];
+ }
+ if (tableType == byU16) {
+ const U16* const hashTable = (const U16*) tableBase;
+ assert(h < (1U << (LZ4_MEMORY_USAGE-1)));
+ return hashTable[h];
+ }
+ assert(0); return 0; /* forbidden case */
+}
+
+static const BYTE* LZ4_getPositionOnHash(U32 h, const void* tableBase, tableType_t tableType, const BYTE* srcBase)
+{
+ if (tableType == byPtr) { const BYTE* const* hashTable = (const BYTE* const*) tableBase; return hashTable[h]; }
+ if (tableType == byU32) { const U32* const hashTable = (const U32*) tableBase; return hashTable[h] + srcBase; }
+ { const U16* const hashTable = (const U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */
+}
+
+LZ4_FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p,
+ const void* tableBase, tableType_t tableType,
+ const BYTE* srcBase)
+{
+ U32 const h = LZ4_hashPosition(p, tableType);
+ return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase);
+}
+
+LZ4_FORCE_INLINE void LZ4_prepareTable(
+ LZ4_stream_t_internal* const cctx,
+ const int inputSize,
+ const tableType_t tableType) {
+ /* If the table hasn't been used, it's guaranteed to be zeroed out, and is
+ * therefore safe to use no matter what mode we're in. Otherwise, we figure
+ * out if it's safe to leave as is or whether it needs to be reset.
+ */
+ if (cctx->tableType != clearedTable) {
+ if (cctx->tableType != tableType
+ || (tableType == byU16 && cctx->currentOffset + inputSize >= 0xFFFFU)
+ || (tableType == byU32 && cctx->currentOffset > 1 GB)
+ || tableType == byPtr
+ || inputSize >= 4 KB)
+ {
+ DEBUGLOG(4, "LZ4_prepareTable: Resetting table in %p", cctx);
+ MEM_INIT(cctx->hashTable, 0, LZ4_HASHTABLESIZE);
+ cctx->currentOffset = 0;
+ cctx->tableType = clearedTable;
+ } else {
+ DEBUGLOG(4, "LZ4_prepareTable: Re-use hash table (no reset)");
+ }
+ }
+
+ /* Adding a gap, so all previous entries are > MAX_DISTANCE back, is faster
+ * than compressing without a gap. However, compressing with
+ * currentOffset == 0 is faster still, so we preserve that case.
+ */
+ if (cctx->currentOffset != 0 && tableType == byU32) {
+ DEBUGLOG(5, "LZ4_prepareTable: adding 64KB to currentOffset");
+ cctx->currentOffset += 64 KB;
+ }
+
+ /* Finally, clear history */
+ cctx->dictCtx = NULL;
+ cctx->dictionary = NULL;
+ cctx->dictSize = 0;
+}
+
+/** LZ4_compress_generic() :
+ inlined, to ensure branches are decided at compilation time */
+LZ4_FORCE_INLINE int LZ4_compress_generic(
+ LZ4_stream_t_internal* const cctx,
+ const char* const source,
+ char* const dest,
+ const int inputSize,
+ int *inputConsumed, /* only written when outputLimited == fillOutput */
+ const int maxOutputSize,
+ const limitedOutput_directive outputLimited,
+ const tableType_t tableType,
+ const dict_directive dictDirective,
+ const dictIssue_directive dictIssue,
+ const U32 acceleration)
+{
+ const BYTE* ip = (const BYTE*) source;
+
+ U32 const startIndex = cctx->currentOffset;
+ const BYTE* base = (const BYTE*) source - startIndex;
+ const BYTE* lowLimit;
+
+ const LZ4_stream_t_internal* dictCtx = (const LZ4_stream_t_internal*) cctx->dictCtx;
+ const BYTE* const dictionary =
+ dictDirective == usingDictCtx ? dictCtx->dictionary : cctx->dictionary;
+ const U32 dictSize =
+ dictDirective == usingDictCtx ? dictCtx->dictSize : cctx->dictSize;
+ const U32 dictDelta = (dictDirective == usingDictCtx) ? startIndex - dictCtx->currentOffset : 0; /* make indexes in dictCtx comparable with index in current context */
+
+ int const maybe_extMem = (dictDirective == usingExtDict) || (dictDirective == usingDictCtx);
+ U32 const prefixIdxLimit = startIndex - dictSize; /* used when dictDirective == dictSmall */
+ const BYTE* const dictEnd = dictionary + dictSize;
+ const BYTE* anchor = (const BYTE*) source;
+ const BYTE* const iend = ip + inputSize;
+ const BYTE* const mflimitPlusOne = iend - MFLIMIT + 1;
+ const BYTE* const matchlimit = iend - LASTLITERALS;
+
+ /* the dictCtx currentOffset is indexed on the start of the dictionary,
+ * while a dictionary in the current context precedes the currentOffset */
+ const BYTE* dictBase = (dictDirective == usingDictCtx) ?
+ dictionary + dictSize - dictCtx->currentOffset :
+ dictionary + dictSize - startIndex;
+
+ BYTE* op = (BYTE*) dest;
+ BYTE* const olimit = op + maxOutputSize;
+
+ U32 offset = 0;
+ U32 forwardH;
+
+ DEBUGLOG(5, "LZ4_compress_generic: srcSize=%i, tableType=%u", inputSize, tableType);
+ /* Init conditions */
+ if (outputLimited == fillOutput && maxOutputSize < 1) return 0; /* Impossible to store anything */
+ if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported inputSize, too large (or negative) */
+ if ((tableType == byU16) && (inputSize>=LZ4_64Klimit)) return 0; /* Size too large (not within 64K limit) */
+ if (tableType==byPtr) assert(dictDirective==noDict); /* only supported use case with byPtr */
+ assert(acceleration >= 1);
+
+ lowLimit = (const BYTE*)source - (dictDirective == withPrefix64k ? dictSize : 0);
+
+ /* Update context state */
+ if (dictDirective == usingDictCtx) {
+ /* Subsequent linked blocks can't use the dictionary. */
+ /* Instead, they use the block we just deCompressBuffer. */
+ cctx->dictCtx = NULL;
+ cctx->dictSize = (U32)inputSize;
+ } else {
+ cctx->dictSize += (U32)inputSize;
+ }
+ cctx->currentOffset += (U32)inputSize;
+ cctx->tableType = (U16)tableType;
+
+ if (inputSizehashTable, tableType, base);
+ ip++; forwardH = LZ4_hashPosition(ip, tableType);
+
+ /* Main Loop */
+ for ( ; ; ) {
+ const BYTE* match;
+ BYTE* token;
+
+ /* Find a match */
+ if (tableType == byPtr) {
+ const BYTE* forwardIp = ip;
+ unsigned step = 1;
+ unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
+ do {
+ U32 const h = forwardH;
+ ip = forwardIp;
+ forwardIp += step;
+ step = (searchMatchNb++ >> LZ4_skipTrigger);
+
+ if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
+ assert(ip < mflimitPlusOne);
+
+ match = LZ4_getPositionOnHash(h, cctx->hashTable, tableType, base);
+ forwardH = LZ4_hashPosition(forwardIp, tableType);
+ LZ4_putPositionOnHash(ip, h, cctx->hashTable, tableType, base);
+
+ } while ( (match+MAX_DISTANCE < ip)
+ || (LZ4_read32(match) != LZ4_read32(ip)) );
+
+ } else { /* byU32, byU16 */
+
+ const BYTE* forwardIp = ip;
+ unsigned step = 1;
+ unsigned searchMatchNb = acceleration << LZ4_skipTrigger;
+ do {
+ U32 const h = forwardH;
+ U32 const current = (U32)(forwardIp - base);
+ U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
+ assert(matchIndex <= current);
+ assert(forwardIp - base < (ptrdiff_t)(2 GB - 1));
+ ip = forwardIp;
+ forwardIp += step;
+ step = (searchMatchNb++ >> LZ4_skipTrigger);
+
+ if (unlikely(forwardIp > mflimitPlusOne)) goto _last_literals;
+ assert(ip < mflimitPlusOne);
+
+ if (dictDirective == usingDictCtx) {
+ if (matchIndex < startIndex) {
+ /* there was no match, try the dictionary */
+ assert(tableType == byU32);
+ matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
+ match = dictBase + matchIndex;
+ matchIndex += dictDelta; /* make dictCtx index comparable with current context */
+ lowLimit = dictionary;
+ } else {
+ match = base + matchIndex;
+ lowLimit = (const BYTE*)source;
+ }
+ } else if (dictDirective==usingExtDict) {
+ if (matchIndex < startIndex) {
+ DEBUGLOG(7, "extDict candidate: matchIndex=%5u < startIndex=%5u", matchIndex, startIndex);
+ assert(startIndex - matchIndex >= MINMATCH);
+ match = dictBase + matchIndex;
+ lowLimit = dictionary;
+ } else {
+ match = base + matchIndex;
+ lowLimit = (const BYTE*)source;
+ }
+ } else { /* single continuous memory segment */
+ match = base + matchIndex;
+ }
+ forwardH = LZ4_hashPosition(forwardIp, tableType);
+ LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
+
+ if ((dictIssue == dictSmall) && (matchIndex < prefixIdxLimit)) continue; /* match outside of valid area */
+ assert(matchIndex < current);
+ if ((tableType != byU16) && (matchIndex+MAX_DISTANCE < current)) continue; /* too far */
+ if (tableType == byU16) assert((current - matchIndex) <= MAX_DISTANCE); /* too_far presumed impossible with byU16 */
+
+ if (LZ4_read32(match) == LZ4_read32(ip)) {
+ if (maybe_extMem) offset = current - matchIndex;
+ break; /* match found */
+ }
+
+ } while(1);
+ }
+
+ /* Catch up */
+ while (((ip>anchor) & (match > lowLimit)) && (unlikely(ip[-1]==match[-1]))) { ip--; match--; }
+
+ /* Encode Literals */
+ { unsigned const litLength = (unsigned)(ip - anchor);
+ token = op++;
+ if ((outputLimited == limitedOutput) && /* Check output buffer overflow */
+ (unlikely(op + litLength + (2 + 1 + LASTLITERALS) + (litLength/255) > olimit)))
+ return 0;
+ if ((outputLimited == fillOutput) &&
+ (unlikely(op + (litLength+240)/255 /* litlen */ + litLength /* literals */ + 2 /* offset */ + 1 /* token */ + MFLIMIT - MINMATCH /* min last literals so last match is <= end - MFLIMIT */ > olimit))) {
+ op--;
+ goto _last_literals;
+ }
+ if (litLength >= RUN_MASK) {
+ int len = (int)litLength-RUN_MASK;
+ *token = (RUN_MASK<= 255 ; len-=255) *op++ = 255;
+ *op++ = (BYTE)len;
+ }
+ else *token = (BYTE)(litLength< olimit)) {
+ /* the match was too close to the end, rewind and go to last literals */
+ op = token;
+ goto _last_literals;
+ }
+
+ /* Encode Offset */
+ if (maybe_extMem) { /* static test */
+ DEBUGLOG(6, " with offset=%u (ext if > %i)", offset, (int)(ip - (const BYTE*)source));
+ assert(offset <= MAX_DISTANCE && offset > 0);
+ LZ4_writeLE16(op, (U16)offset); op+=2;
+ } else {
+ DEBUGLOG(6, " with offset=%u (same segment)", (U32)(ip - match));
+ assert(ip-match <= MAX_DISTANCE);
+ LZ4_writeLE16(op, (U16)(ip - match)); op+=2;
+ }
+
+ /* Encode MatchLength */
+ { unsigned matchCode;
+
+ if ( (dictDirective==usingExtDict || dictDirective==usingDictCtx)
+ && (lowLimit==dictionary) /* match within extDict */ ) {
+ const BYTE* limit = ip + (dictEnd-match);
+ assert(dictEnd > match);
+ if (limit > matchlimit) limit = matchlimit;
+ matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, limit);
+ ip += MINMATCH + matchCode;
+ if (ip==limit) {
+ unsigned const more = LZ4_count(limit, (const BYTE*)source, matchlimit);
+ matchCode += more;
+ ip += more;
+ }
+ DEBUGLOG(6, " with matchLength=%u starting in extDict", matchCode+MINMATCH);
+ } else {
+ matchCode = LZ4_count(ip+MINMATCH, match+MINMATCH, matchlimit);
+ ip += MINMATCH + matchCode;
+ DEBUGLOG(6, " with matchLength=%u", matchCode+MINMATCH);
+ }
+
+ if ((outputLimited) && /* Check output buffer overflow */
+ (unlikely(op + (1 + LASTLITERALS) + (matchCode>>8) > olimit)) ) {
+ if (outputLimited == limitedOutput)
+ return 0;
+ if (outputLimited == fillOutput) {
+ /* Match description too long : reduce it */
+ U32 newMatchCode = 15 /* in token */ - 1 /* to avoid needing a zero byte */ + ((U32)(olimit - op) - 2 - 1 - LASTLITERALS) * 255;
+ ip -= matchCode - newMatchCode;
+ matchCode = newMatchCode;
+ }
+ }
+ if (matchCode >= ML_MASK) {
+ *token += ML_MASK;
+ matchCode -= ML_MASK;
+ LZ4_write32(op, 0xFFFFFFFF);
+ while (matchCode >= 4*255) {
+ op+=4;
+ LZ4_write32(op, 0xFFFFFFFF);
+ matchCode -= 4*255;
+ }
+ op += matchCode / 255;
+ *op++ = (BYTE)(matchCode % 255);
+ } else
+ *token += (BYTE)(matchCode);
+ }
+
+ anchor = ip;
+
+ /* Test end of chunk */
+ if (ip >= mflimitPlusOne) break;
+
+ /* Fill table */
+ LZ4_putPosition(ip-2, cctx->hashTable, tableType, base);
+
+ /* Test next position */
+ if (tableType == byPtr) {
+
+ match = LZ4_getPosition(ip, cctx->hashTable, tableType, base);
+ LZ4_putPosition(ip, cctx->hashTable, tableType, base);
+ if ( (match+MAX_DISTANCE >= ip)
+ && (LZ4_read32(match) == LZ4_read32(ip)) )
+ { token=op++; *token=0; goto _next_match; }
+
+ } else { /* byU32, byU16 */
+
+ U32 const h = LZ4_hashPosition(ip, tableType);
+ U32 const current = (U32)(ip-base);
+ U32 matchIndex = LZ4_getIndexOnHash(h, cctx->hashTable, tableType);
+ assert(matchIndex < current);
+ if (dictDirective == usingDictCtx) {
+ if (matchIndex < startIndex) {
+ /* there was no match, try the dictionary */
+ matchIndex = LZ4_getIndexOnHash(h, dictCtx->hashTable, byU32);
+ match = dictBase + matchIndex;
+ lowLimit = dictionary; /* required for match length counter */
+ matchIndex += dictDelta;
+ } else {
+ match = base + matchIndex;
+ lowLimit = (const BYTE*)source; /* required for match length counter */
+ }
+ } else if (dictDirective==usingExtDict) {
+ if (matchIndex < startIndex) {
+ match = dictBase + matchIndex;
+ lowLimit = dictionary; /* required for match length counter */
+ } else {
+ match = base + matchIndex;
+ lowLimit = (const BYTE*)source; /* required for match length counter */
+ }
+ } else { /* single memory segment */
+ match = base + matchIndex;
+ }
+ LZ4_putIndexOnHash(current, h, cctx->hashTable, tableType);
+ assert(matchIndex < current);
+ if ( ((dictIssue==dictSmall) ? (matchIndex >= prefixIdxLimit) : 1)
+ && ((tableType==byU16) ? 1 : (matchIndex+MAX_DISTANCE >= current))
+ && (LZ4_read32(match) == LZ4_read32(ip)) ) {
+ token=op++;
+ *token=0;
+ if (maybe_extMem) offset = current - matchIndex;
+ DEBUGLOG(6, "seq.start:%i, literals=%u, match.start:%i",
+ (int)(anchor-(const BYTE*)source), 0, (int)(ip-(const BYTE*)source));
+ goto _next_match;
+ }
+ }
+
+ /* Prepare next loop */
+ forwardH = LZ4_hashPosition(++ip, tableType);
+
+ }
+
+_last_literals:
+ /* Encode Last Literals */
+ { size_t lastRun = (size_t)(iend - anchor);
+ if ( (outputLimited) && /* Check output buffer overflow */
+ (op + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > olimit)) {
+ if (outputLimited == fillOutput) {
+ /* adapt lastRun to fill 'dst' */
+ lastRun = (olimit-op) - 1;
+ lastRun -= (lastRun+240)/255;
+ }
+ if (outputLimited == limitedOutput)
+ return 0;
+ }
+ if (lastRun >= RUN_MASK) {
+ size_t accumulator = lastRun - RUN_MASK;
+ *op++ = RUN_MASK << ML_BITS;
+ for(; accumulator >= 255 ; accumulator-=255) *op++ = 255;
+ *op++ = (BYTE) accumulator;
+ } else {
+ *op++ = (BYTE)(lastRun<internal_donotuse;
+ if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
+ LZ4_resetStream((LZ4_stream_t*)state);
+ if (maxOutputSize >= LZ4_compressBound(inputSize)) {
+ if (inputSize < LZ4_64Klimit) {
+ return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, byU16, noDict, noDictIssue, acceleration);
+ } else {
+ const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32;
+ return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
+ }
+ } else {
+ if (inputSize < LZ4_64Klimit) {;
+ return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
+ } else {
+ const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)source > MAX_DISTANCE)) ? byPtr : byU32;
+ return LZ4_compress_generic(ctx, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, noDict, noDictIssue, acceleration);
+ }
+ }
+}
+
+/**
+ * LZ4_compress_fast_extState_fastReset() :
+ * A variant of LZ4_compress_fast_extState().
+ *
+ * Using this variant avoids an expensive initialization step. It is only safe
+ * to call if the state buffer is known to be correctly initialized already
+ * (see comment in lz4.h on LZ4_resetStream_fast() for a definition of
+ * "correctly initialized").
+ */
+int LZ4_compress_fast_extState_fastReset(void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration)
+{
+ LZ4_stream_t_internal* ctx = &((LZ4_stream_t*)state)->internal_donotuse;
+ if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
+
+ if (dstCapacity >= LZ4_compressBound(srcSize)) {
+ if (srcSize < LZ4_64Klimit) {
+ const tableType_t tableType = byU16;
+ LZ4_prepareTable(ctx, srcSize, tableType);
+ if (ctx->currentOffset) {
+ return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, dictSmall, acceleration);
+ } else {
+ return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
+ }
+ } else {
+ const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32;
+ LZ4_prepareTable(ctx, srcSize, tableType);
+ return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, 0, notLimited, tableType, noDict, noDictIssue, acceleration);
+ }
+ } else {
+ if (srcSize < LZ4_64Klimit) {
+ const tableType_t tableType = byU16;
+ LZ4_prepareTable(ctx, srcSize, tableType);
+ if (ctx->currentOffset) {
+ return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, dictSmall, acceleration);
+ } else {
+ return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
+ }
+ } else {
+ const tableType_t tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32;
+ LZ4_prepareTable(ctx, srcSize, tableType);
+ return LZ4_compress_generic(ctx, src, dst, srcSize, NULL, dstCapacity, limitedOutput, tableType, noDict, noDictIssue, acceleration);
+ }
+ }
+}
+
+
+int LZ4_compress_fast(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+ int result;
+#if (LZ4_HEAPMODE)
+ LZ4_stream_t* ctxPtr = ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
+ if (ctxPtr == NULL) return 0;
+#else
+ LZ4_stream_t ctx;
+ LZ4_stream_t* const ctxPtr = &ctx;
+#endif
+ result = LZ4_compress_fast_extState(ctxPtr, source, dest, inputSize, maxOutputSize, acceleration);
+
+#if (LZ4_HEAPMODE)
+ FREEMEM(ctxPtr);
+#endif
+ return result;
+}
+
+
+int LZ4_compress_default(const char* source, char* dest, int inputSize, int maxOutputSize)
+{
+ return LZ4_compress_fast(source, dest, inputSize, maxOutputSize, 1);
+}
+
+
+/* hidden debug function */
+/* strangely enough, gcc generates faster code when this function is uncommented, even if unused */
+int LZ4_compress_fast_force(const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+ LZ4_stream_t ctx;
+ LZ4_resetStream(&ctx);
+
+ if (inputSize < LZ4_64Klimit)
+ return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, byU16, noDict, noDictIssue, acceleration);
+ else
+ return LZ4_compress_generic(&ctx.internal_donotuse, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, sizeof(void*)==8 ? byU32 : byPtr, noDict, noDictIssue, acceleration);
+}
+
+
+/* Note!: This function leaves the stream in an unclean/broken state!
+ * It is not safe to subsequently use the same state with a _fastReset() or
+ * _continue() call without resetting it. */
+static int LZ4_compress_destSize_extState (LZ4_stream_t* state, const char* src, char* dst, int* srcSizePtr, int targetDstSize)
+{
+ LZ4_resetStream(state);
+
+ if (targetDstSize >= LZ4_compressBound(*srcSizePtr)) { /* compression success is guaranteed */
+ return LZ4_compress_fast_extState(state, src, dst, *srcSizePtr, targetDstSize, 1);
+ } else {
+ if (*srcSizePtr < LZ4_64Klimit) {
+ return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, byU16, noDict, noDictIssue, 1);
+ } else {
+ tableType_t const tableType = ((sizeof(void*)==4) && ((uptrval)src > MAX_DISTANCE)) ? byPtr : byU32;
+ return LZ4_compress_generic(&state->internal_donotuse, src, dst, *srcSizePtr, srcSizePtr, targetDstSize, fillOutput, tableType, noDict, noDictIssue, 1);
+ } }
+}
+
+
+int LZ4_compress_destSize(const char* src, char* dst, int* srcSizePtr, int targetDstSize)
+{
+#if (LZ4_HEAPMODE)
+ LZ4_stream_t* ctx = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t)); /* malloc-calloc always properly aligned */
+ if (ctx == NULL) return 0;
+#else
+ LZ4_stream_t ctxBody;
+ LZ4_stream_t* ctx = &ctxBody;
+#endif
+
+ int result = LZ4_compress_destSize_extState(ctx, src, dst, srcSizePtr, targetDstSize);
+
+#if (LZ4_HEAPMODE)
+ FREEMEM(ctx);
+#endif
+ return result;
+}
+
+
+
+/*-******************************
+* Streaming functions
+********************************/
+
+LZ4_stream_t* LZ4_createStream(void)
+{
+ LZ4_stream_t* lz4s = (LZ4_stream_t*)ALLOC(sizeof(LZ4_stream_t));
+ LZ4_STATIC_ASSERT(LZ4_STREAMSIZE >= sizeof(LZ4_stream_t_internal)); /* A compilation error here means LZ4_STREAMSIZE is not large enough */
+ DEBUGLOG(4, "LZ4_createStream %p", lz4s);
+ if (lz4s == NULL) return NULL;
+ LZ4_resetStream(lz4s);
+ return lz4s;
+}
+
+void LZ4_resetStream (LZ4_stream_t* LZ4_stream)
+{
+ DEBUGLOG(5, "LZ4_resetStream (ctx:%p)", LZ4_stream);
+ MEM_INIT(LZ4_stream, 0, sizeof(LZ4_stream_t));
+}
+
+void LZ4_resetStream_fast(LZ4_stream_t* ctx) {
+ LZ4_prepareTable(&(ctx->internal_donotuse), 0, byU32);
+}
+
+int LZ4_freeStream (LZ4_stream_t* LZ4_stream)
+{
+ if (!LZ4_stream) return 0; /* support free on NULL */
+ DEBUGLOG(5, "LZ4_freeStream %p", LZ4_stream);
+ FREEMEM(LZ4_stream);
+ return (0);
+}
+
+
+#define HASH_UNIT sizeof(reg_t)
+int LZ4_loadDict (LZ4_stream_t* LZ4_dict, const char* dictionary, int dictSize)
+{
+ LZ4_stream_t_internal* dict = &LZ4_dict->internal_donotuse;
+ const tableType_t tableType = byU32;
+ const BYTE* p = (const BYTE*)dictionary;
+ const BYTE* const dictEnd = p + dictSize;
+ const BYTE* base;
+
+ DEBUGLOG(4, "LZ4_loadDict (%i bytes from %p into %p)", dictSize, dictionary, LZ4_dict);
+
+ /* It's necessary to reset the context,
+ * and not just continue it with prepareTable()
+ * to avoid any risk of generating overflowing matchIndex
+ * when compressing using this dictionary */
+ LZ4_resetStream(LZ4_dict);
+
+ /* We always increment the offset by 64 KB, since, if the dict is longer,
+ * we truncate it to the last 64k, and if it's shorter, we still want to
+ * advance by a whole window length so we can provide the guarantee that
+ * there are only valid offsets in the window, which allows an optimization
+ * in LZ4_compress_fast_continue() where it uses noDictIssue even when the
+ * dictionary isn't a full 64k. */
+
+ if ((dictEnd - p) > 64 KB) p = dictEnd - 64 KB;
+ base = dictEnd - 64 KB - dict->currentOffset;
+ dict->dictionary = p;
+ dict->dictSize = (U32)(dictEnd - p);
+ dict->currentOffset += 64 KB;
+ dict->tableType = tableType;
+
+ if (dictSize < (int)HASH_UNIT) {
+ return 0;
+ }
+
+ while (p <= dictEnd-HASH_UNIT) {
+ LZ4_putPosition(p, dict->hashTable, tableType, base);
+ p+=3;
+ }
+
+ return dict->dictSize;
+}
+
+void LZ4_attach_dictionary(LZ4_stream_t *working_stream, const LZ4_stream_t *dictionary_stream) {
+ if (dictionary_stream != NULL) {
+ /* If the current offset is zero, we will never look in the
+ * external dictionary context, since there is no value a table
+ * entry can take that indicate a miss. In that case, we need
+ * to bump the offset to something non-zero.
+ */
+ if (working_stream->internal_donotuse.currentOffset == 0) {
+ working_stream->internal_donotuse.currentOffset = 64 KB;
+ }
+ working_stream->internal_donotuse.dictCtx = &(dictionary_stream->internal_donotuse);
+ } else {
+ working_stream->internal_donotuse.dictCtx = NULL;
+ }
+}
+
+
+static void LZ4_renormDictT(LZ4_stream_t_internal* LZ4_dict, int nextSize)
+{
+ if (LZ4_dict->currentOffset + nextSize > 0x80000000) { /* potential ptrdiff_t overflow (32-bits mode) */
+ /* rescale hash table */
+ U32 const delta = LZ4_dict->currentOffset - 64 KB;
+ const BYTE* dictEnd = LZ4_dict->dictionary + LZ4_dict->dictSize;
+ int i;
+ DEBUGLOG(4, "LZ4_renormDictT");
+ for (i=0; ihashTable[i] < delta) LZ4_dict->hashTable[i]=0;
+ else LZ4_dict->hashTable[i] -= delta;
+ }
+ LZ4_dict->currentOffset = 64 KB;
+ if (LZ4_dict->dictSize > 64 KB) LZ4_dict->dictSize = 64 KB;
+ LZ4_dict->dictionary = dictEnd - LZ4_dict->dictSize;
+ }
+}
+
+
+int LZ4_compress_fast_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize, int maxOutputSize, int acceleration)
+{
+ const tableType_t tableType = byU32;
+ LZ4_stream_t_internal* streamPtr = &LZ4_stream->internal_donotuse;
+ const BYTE* dictEnd = streamPtr->dictionary + streamPtr->dictSize;
+
+ DEBUGLOG(5, "LZ4_compress_fast_continue (inputSize=%i)", inputSize);
+
+ if (streamPtr->initCheck) return 0; /* Uninitialized structure detected */
+ LZ4_renormDictT(streamPtr, inputSize); /* avoid index overflow */
+ if (acceleration < 1) acceleration = ACCELERATION_DEFAULT;
+
+ /* invalidate tiny dictionaries */
+ if ( (streamPtr->dictSize-1 < 4) /* intentional underflow */
+ && (dictEnd != (const BYTE*)source) ) {
+ DEBUGLOG(5, "LZ4_compress_fast_continue: dictSize(%u) at addr:%p is too small", streamPtr->dictSize, streamPtr->dictionary);
+ streamPtr->dictSize = 0;
+ streamPtr->dictionary = (const BYTE*)source;
+ dictEnd = (const BYTE*)source;
+ }
+
+ /* Check overlapping input/dictionary space */
+ { const BYTE* sourceEnd = (const BYTE*) source + inputSize;
+ if ((sourceEnd > streamPtr->dictionary) && (sourceEnd < dictEnd)) {
+ streamPtr->dictSize = (U32)(dictEnd - sourceEnd);
+ if (streamPtr->dictSize > 64 KB) streamPtr->dictSize = 64 KB;
+ if (streamPtr->dictSize < 4) streamPtr->dictSize = 0;
+ streamPtr->dictionary = dictEnd - streamPtr->dictSize;
+ }
+ }
+
+ /* prefix mode : source data follows dictionary */
+ if (dictEnd == (const BYTE*)source) {
+ if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset))
+ return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, dictSmall, acceleration);
+ else
+ return LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, withPrefix64k, noDictIssue, acceleration);
+ }
+
+ /* external dictionary mode */
+ { int result;
+ if (streamPtr->dictCtx) {
+ /* We depend here on the fact that dictCtx'es (produced by
+ * LZ4_loadDict) guarantee that their tables contain no references
+ * to offsets between dictCtx->currentOffset - 64 KB and
+ * dictCtx->currentOffset - dictCtx->dictSize. This makes it safe
+ * to use noDictIssue even when the dict isn't a full 64 KB.
+ */
+ if (inputSize > 4 KB) {
+ /* For compressing large blobs, it is faster to pay the setup
+ * cost to copy the dictionary's tables into the active context,
+ * so that the compression loop is only looking into one table.
+ */
+ memcpy(streamPtr, streamPtr->dictCtx, sizeof(LZ4_stream_t));
+ result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
+ } else {
+ result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingDictCtx, noDictIssue, acceleration);
+ }
+ } else {
+ if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
+ result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, dictSmall, acceleration);
+ } else {
+ result = LZ4_compress_generic(streamPtr, source, dest, inputSize, NULL, maxOutputSize, limitedOutput, tableType, usingExtDict, noDictIssue, acceleration);
+ }
+ }
+ streamPtr->dictionary = (const BYTE*)source;
+ streamPtr->dictSize = (U32)inputSize;
+ return result;
+ }
+}
+
+
+/* Hidden debug function, to force-test external dictionary mode */
+int LZ4_compress_forceExtDict (LZ4_stream_t* LZ4_dict, const char* source, char* dest, int srcSize)
+{
+ LZ4_stream_t_internal* streamPtr = &LZ4_dict->internal_donotuse;
+ int result;
+
+ LZ4_renormDictT(streamPtr, srcSize);
+
+ if ((streamPtr->dictSize < 64 KB) && (streamPtr->dictSize < streamPtr->currentOffset)) {
+ result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, dictSmall, 1);
+ } else {
+ result = LZ4_compress_generic(streamPtr, source, dest, srcSize, NULL, 0, notLimited, byU32, usingExtDict, noDictIssue, 1);
+ }
+
+ streamPtr->dictionary = (const BYTE*)source;
+ streamPtr->dictSize = (U32)srcSize;
+
+ return result;
+}
+
+
+/*! LZ4_saveDict() :
+ * If previously deCompressBuffer data block is not guaranteed to remain available at its memory location,
+ * save it into a safer place (char* safeBuffer).
+ * Note : you don't need to call LZ4_loadDict() afterwards,
+ * dictionary is immediately usable, you can therefore call LZ4_compress_fast_continue().
+ * Return : saved dictionary size in bytes (necessarily <= dictSize), or 0 if error.
+ */
+int LZ4_saveDict (LZ4_stream_t* LZ4_dict, char* safeBuffer, int dictSize)
+{
+ LZ4_stream_t_internal* const dict = &LZ4_dict->internal_donotuse;
+ const BYTE* const previousDictEnd = dict->dictionary + dict->dictSize;
+
+ if ((U32)dictSize > 64 KB) dictSize = 64 KB; /* useless to define a dictionary > 64 KB */
+ if ((U32)dictSize > dict->dictSize) dictSize = dict->dictSize;
+
+ memmove(safeBuffer, previousDictEnd - dictSize, dictSize);
+
+ dict->dictionary = (const BYTE*)safeBuffer;
+ dict->dictSize = (U32)dictSize;
+
+ return dictSize;
+}
+
+
+
+/*-*******************************
+ * Decompression functions
+ ********************************/
+
+typedef enum { endOnOutputSize = 0, endOnInputSize = 1 } endCondition_directive;
+typedef enum { decode_full_block = 0, partial_decode = 1 } earlyEnd_directive;
+
+#undef MIN
+#define MIN(a,b) ( (a) < (b) ? (a) : (b) )
+
+/*! LZ4_decompress_generic() :
+ * This generic decompression function covers all use cases.
+ * It shall be instantiated several times, using different sets of directives.
+ * Note that it is important for performance that this function really get inlined,
+ * in order to remove useless branches during compilation optimization.
+ */
+LZ4_FORCE_INLINE int
+LZ4_decompress_generic(
+ const char* const src,
+ char* const dst,
+ int srcSize,
+ int outputSize, /* If endOnInput==endOnInputSize, this value is `dstCapacity` */
+
+ endCondition_directive endOnInput, /* endOnOutputSize, endOnInputSize */
+ earlyEnd_directive partialDecoding, /* full, partial */
+ dict_directive dict, /* noDict, withPrefix64k, usingExtDict */
+ const BYTE* const lowPrefix, /* always <= dst, == dst when no prefix */
+ const BYTE* const dictStart, /* only if dict==usingExtDict */
+ const size_t dictSize /* note : = 0 if noDict */
+ )
+{
+ if (src == NULL) return -1;
+
+ { const BYTE* ip = (const BYTE*) src;
+ const BYTE* const iend = ip + srcSize;
+
+ BYTE* op = (BYTE*) dst;
+ BYTE* const oend = op + outputSize;
+ BYTE* cpy;
+
+ const BYTE* const dictEnd = (dictStart == NULL) ? NULL : dictStart + dictSize;
+ const unsigned inc32table[8] = {0, 1, 2, 1, 0, 4, 4, 4};
+ const int dec64table[8] = {0, 0, 0, -1, -4, 1, 2, 3};
+
+ const int safeDecode = (endOnInput==endOnInputSize);
+ const int checkOffset = ((safeDecode) && (dictSize < (int)(64 KB)));
+
+ /* Set up the "end" pointers for the shortcut. */
+ const BYTE* const shortiend = iend - (endOnInput ? 14 : 8) /*maxLL*/ - 2 /*offset*/;
+ const BYTE* const shortoend = oend - (endOnInput ? 14 : 8) /*maxLL*/ - 18 /*maxML*/;
+
+ DEBUGLOG(5, "LZ4_decompress_generic (srcSize:%i, dstSize:%i)", srcSize, outputSize);
+
+ /* Special cases */
+ assert(lowPrefix <= op);
+ if ((endOnInput) && (unlikely(outputSize==0))) return ((srcSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */
+ if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0 ? 1 : -1);
+ if ((endOnInput) && unlikely(srcSize==0)) return -1;
+
+ /* Main Loop : decode sequences */
+ while (1) {
+ const BYTE* match;
+ size_t offset;
+
+ unsigned const token = *ip++;
+ size_t length = token >> ML_BITS; /* literal length */
+
+ assert(!endOnInput || ip <= iend); /* ip < iend before the increment */
+
+ /* A two-stage shortcut for the most common case:
+ * 1) If the literal length is 0..14, and there is enough space,
+ * enter the shortcut and copy 16 bytes on behalf of the literals
+ * (in the fast mode, only 8 bytes can be safely copied this way).
+ * 2) Further if the match length is 4..18, copy 18 bytes in a similar
+ * manner; but we ensure that there's enough space in the output for
+ * those 18 bytes earlier, upon entering the shortcut (in other words,
+ * there is a combined check for both stages).
+ */
+ if ( (endOnInput ? length != RUN_MASK : length <= 8)
+ /* strictly "less than" on input, to re-enter the loop with at least one byte */
+ && likely((endOnInput ? ip < shortiend : 1) & (op <= shortoend)) ) {
+ /* Copy the literals */
+ memcpy(op, ip, endOnInput ? 16 : 8);
+ op += length; ip += length;
+
+ /* The second stage: prepare for match copying, decode full info.
+ * If it doesn't work out, the info won't be wasted. */
+ length = token & ML_MASK; /* match length */
+ offset = LZ4_readLE16(ip); ip += 2;
+ match = op - offset;
+ assert(match <= op); /* check overflow */
+
+ /* Do not deal with overlapping matches. */
+ if ( (length != ML_MASK)
+ && (offset >= 8)
+ && (dict==withPrefix64k || match >= lowPrefix) ) {
+ /* Copy the match. */
+ memcpy(op + 0, match + 0, 8);
+ memcpy(op + 8, match + 8, 8);
+ memcpy(op +16, match +16, 2);
+ op += length + MINMATCH;
+ /* Both stages worked, load the next token. */
+ continue;
+ }
+
+ /* The second stage didn't work out, but the info is ready.
+ * Propel it right to the point of match copying. */
+ goto _copy_match;
+ }
+
+ /* decode literal length */
+ if (length == RUN_MASK) {
+ unsigned s;
+ if (unlikely(endOnInput ? ip >= iend-RUN_MASK : 0)) goto _output_error; /* overflow detection */
+ do {
+ s = *ip++;
+ length += s;
+ } while ( likely(endOnInput ? ip= WILDCOPYLENGTH);
+ if ( ((endOnInput) && ((cpy>oend-MFLIMIT) || (ip+length>iend-(2+1+LASTLITERALS))) )
+ || ((!endOnInput) && (cpy>oend-WILDCOPYLENGTH)) )
+ {
+ if (partialDecoding) {
+ if (cpy > oend) { cpy = oend; length = oend-op; } /* Partial decoding : stop in the middle of literal segment */
+ if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */
+ } else {
+ if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */
+ if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */
+ }
+ memcpy(op, ip, length);
+ ip += length;
+ op += length;
+ if (!partialDecoding || (cpy == oend)) {
+ /* Necessarily EOF, due to parsing restrictions */
+ break;
+ }
+
+ } else {
+ LZ4_wildCopy(op, ip, cpy); /* may overwrite up to WILDCOPYLENGTH beyond cpy */
+ ip += length; op = cpy;
+ }
+
+ /* get offset */
+ offset = LZ4_readLE16(ip); ip+=2;
+ match = op - offset;
+
+ /* get matchlength */
+ length = token & ML_MASK;
+
+ _copy_match:
+ if ((checkOffset) && (unlikely(match + dictSize < lowPrefix))) goto _output_error; /* Error : offset outside buffers */
+ if (!partialDecoding) {
+ assert(oend > op);
+ assert(oend - op >= 4);
+ LZ4_write32(op, 0); /* silence an msan warning when offset==0; costs <1%; */
+ } /* note : when partialDecoding, there is no guarantee that at least 4 bytes remain available in output buffer */
+
+ if (length == ML_MASK) {
+ unsigned s;
+ do {
+ s = *ip++;
+ if ((endOnInput) && (ip > iend-LASTLITERALS)) goto _output_error;
+ length += s;
+ } while (s==255);
+ if ((safeDecode) && unlikely((uptrval)(op)+length<(uptrval)op)) goto _output_error; /* overflow detection */
+ }
+ length += MINMATCH;
+
+ /* match starting within external dictionary */
+ if ((dict==usingExtDict) && (match < lowPrefix)) {
+ if (unlikely(op+length > oend-LASTLITERALS)) {
+ if (partialDecoding) length = MIN(length, (size_t)(oend-op));
+ else goto _output_error; /* doesn't respect parsing restriction */
+ }
+
+ if (length <= (size_t)(lowPrefix-match)) {
+ /* match fits entirely within external dictionary : just copy */
+ memmove(op, dictEnd - (lowPrefix-match), length);
+ op += length;
+ } else {
+ /* match stretches into both external dictionary and current block */
+ size_t const copySize = (size_t)(lowPrefix - match);
+ size_t const restSize = length - copySize;
+ memcpy(op, dictEnd - copySize, copySize);
+ op += copySize;
+ if (restSize > (size_t)(op - lowPrefix)) { /* overlap copy */
+ BYTE* const endOfMatch = op + restSize;
+ const BYTE* copyFrom = lowPrefix;
+ while (op < endOfMatch) *op++ = *copyFrom++;
+ } else {
+ memcpy(op, lowPrefix, restSize);
+ op += restSize;
+ } }
+ continue;
+ }
+
+ /* copy match within block */
+ cpy = op + length;
+
+ /* partialDecoding : may not respect endBlock parsing restrictions */
+ assert(op<=oend);
+ if (partialDecoding && (cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
+ size_t const mlen = MIN(length, (size_t)(oend-op));
+ const BYTE* const matchEnd = match + mlen;
+ BYTE* const copyEnd = op + mlen;
+ if (matchEnd > op) { /* overlap copy */
+ while (op < copyEnd) *op++ = *match++;
+ } else {
+ memcpy(op, match, mlen);
+ }
+ op = copyEnd;
+ if (op==oend) break;
+ continue;
+ }
+
+ if (unlikely(offset<8)) {
+ op[0] = match[0];
+ op[1] = match[1];
+ op[2] = match[2];
+ op[3] = match[3];
+ match += inc32table[offset];
+ memcpy(op+4, match, 4);
+ match -= dec64table[offset];
+ } else {
+ memcpy(op, match, 8);
+ match += 8;
+ }
+ op += 8;
+
+ if (unlikely(cpy > oend-MATCH_SAFEGUARD_DISTANCE)) {
+ BYTE* const oCopyLimit = oend - (WILDCOPYLENGTH-1);
+ if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last LASTLITERALS bytes must be literals (undeCompressBuffer) */
+ if (op < oCopyLimit) {
+ LZ4_wildCopy(op, match, oCopyLimit);
+ match += oCopyLimit - op;
+ op = oCopyLimit;
+ }
+ while (op < cpy) *op++ = *match++;
+ } else {
+ memcpy(op, match, 8);
+ if (length > 16) LZ4_wildCopy(op+8, match+8, cpy);
+ }
+ op = cpy; /* wildcopy correction */
+ }
+
+ /* end of decoding */
+ if (endOnInput)
+ return (int) (((char*)op)-dst); /* Nb of output bytes decoded */
+ else
+ return (int) (((const char*)ip)-src); /* Nb of input bytes read */
+
+ /* Overflow error detected */
+ _output_error:
+ return (int) (-(((const char*)ip)-src))-1;
+ }
+}
+
+
+/*===== Instantiate the API decoding functions. =====*/
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe(const char* source, char* dest, int deCompressBufferSize, int maxDedeCompressBufferSize)
+{
+ return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxDedeCompressBufferSize,
+ endOnInputSize, decode_full_block, noDict,
+ (BYTE*)dest, NULL, 0);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe_partial(const char* src, char* dst, int deCompressBufferSize, int targetOutputSize, int dstCapacity)
+{
+ dstCapacity = MIN(targetOutputSize, dstCapacity);
+ return LZ4_decompress_generic(src, dst, deCompressBufferSize, dstCapacity,
+ endOnInputSize, partial_decode,
+ noDict, (BYTE*)dst, NULL, 0);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_fast(const char* source, char* dest, int originalSize)
+{
+ return LZ4_decompress_generic(source, dest, 0, originalSize,
+ endOnOutputSize, decode_full_block, withPrefix64k,
+ (BYTE*)dest - 64 KB, NULL, 0);
+}
+
+/*===== Instantiate a few more decoding cases, used more than once. =====*/
+
+LZ4_FORCE_O2_GCC_PPC64LE /* Exported, an obsolete API function. */
+int LZ4_decompress_safe_withPrefix64k(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize)
+{
+ return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize,
+ endOnInputSize, decode_full_block, withPrefix64k,
+ (BYTE*)dest - 64 KB, NULL, 0);
+}
+
+/* Another obsolete API function, paired with the previous one. */
+int LZ4_decompress_fast_withPrefix64k(const char* source, char* dest, int originalSize)
+{
+ /* LZ4_decompress_fast doesn't validate match offsets,
+ * and thus serves well with any prefixed dictionary. */
+ return LZ4_decompress_fast(source, dest, originalSize);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+static int LZ4_decompress_safe_withSmallPrefix(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize,
+ size_t prefixSize)
+{
+ return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize,
+ endOnInputSize, decode_full_block, noDict,
+ (BYTE*)dest-prefixSize, NULL, 0);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe_forceExtDict(const char* source, char* dest,
+ int deCompressBufferSize, int maxOutputSize,
+ const void* dictStart, size_t dictSize)
+{
+ return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize,
+ endOnInputSize, decode_full_block, usingExtDict,
+ (BYTE*)dest, (const BYTE*)dictStart, dictSize);
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+static int LZ4_decompress_fast_extDict(const char* source, char* dest, int originalSize,
+ const void* dictStart, size_t dictSize)
+{
+ return LZ4_decompress_generic(source, dest, 0, originalSize,
+ endOnOutputSize, decode_full_block, usingExtDict,
+ (BYTE*)dest, (const BYTE*)dictStart, dictSize);
+}
+
+/* The "double dictionary" mode, for use with e.g. ring buffers: the first part
+ * of the dictionary is passed as prefix, and the second via dictStart + dictSize.
+ * These routines are used only once, in LZ4_decompress_*_continue().
+ */
+LZ4_FORCE_INLINE
+int LZ4_decompress_safe_doubleDict(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize,
+ size_t prefixSize, const void* dictStart, size_t dictSize)
+{
+ return LZ4_decompress_generic(source, dest, deCompressBufferSize, maxOutputSize,
+ endOnInputSize, decode_full_block, usingExtDict,
+ (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
+}
+
+LZ4_FORCE_INLINE
+int LZ4_decompress_fast_doubleDict(const char* source, char* dest, int originalSize,
+ size_t prefixSize, const void* dictStart, size_t dictSize)
+{
+ return LZ4_decompress_generic(source, dest, 0, originalSize,
+ endOnOutputSize, decode_full_block, usingExtDict,
+ (BYTE*)dest-prefixSize, (const BYTE*)dictStart, dictSize);
+}
+
+/*===== streaming decompression functions =====*/
+
+LZ4_streamDecode_t* LZ4_createStreamDecode(void)
+{
+ LZ4_streamDecode_t* lz4s = (LZ4_streamDecode_t*) ALLOC_AND_ZERO(sizeof(LZ4_streamDecode_t));
+ return lz4s;
+}
+
+int LZ4_freeStreamDecode (LZ4_streamDecode_t* LZ4_stream)
+{
+ if (!LZ4_stream) return 0; /* support free on NULL */
+ FREEMEM(LZ4_stream);
+ return 0;
+}
+
+/*! LZ4_setStreamDecode() :
+ * Use this function to instruct where to find the dictionary.
+ * This function is not necessary if previous data is still available where it was decoded.
+ * Loading a size of 0 is allowed (same effect as no dictionary).
+ * @return : 1 if OK, 0 if error
+ */
+int LZ4_setStreamDecode (LZ4_streamDecode_t* LZ4_streamDecode, const char* dictionary, int dictSize)
+{
+ LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
+ lz4sd->prefixSize = (size_t) dictSize;
+ lz4sd->prefixEnd = (const BYTE*) dictionary + dictSize;
+ lz4sd->externalDict = NULL;
+ lz4sd->extDictSize = 0;
+ return 1;
+}
+
+/*! LZ4_decoderRingBufferSize() :
+ * when setting a ring buffer for streaming decompression (optional scenario),
+ * provides the minimum size of this ring buffer
+ * to be compatible with any source respecting maxBlockSize condition.
+ * Note : in a ring buffer scenario,
+ * blocks are presumed dedeCompressBuffer next to each other.
+ * When not enough space remains for next block (remainingSize < maxBlockSize),
+ * decoding resumes from beginning of ring buffer.
+ * @return : minimum ring buffer size,
+ * or 0 if there is an error (invalid maxBlockSize).
+ */
+int LZ4_decoderRingBufferSize(int maxBlockSize)
+{
+ if (maxBlockSize < 0) return 0;
+ if (maxBlockSize > LZ4_MAX_INPUT_SIZE) return 0;
+ if (maxBlockSize < 16) maxBlockSize = 16;
+ return LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize);
+}
+
+/*
+*_continue() :
+ These decoding functions allow decompression of multiple blocks in "streaming" mode.
+ Previously decoded blocks must still be available at the memory position where they were decoded.
+ If it's not possible, save the relevant part of decoded data into a safe buffer,
+ and indicate where it stands using LZ4_setStreamDecode()
+*/
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_safe_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int deCompressBufferSize, int maxOutputSize)
+{
+ LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
+ int result;
+
+ if (lz4sd->prefixSize == 0) {
+ /* The first call, no dictionary yet. */
+ assert(lz4sd->extDictSize == 0);
+ result = LZ4_decompress_safe(source, dest, deCompressBufferSize, maxOutputSize);
+ if (result <= 0) return result;
+ lz4sd->prefixSize = result;
+ lz4sd->prefixEnd = (BYTE*)dest + result;
+ } else if (lz4sd->prefixEnd == (BYTE*)dest) {
+ /* They're rolling the current segment. */
+ if (lz4sd->prefixSize >= 64 KB - 1)
+ result = LZ4_decompress_safe_withPrefix64k(source, dest, deCompressBufferSize, maxOutputSize);
+ else if (lz4sd->extDictSize == 0)
+ result = LZ4_decompress_safe_withSmallPrefix(source, dest, deCompressBufferSize, maxOutputSize,
+ lz4sd->prefixSize);
+ else
+ result = LZ4_decompress_safe_doubleDict(source, dest, deCompressBufferSize, maxOutputSize,
+ lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
+ if (result <= 0) return result;
+ lz4sd->prefixSize += result;
+ lz4sd->prefixEnd += result;
+ } else {
+ /* The buffer wraps around, or they're switching to another buffer. */
+ lz4sd->extDictSize = lz4sd->prefixSize;
+ lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
+ result = LZ4_decompress_safe_forceExtDict(source, dest, deCompressBufferSize, maxOutputSize,
+ lz4sd->externalDict, lz4sd->extDictSize);
+ if (result <= 0) return result;
+ lz4sd->prefixSize = result;
+ lz4sd->prefixEnd = (BYTE*)dest + result;
+ }
+
+ return result;
+}
+
+LZ4_FORCE_O2_GCC_PPC64LE
+int LZ4_decompress_fast_continue (LZ4_streamDecode_t* LZ4_streamDecode, const char* source, char* dest, int originalSize)
+{
+ LZ4_streamDecode_t_internal* lz4sd = &LZ4_streamDecode->internal_donotuse;
+ int result;
+
+ if (lz4sd->prefixSize == 0) {
+ assert(lz4sd->extDictSize == 0);
+ result = LZ4_decompress_fast(source, dest, originalSize);
+ if (result <= 0) return result;
+ lz4sd->prefixSize = originalSize;
+ lz4sd->prefixEnd = (BYTE*)dest + originalSize;
+ } else if (lz4sd->prefixEnd == (BYTE*)dest) {
+ if (lz4sd->prefixSize >= 64 KB - 1 || lz4sd->extDictSize == 0)
+ result = LZ4_decompress_fast(source, dest, originalSize);
+ else
+ result = LZ4_decompress_fast_doubleDict(source, dest, originalSize,
+ lz4sd->prefixSize, lz4sd->externalDict, lz4sd->extDictSize);
+ if (result <= 0) return result;
+ lz4sd->prefixSize += originalSize;
+ lz4sd->prefixEnd += originalSize;
+ } else {
+ lz4sd->extDictSize = lz4sd->prefixSize;
+ lz4sd->externalDict = lz4sd->prefixEnd - lz4sd->extDictSize;
+ result = LZ4_decompress_fast_extDict(source, dest, originalSize,
+ lz4sd->externalDict, lz4sd->extDictSize);
+ if (result <= 0) return result;
+ lz4sd->prefixSize = originalSize;
+ lz4sd->prefixEnd = (BYTE*)dest + originalSize;
+ }
+
+ return result;
+}
+
+
+/*
+Advanced decoding functions :
+*_usingDict() :
+ These decoding functions work the same as "_continue" ones,
+ the dictionary must be explicitly provided within parameters
+*/
+
+int LZ4_decompress_safe_usingDict(const char* source, char* dest, int deCompressBufferSize, int maxOutputSize, const char* dictStart, int dictSize)
+{
+ if (dictSize==0)
+ return LZ4_decompress_safe(source, dest, deCompressBufferSize, maxOutputSize);
+ if (dictStart+dictSize == dest) {
+ if (dictSize >= 64 KB - 1)
+ return LZ4_decompress_safe_withPrefix64k(source, dest, deCompressBufferSize, maxOutputSize);
+ return LZ4_decompress_safe_withSmallPrefix(source, dest, deCompressBufferSize, maxOutputSize, dictSize);
+ }
+ return LZ4_decompress_safe_forceExtDict(source, dest, deCompressBufferSize, maxOutputSize, dictStart, dictSize);
+}
+
+int LZ4_decompress_fast_usingDict(const char* source, char* dest, int originalSize, const char* dictStart, int dictSize)
+{
+ if (dictSize==0 || dictStart+dictSize == dest)
+ return LZ4_decompress_fast(source, dest, originalSize);
+ return LZ4_decompress_fast_extDict(source, dest, originalSize, dictStart, dictSize);
+}
+
+
+/*=*************************************************
+* Obsolete Functions
+***************************************************/
+/* obsolete compression functions */
+int LZ4_compress_limitedOutput(const char* source, char* dest, int inputSize, int maxOutputSize)
+{
+ return LZ4_compress_default(source, dest, inputSize, maxOutputSize);
+}
+int LZ4_compress(const char* source, char* dest, int inputSize)
+{
+ return LZ4_compress_default(source, dest, inputSize, LZ4_compressBound(inputSize));
+}
+int LZ4_compress_limitedOutput_withState (void* state, const char* src, char* dst, int srcSize, int dstSize)
+{
+ return LZ4_compress_fast_extState(state, src, dst, srcSize, dstSize, 1);
+}
+int LZ4_compress_withState (void* state, const char* src, char* dst, int srcSize)
+{
+ return LZ4_compress_fast_extState(state, src, dst, srcSize, LZ4_compressBound(srcSize), 1);
+}
+int LZ4_compress_limitedOutput_continue (LZ4_stream_t* LZ4_stream, const char* src, char* dst, int srcSize, int dstCapacity)
+{
+ return LZ4_compress_fast_continue(LZ4_stream, src, dst, srcSize, dstCapacity, 1);
+}
+int LZ4_compress_continue (LZ4_stream_t* LZ4_stream, const char* source, char* dest, int inputSize)
+{
+ return LZ4_compress_fast_continue(LZ4_stream, source, dest, inputSize, LZ4_compressBound(inputSize), 1);
+}
+
+/*
+These decompression functions are deprecated and should no longer be used.
+They are only provided here for compatibility with older user programs.
+- LZ4_uncompress is totally equivalent to LZ4_decompress_fast
+- LZ4_uncompress_unknownOutputSize is totally equivalent to LZ4_decompress_safe
+*/
+int LZ4_uncompress (const char* source, char* dest, int outputSize)
+{
+ return LZ4_decompress_fast(source, dest, outputSize);
+}
+int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize)
+{
+ return LZ4_decompress_safe(source, dest, isize, maxOutputSize);
+}
+
+/* Obsolete Streaming functions */
+
+int LZ4_sizeofStreamState() { return LZ4_STREAMSIZE; }
+
+int LZ4_resetStreamState(void* state, char* inputBuffer)
+{
+ (void)inputBuffer;
+ LZ4_resetStream((LZ4_stream_t*)state);
+ return 0;
+}
+
+void* LZ4_create (char* inputBuffer)
+{
+ (void)inputBuffer;
+ return LZ4_createStream();
+}
+
+char* LZ4_slideInputBuffer (void* state)
+{
+ /* avoid const char * -> char * conversion warning */
+ return (char *)(uptrval)((LZ4_stream_t*)state)->internal_donotuse.dictionary;
+}
+
+#endif /* LZ4_COMMONDEFS_ONLY */
diff --git a/bsdiff/lz4.h b/bsdiff/lz4.h
new file mode 100755
index 0000000..e873c13
--- /dev/null
+++ b/bsdiff/lz4.h
@@ -0,0 +1,660 @@
+/*
+ * LZ4 - Fast LZ compression algorithm
+ * Header File
+ * Copyright (C) 2011-present, Yann Collet.
+
+ BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php)
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are
+ met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following disclaimer
+ in the documentation and/or other materials provided with the
+ distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ You can contact the author at :
+ - LZ4 homepage : http://www.lz4.org
+ - LZ4 source repository : https://github.com/lz4/lz4
+ */
+#if defined (__cplusplus)
+extern "C" {
+#endif
+
+#ifndef LZ4_H_2983827168210
+#define LZ4_H_2983827168210
+
+/* --- Dependency --- */
+#include /* size_t */
+
+/**
+ Introduction
+
+ LZ4 is lossless compression algorithm, providing compression speed at 500 MB/s per core,
+ scalable with multi-cores CPU. It features an extremely fast decoder, with speed in
+ multiple GB/s per core, typically reaching RAM speed limits on multi-core systems.
+
+ The LZ4 compression library provides in-memory compression and decompression functions.
+ Compression can be done in:
+ - a single step (described as Simple Functions)
+ - a single step, reusing a context (described in Advanced Functions)
+ - unbounded multiple steps (described as Streaming compression)
+
+ lz4.h provides block compression functions. It gives full buffer control to user.
+ Decompressing an lz4-deCompressBuffer block also requires metadata (such as deCompressBuffer size).
+ Each application is free to encode such metadata in whichever way it wants.
+
+ An additional format, called LZ4 frame specification (doc/lz4_Frame_format.md),
+ take care of encoding standard metadata alongside LZ4-deCompressBuffer blocks.
+ Frame format is required for interoperability.
+ It is delivered through a companion API, declared in lz4frame.h.
+ */
+
+/*^***************************************************************
+ * Export parameters
+ *****************************************************************/
+/*
+ * LZ4_DLL_EXPORT :
+ * Enable exporting of functions when building a Windows DLL
+ * LZ4LIB_VISIBILITY :
+ * Control library symbols visibility.
+ */
+#ifndef LZ4LIB_VISIBILITY
+# if defined(__GNUC__) && (__GNUC__ >= 4)
+# define LZ4LIB_VISIBILITY __attribute__ ((visibility ("default")))
+# else
+# define LZ4LIB_VISIBILITY
+# endif
+#endif
+#if defined(LZ4_DLL_EXPORT) && (LZ4_DLL_EXPORT==1)
+# define LZ4LIB_API __declspec(dllexport) LZ4LIB_VISIBILITY
+#elif defined(LZ4_DLL_IMPORT) && (LZ4_DLL_IMPORT==1)
+# define LZ4LIB_API __declspec(dllimport) LZ4LIB_VISIBILITY /* It isn't required but allows to generate better code, saving a function pointer load from the IAT and an indirect jump.*/
+#else
+# define LZ4LIB_API LZ4LIB_VISIBILITY
+#endif
+
+/*------ Version ------*/
+#define LZ4_VERSION_MAJOR 1 /* for breaking interface changes */
+#define LZ4_VERSION_MINOR 8 /* for new (non-breaking) interface capabilities */
+#define LZ4_VERSION_RELEASE 3 /* for tweaks, bug-fixes, or development */
+
+#define LZ4_VERSION_NUMBER (LZ4_VERSION_MAJOR *100*100 + LZ4_VERSION_MINOR *100 + LZ4_VERSION_RELEASE)
+
+#define LZ4_LIB_VERSION LZ4_VERSION_MAJOR.LZ4_VERSION_MINOR.LZ4_VERSION_RELEASE
+#define LZ4_QUOTE(str) #str
+#define LZ4_EXPAND_AND_QUOTE(str) LZ4_QUOTE(str)
+#define LZ4_VERSION_STRING LZ4_EXPAND_AND_QUOTE(LZ4_LIB_VERSION)
+
+LZ4LIB_API int LZ4_versionNumber(void); /**< library version number; useful to check dll version */
+LZ4LIB_API const char* LZ4_versionString(void); /**< library version string; useful to check dll version */
+
+/*-************************************
+ * Tuning parameter
+ **************************************/
+/*!
+ * LZ4_MEMORY_USAGE :
+ * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.)
+ * Increasing memory usage improves compression ratio.
+ * Reduced memory usage may improve speed, thanks to better cache locality.
+ * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache
+ */
+#ifndef LZ4_MEMORY_USAGE
+# define LZ4_MEMORY_USAGE 14
+#endif
+
+/*-************************************
+ * Simple Functions
+ **************************************/
+/*! LZ4_compress_default() :
+ Compresses 'srcSize' bytes from buffer 'src'
+ into already allocated 'dst' buffer of size 'dstCapacity'.
+ Compression is guaranteed to succeed if 'dstCapacity' >= LZ4_compressBound(srcSize).
+ It also runs faster, so it's a recommended setting.
+ If the function cannot compress 'src' into a more limited 'dst' budget,
+ compression stops *immediately*, and the function result is zero.
+ In which case, 'dst' content is undefined (invalid).
+ srcSize : max supported value is LZ4_MAX_INPUT_SIZE.
+ dstCapacity : size of buffer 'dst' (which must be already allocated)
+ @return : the number of bytes written into buffer 'dst' (necessarily <= dstCapacity)
+ or 0 if compression fails
+ Note : This function is protected against buffer overflow scenarios (never writes outside 'dst' buffer, nor read outside 'source' buffer).
+ */
+LZ4LIB_API int LZ4_compress_default(const char* src, char* dst, int srcSize,
+ int dstCapacity);
+
+/*! LZ4_decompress_safe() :
+ deCompressBufferSize : is the exact complete size of the deCompressBuffer block.
+ dstCapacity : is the size of destination buffer, which must be already allocated.
+ @return : the number of bytes dedeCompressBuffer into destination buffer (necessarily <= dstCapacity)
+ If destination buffer is not large enough, decoding will stop and output an error code (negative value).
+ If the source stream is detected malformed, the function will stop decoding and return a negative result.
+ Note : This function is protected against malicious data packets (never writes outside 'dst' buffer, nor read outside 'source' buffer).
+ */
+LZ4LIB_API int LZ4_decompress_safe(const char* src, char* dst,
+ int deCompressBufferSize, int dstCapacity);
+
+/*-************************************
+ * Advanced Functions
+ **************************************/
+#define LZ4_MAX_INPUT_SIZE 0x7E000000 /* 2 113 929 216 bytes */
+#define LZ4_COMPRESSBOUND(isize) ((unsigned)(isize) > (unsigned)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16)
+
+/*! LZ4_compressBound() :
+ Provides the maximum size that LZ4 compression may output in a "worst case" scenario (input data not compressible)
+ This function is primarily useful for memory allocation purposes (destination buffer size).
+ Macro LZ4_COMPRESSBOUND() is also provided for compilation-time evaluation (stack memory allocation for example).
+ Note that LZ4_compress_default() compresses faster when dstCapacity is >= LZ4_compressBound(srcSize)
+ inputSize : max supported value is LZ4_MAX_INPUT_SIZE
+ return : maximum output size in a "worst case" scenario
+ or 0, if input size is incorrect (too large or negative)
+ */
+LZ4LIB_API int LZ4_compressBound(int inputSize);
+
+/*! LZ4_compress_fast() :
+ Same as LZ4_compress_default(), but allows selection of "acceleration" factor.
+ The larger the acceleration value, the faster the algorithm, but also the lesser the compression.
+ It's a trade-off. It can be fine tuned, with each successive value providing roughly +~3% to speed.
+ An acceleration value of "1" is the same as regular LZ4_compress_default()
+ Values <= 0 will be replaced by ACCELERATION_DEFAULT (currently == 1, see lz4.c).
+ */
+LZ4LIB_API int LZ4_compress_fast(const char* src, char* dst, int srcSize,
+ int dstCapacity, int acceleration);
+
+/*! LZ4_compress_fast_extState() :
+ * Same as LZ4_compress_fast(), using an externally allocated memory space for its state.
+ * Use LZ4_sizeofState() to know how much memory must be allocated,
+ * and allocate it on 8-bytes boundaries (using `malloc()` typically).
+ * Then, provide this buffer as `void* state` to compression function.
+ */
+LZ4LIB_API int LZ4_sizeofState(void);
+LZ4LIB_API int LZ4_compress_fast_extState(void* state, const char* src,
+ char* dst, int srcSize, int dstCapacity, int acceleration);
+
+/*! LZ4_compress_destSize() :
+ * Reverse the logic : compresses as much data as possible from 'src' buffer
+ * into already allocated buffer 'dst', of size >= 'targetDestSize'.
+ * This function either compresses the entire 'src' content into 'dst' if it's large enough,
+ * or fill 'dst' buffer completely with as much data as possible from 'src'.
+ * note: acceleration parameter is fixed to "default".
+ *
+ * *srcSizePtr : will be modified to indicate how many bytes where read from 'src' to fill 'dst'.
+ * New value is necessarily <= input value.
+ * @return : Nb bytes written into 'dst' (necessarily <= targetDestSize)
+ * or 0 if compression fails.
+ */
+LZ4LIB_API int LZ4_compress_destSize(const char* src, char* dst,
+ int* srcSizePtr, int targetDstSize);
+
+/*! LZ4_decompress_fast() : **unsafe!**
+ * This function used to be a bit faster than LZ4_decompress_safe(),
+ * though situation has changed in recent versions,
+ * and now `LZ4_decompress_safe()` can be as fast and sometimes faster than `LZ4_decompress_fast()`.
+ * Moreover, LZ4_decompress_fast() is not protected vs malformed input, as it doesn't perform full validation of deCompressBuffer data.
+ * As a consequence, this function is no longer recommended, and may be deprecated in future versions.
+ * It's last remaining specificity is that it can decompress data without knowing its deCompressBuffer size.
+ *
+ * originalSize : is the undeCompressBuffer size to regenerate.
+ * `dst` must be already allocated, its size must be >= 'originalSize' bytes.
+ * @return : number of bytes read from source buffer (== deCompressBuffer size).
+ * If the source stream is detected malformed, the function stops decoding and returns a negative result.
+ * note : This function requires undeCompressBuffer originalSize to be known in advance.
+ * The function never writes past the output buffer.
+ * However, since it doesn't know its 'src' size, it may read past the intended input.
+ * Also, because match offsets are not validated during decoding,
+ * reads from 'src' may underflow.
+ * Use this function in trusted environment **only**.
+ */
+LZ4LIB_API int LZ4_decompress_fast(const char* src, char* dst,
+ int originalSize);
+
+/*! LZ4_decompress_safe_partial() :
+ * Decompress an LZ4 deCompressBuffer block, of size 'srcSize' at position 'src',
+ * into destination buffer 'dst' of size 'dstCapacity'.
+ * Up to 'targetOutputSize' bytes will be decoded.
+ * The function stops decoding on reaching this objective,
+ * which can boost performance when only the beginning of a block is required.
+ *
+ * @return : the number of bytes decoded in `dst` (necessarily <= dstCapacity)
+ * If source stream is detected malformed, function returns a negative result.
+ *
+ * Note : @return can be < targetOutputSize, if deCompressBuffer block contains less data.
+ *
+ * Note 2 : this function features 2 parameters, targetOutputSize and dstCapacity,
+ * and expects targetOutputSize <= dstCapacity.
+ * It effectively stops decoding on reaching targetOutputSize,
+ * so dstCapacity is kind of redundant.
+ * This is because in a previous version of this function,
+ * decoding operation would not "break" a sequence in the middle.
+ * As a consequence, there was no guarantee that decoding would stop at exactly targetOutputSize,
+ * it could write more bytes, though only up to dstCapacity.
+ * Some "margin" used to be required for this operation to work properly.
+ * This is no longer necessary.
+ * The function nonetheless keeps its signature, in an effort to not break API.
+ */
+LZ4LIB_API int LZ4_decompress_safe_partial(const char* src, char* dst,
+ int srcSize, int targetOutputSize, int dstCapacity);
+
+/*-*********************************************
+ * Streaming Compression Functions
+ ***********************************************/
+typedef union LZ4_stream_u LZ4_stream_t; /* incomplete type (defined later) */
+
+LZ4LIB_API LZ4_stream_t* LZ4_createStream(void);
+LZ4LIB_API int LZ4_freeStream(LZ4_stream_t* streamPtr);
+
+/*! LZ4_resetStream() :
+ * An LZ4_stream_t structure can be allocated once and re-used multiple times.
+ * Use this function to start compressing a new stream.
+ */
+LZ4LIB_API void LZ4_resetStream(LZ4_stream_t* streamPtr);
+
+/*! LZ4_loadDict() :
+ * Use this function to load a static dictionary into LZ4_stream_t.
+ * Any previous data will be forgotten, only 'dictionary' will remain in memory.
+ * Loading a size of 0 is allowed, and is the same as reset.
+ * @return : dictionary size, in bytes (necessarily <= 64 KB)
+ */
+LZ4LIB_API int LZ4_loadDict(LZ4_stream_t* streamPtr, const char* dictionary,
+ int dictSize);
+
+/*! LZ4_compress_fast_continue() :
+ * Compress 'src' content using data from previously deCompressBuffer blocks, for better compression ratio.
+ * 'dst' buffer must be already allocated.
+ * If dstCapacity >= LZ4_compressBound(srcSize), compression is guaranteed to succeed, and runs faster.
+ *
+ * @return : size of deCompressBuffer block
+ * or 0 if there is an error (typically, cannot fit into 'dst').
+ *
+ * Note 1 : Each invocation to LZ4_compress_fast_continue() generates a new block.
+ * Each block has precise boundaries.
+ * Each block must be dedeCompressBuffer separately, calling LZ4_decompress_*() with relevant metadata.
+ * It's not possible to append blocks together and expect a single invocation of LZ4_decompress_*() to decompress them together.
+ *
+ * Note 2 : The previous 64KB of source data is __assumed__ to remain present, unmodified, at same address in memory !
+ *
+ * Note 3 : When input is structured as a double-buffer, each buffer can have any size, including < 64 KB.
+ * Make sure that buffers are separated, by at least one byte.
+ * This construction ensures that each block only depends on previous block.
+ *
+ * Note 4 : If input buffer is a ring-buffer, it can have any size, including < 64 KB.
+ *
+ * Note 5 : After an error, the stream status is undefined (invalid), it can only be reset or freed.
+ */
+LZ4LIB_API int LZ4_compress_fast_continue(LZ4_stream_t* streamPtr,
+ const char* src, char* dst, int srcSize, int dstCapacity,
+ int acceleration);
+
+/*! LZ4_saveDict() :
+ * If last 64KB data cannot be guaranteed to remain available at its current memory location,
+ * save it into a safer place (char* safeBuffer).
+ * This is schematically equivalent to a memcpy() followed by LZ4_loadDict(),
+ * but is much faster, because LZ4_saveDict() doesn't need to rebuild tables.
+ * @return : saved dictionary size in bytes (necessarily <= maxDictSize), or 0 if error.
+ */
+LZ4LIB_API int LZ4_saveDict(LZ4_stream_t* streamPtr, char* safeBuffer,
+ int maxDictSize);
+
+/*-**********************************************
+ * Streaming Decompression Functions
+ * Bufferless synchronous API
+ ************************************************/
+typedef union LZ4_streamDecode_u LZ4_streamDecode_t; /* tracking context */
+
+/*! LZ4_createStreamDecode() and LZ4_freeStreamDecode() :
+ * creation / destruction of streaming decompression tracking context.
+ * A tracking context can be re-used multiple times.
+ */
+LZ4LIB_API LZ4_streamDecode_t* LZ4_createStreamDecode(void);
+LZ4LIB_API int LZ4_freeStreamDecode(LZ4_streamDecode_t* LZ4_stream);
+
+/*! LZ4_setStreamDecode() :
+ * An LZ4_streamDecode_t context can be allocated once and re-used multiple times.
+ * Use this function to start decompression of a new stream of blocks.
+ * A dictionary can optionally be set. Use NULL or size 0 for a reset order.
+ * Dictionary is presumed stable : it must remain accessible and unmodified during next decompression.
+ * @return : 1 if OK, 0 if error
+ */
+LZ4LIB_API int LZ4_setStreamDecode(LZ4_streamDecode_t* LZ4_streamDecode,
+ const char* dictionary, int dictSize);
+
+/*! LZ4_decoderRingBufferSize() : v1.8.2+
+ * Note : in a ring buffer scenario (optional),
+ * blocks are presumed dedeCompressBuffer next to each other
+ * up to the moment there is not enough remaining space for next block (remainingSize < maxBlockSize),
+ * at which stage it resumes from beginning of ring buffer.
+ * When setting such a ring buffer for streaming decompression,
+ * provides the minimum size of this ring buffer
+ * to be compatible with any source respecting maxBlockSize condition.
+ * @return : minimum ring buffer size,
+ * or 0 if there is an error (invalid maxBlockSize).
+ */
+LZ4LIB_API int LZ4_decoderRingBufferSize(int maxBlockSize);
+#define LZ4_DECODER_RING_BUFFER_SIZE(maxBlockSize) (65536 + 14 + (maxBlockSize)) /* for static allocation; maxBlockSize presumed valid */
+
+/*! LZ4_decompress_*_continue() :
+ * These decoding functions allow decompression of consecutive blocks in "streaming" mode.
+ * A block is an unsplittable entity, it must be presented entirely to a decompression function.
+ * Decompression functions only accepts one block at a time.
+ * The last 64KB of previously decoded data *must* remain available and unmodified at the memory position where they were decoded.
+ * If less than 64KB of data has been decoded, all the data must be present.
+ *
+ * Special : if decompression side sets a ring buffer, it must respect one of the following conditions :
+ * - Decompression buffer size is _at least_ LZ4_decoderRingBufferSize(maxBlockSize).
+ * maxBlockSize is the maximum size of any single block. It can have any value > 16 bytes.
+ * In which case, encoding and decoding buffers do not need to be synchronized.
+ * Actually, data can be produced by any source compliant with LZ4 format specification, and respecting maxBlockSize.
+ * - Synchronized mode :
+ * Decompression buffer size is _exactly_ the same as compression buffer size,
+ * and follows exactly same update rule (block boundaries at same positions),
+ * and decoding function is provided with exact dedeCompressBuffer size of each block (exception for last block of the stream),
+ * _then_ decoding & encoding ring buffer can have any size, including small ones ( < 64 KB).
+ * - Decompression buffer is larger than encoding buffer, by a minimum of maxBlockSize more bytes.
+ * In which case, encoding and decoding buffers do not need to be synchronized,
+ * and encoding ring buffer can have any size, including small ones ( < 64 KB).
+ *
+ * Whenever these conditions are not possible,
+ * save the last 64KB of decoded data into a safe buffer where it can't be modified during decompression,
+ * then indicate where this data is saved using LZ4_setStreamDecode(), before decompressing next block.
+ */
+LZ4LIB_API int LZ4_decompress_safe_continue(
+ LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst,
+ int srcSize, int dstCapacity);
+LZ4LIB_API int LZ4_decompress_fast_continue(
+ LZ4_streamDecode_t* LZ4_streamDecode, const char* src, char* dst,
+ int originalSize);
+
+/*! LZ4_decompress_*_usingDict() :
+ * These decoding functions work the same as
+ * a combination of LZ4_setStreamDecode() followed by LZ4_decompress_*_continue()
+ * They are stand-alone, and don't need an LZ4_streamDecode_t structure.
+ * Dictionary is presumed stable : it must remain accessible and unmodified during decompression.
+ * Performance tip : Decompression speed can be substantially increased
+ * when dst == dictStart + dictSize.
+ */
+LZ4LIB_API int LZ4_decompress_safe_usingDict(const char* src, char* dst,
+ int srcSize, int dstCapcity, const char* dictStart, int dictSize);
+LZ4LIB_API int LZ4_decompress_fast_usingDict(const char* src, char* dst,
+ int originalSize, const char* dictStart, int dictSize);
+
+/*^**********************************************
+ * !!!!!! STATIC LINKING ONLY !!!!!!
+ ***********************************************/
+
+/*-************************************
+ * Unstable declarations
+ **************************************
+ * Declarations in this section must be considered unstable.
+ * Their signatures may change, or may be removed in the future.
+ * They are therefore only safe to depend on
+ * when the caller is statically linked against the library.
+ * To access their declarations, define LZ4_STATIC_LINKING_ONLY.
+ **************************************/
+
+#ifdef LZ4_STATIC_LINKING_ONLY
+
+/* By default, symbols in this section aren't published into shared/dynamic libraries.
+ * You can override this behavior and force them to be published
+ * by defining LZ4_PUBLISH_STATIC_FUNCTIONS.
+ * Use at your own risk.
+ */
+
+#ifdef LZ4_PUBLISH_STATIC_FUNCTIONS
+#define LZ4LIB_STATIC_API LZ4LIB_API
+#else
+#define LZ4LIB_STATIC_API
+#endif
+
+/*! LZ4_resetStream_fast() :
+ * Use this, like LZ4_resetStream(), to prepare a context for a new chain of
+ * calls to a streaming API (e.g., LZ4_compress_fast_continue()).
+ *
+ * Note:
+ * Using this in advance of a non-streaming-compression function is redundant,
+ * since they all perform their own custom reset internally.
+ *
+ * Differences from LZ4_resetStream():
+ * When an LZ4_stream_t is known to be in a internally coherent state,
+ * it can often be prepared for a new compression with almost no work,
+ * only sometimes falling back to the full, expensive reset
+ * that is always required when the stream is in an indeterminate state
+ * (i.e., the reset performed by LZ4_resetStream()).
+ *
+ * LZ4_streams are guaranteed to be in a valid state when:
+ * - returned from LZ4_createStream()
+ * - reset by LZ4_resetStream()
+ * - memset(stream, 0, sizeof(LZ4_stream_t)), though this is discouraged
+ * - the stream was in a valid state and was reset by LZ4_resetStream_fast()
+ * - the stream was in a valid state and was then used in any compression call
+ * that returned success
+ * - the stream was in an indeterminate state and was used in a compression
+ * call that fully reset the state (e.g., LZ4_compress_fast_extState()) and
+ * that returned success
+ *
+ * When a stream isn't known to be in a valid state, it is not safe to pass to
+ * any fastReset or streaming function. It must first be cleansed by the full
+ * LZ4_resetStream().
+ */
+LZ4LIB_STATIC_API void LZ4_resetStream_fast (LZ4_stream_t* streamPtr);
+
+/*! LZ4_compress_fast_extState_fastReset() :
+ * A variant of LZ4_compress_fast_extState().
+ *
+ * Using this variant avoids an expensive initialization step.
+ * It is only safe to call if the state buffer is known to be correctly initialized already
+ * (see above comment on LZ4_resetStream_fast() for a definition of "correctly initialized").
+ * From a high level, the difference is that
+ * this function initializes the provided state with a call to something like LZ4_resetStream_fast()
+ * while LZ4_compress_fast_extState() starts with a call to LZ4_resetStream().
+ */
+LZ4LIB_STATIC_API int LZ4_compress_fast_extState_fastReset (void* state, const char* src, char* dst, int srcSize, int dstCapacity, int acceleration);
+
+/*! LZ4_attach_dictionary() :
+ * This is an experimental API that allows
+ * efficient use of a static dictionary many times.
+ *
+ * Rather than re-loading the dictionary buffer into a working context before
+ * each compression, or copying a pre-loaded dictionary's LZ4_stream_t into a
+ * working LZ4_stream_t, this function introduces a no-copy setup mechanism,
+ * in which the working stream references the dictionary stream in-place.
+ *
+ * Several assumptions are made about the state of the dictionary stream.
+ * Currently, only streams which have been prepared by LZ4_loadDict() should
+ * be expected to work.
+ *
+ * Alternatively, the provided dictionaryStream may be NULL,
+ * in which case any existing dictionary stream is unset.
+ *
+ * If a dictionary is provided, it replaces any pre-existing stream history.
+ * The dictionary contents are the only history that can be referenced and
+ * logically immediately precede the data deCompressBuffer in the first subsequent
+ * compression call.
+ *
+ * The dictionary will only remain attached to the working stream through the
+ * first compression call, at the end of which it is cleared. The dictionary
+ * stream (and source buffer) must remain in-place / accessible / unchanged
+ * through the completion of the first compression call on the stream.
+ */
+LZ4LIB_STATIC_API void LZ4_attach_dictionary(LZ4_stream_t* workingStream, const LZ4_stream_t* dictionaryStream);
+
+#endif
+
+/*-************************************
+ * Private definitions
+ **************************************
+ * Do not use these definitions directly.
+ * They are only exposed to allow static allocation of `LZ4_stream_t` and `LZ4_streamDecode_t`.
+ * Accessing members will expose code to API and/or ABI break in future versions of the library.
+ **************************************/
+#define LZ4_HASHLOG (LZ4_MEMORY_USAGE-2)
+#define LZ4_HASHTABLESIZE (1 << LZ4_MEMORY_USAGE)
+#define LZ4_HASH_SIZE_U32 (1 << LZ4_HASHLOG) /* required as macro for static allocation */
+
+#if defined(__cplusplus) || (defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */)
+#include
+
+typedef struct LZ4_stream_t_internal LZ4_stream_t_internal;
+struct LZ4_stream_t_internal {
+ uint32_t hashTable[LZ4_HASH_SIZE_U32];
+ uint32_t currentOffset;
+ uint16_t initCheck;
+ uint16_t tableType;
+ const uint8_t* dictionary;
+ const LZ4_stream_t_internal* dictCtx;
+ uint32_t dictSize;
+};
+
+typedef struct {
+ const uint8_t* externalDict;
+ size_t extDictSize;
+ const uint8_t* prefixEnd;
+ size_t prefixSize;
+} LZ4_streamDecode_t_internal;
+
+#else
+
+typedef struct LZ4_stream_t_internal LZ4_stream_t_internal;
+struct LZ4_stream_t_internal {
+ unsigned int hashTable[LZ4_HASH_SIZE_U32];
+ unsigned int currentOffset;
+ unsigned short initCheck;
+ unsigned short tableType;
+ const unsigned char* dictionary;
+ const LZ4_stream_t_internal* dictCtx;
+ unsigned int dictSize;
+};
+
+typedef struct {
+ const unsigned char* externalDict;
+ size_t extDictSize;
+ const unsigned char* prefixEnd;
+ size_t prefixSize;
+}LZ4_streamDecode_t_internal;
+
+#endif
+
+/*! LZ4_stream_t :
+ * information structure to track an LZ4 stream.
+ * init this structure with LZ4_resetStream() before first use.
+ * note : only use in association with static linking !
+ * this definition is not API/ABI safe,
+ * it may change in a future version !
+ */
+#define LZ4_STREAMSIZE_U64 ((1 << (LZ4_MEMORY_USAGE-3)) + 4)
+#define LZ4_STREAMSIZE (LZ4_STREAMSIZE_U64 * sizeof(unsigned long long))
+union LZ4_stream_u {
+ unsigned long long table[LZ4_STREAMSIZE_U64];
+ LZ4_stream_t_internal internal_donotuse;
+};
+/* previously typedef'd to LZ4_stream_t */
+
+/*! LZ4_streamDecode_t :
+ * information structure to track an LZ4 stream during decompression.
+ * init this structure using LZ4_setStreamDecode() before first use.
+ * note : only use in association with static linking !
+ * this definition is not API/ABI safe,
+ * and may change in a future version !
+ */
+#define LZ4_STREAMDECODESIZE_U64 4
+#define LZ4_STREAMDECODESIZE (LZ4_STREAMDECODESIZE_U64 * sizeof(unsigned long long))
+union LZ4_streamDecode_u {
+ unsigned long long table[LZ4_STREAMDECODESIZE_U64];
+ LZ4_streamDecode_t_internal internal_donotuse;
+};
+/* previously typedef'd to LZ4_streamDecode_t */
+
+/*-************************************
+ * Obsolete Functions
+ **************************************/
+
+/*! Deprecation warnings
+ Should deprecation warnings be a problem,
+ it is generally possible to disable them,
+ typically with -Wno-deprecated-declarations for gcc
+ or _CRT_SECURE_NO_WARNINGS in Visual.
+ Otherwise, it's also possible to define LZ4_DISABLE_DEPRECATE_WARNINGS */
+#ifdef LZ4_DISABLE_DEPRECATE_WARNINGS
+# define LZ4_DEPRECATED(message) /* disable deprecation warnings */
+#else
+# define LZ4_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+# if defined (__cplusplus) && (__cplusplus >= 201402) /* C++14 or greater */
+# define LZ4_DEPRECATED(message) [[deprecated(message)]]
+# elif (LZ4_GCC_VERSION >= 405) || defined(__clang__)
+# define LZ4_DEPRECATED(message) __attribute__((deprecated(message)))
+# elif (LZ4_GCC_VERSION >= 301)
+# define LZ4_DEPRECATED(message) __attribute__((deprecated))
+# elif defined(_MSC_VER)
+# define LZ4_DEPRECATED(message) __declspec(deprecated(message))
+# else
+# pragma message("WARNING: You need to implement LZ4_DEPRECATED for this compiler")
+# define LZ4_DEPRECATED(message)
+# endif
+#endif /* LZ4_DISABLE_DEPRECATE_WARNINGS */
+
+/* Obsolete compression functions */
+LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress(
+ const char* source, char* dest, int sourceSize);
+LZ4_DEPRECATED("use LZ4_compress_default() instead") LZ4LIB_API int LZ4_compress_limitedOutput(
+ const char* source, char* dest, int sourceSize, int maxOutputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_withState(
+ void* state, const char* source, char* dest, int inputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_extState() instead") LZ4LIB_API int LZ4_compress_limitedOutput_withState(
+ void* state, const char* source, char* dest, int inputSize,
+ int maxOutputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_continue(
+ LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest,
+ int inputSize);
+LZ4_DEPRECATED("use LZ4_compress_fast_continue() instead") LZ4LIB_API int LZ4_compress_limitedOutput_continue(
+ LZ4_stream_t* LZ4_streamPtr, const char* source, char* dest,
+ int inputSize, int maxOutputSize);
+
+/* Obsolete decompression functions */
+LZ4_DEPRECATED("use LZ4_decompress_fast() instead") LZ4LIB_API int LZ4_uncompress(
+ const char* source, char* dest, int outputSize);
+LZ4_DEPRECATED("use LZ4_decompress_safe() instead") LZ4LIB_API int LZ4_uncompress_unknownOutputSize(
+ const char* source, char* dest, int isize, int maxOutputSize);
+
+/* Obsolete streaming functions; degraded functionality; do not use!
+ *
+ * In order to perform streaming compression, these functions depended on data
+ * that is no longer tracked in the state. They have been preserved as well as
+ * possible: using them will still produce a correct output. However, they don't
+ * actually retain any history between compression calls. The compression ratio
+ * achieved will therefore be no better than compressing each chunk
+ * independently.
+ */
+LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API void* LZ4_create(
+ char* inputBuffer);
+LZ4_DEPRECATED("Use LZ4_createStream() instead") LZ4LIB_API int LZ4_sizeofStreamState(
+ void);
+LZ4_DEPRECATED("Use LZ4_resetStream() instead") LZ4LIB_API int LZ4_resetStreamState(
+ void* state, char* inputBuffer);
+LZ4_DEPRECATED("Use LZ4_saveDict() instead") LZ4LIB_API char* LZ4_slideInputBuffer(
+ void* state);
+
+/* Obsolete streaming decoding functions */
+LZ4_DEPRECATED("use LZ4_decompress_safe_usingDict() instead") LZ4LIB_API int LZ4_decompress_safe_withPrefix64k(
+ const char* src, char* dst, int deCompressBufferSize, int maxDstSize);
+LZ4_DEPRECATED("use LZ4_decompress_fast_usingDict() instead") LZ4LIB_API int LZ4_decompress_fast_withPrefix64k(
+ const char* src, char* dst, int originalSize);
+
+#endif /* LZ4_H_2983827168210 */
+
+#if defined (__cplusplus)
+}
+#endif
diff --git a/bsdiff/varint.c b/bsdiff/varint.c
new file mode 100644
index 0000000..fb80b0f
--- /dev/null
+++ b/bsdiff/varint.c
@@ -0,0 +1,152 @@
+/*-
+ * Copyright (c) 2018-2019 ARM Limited
+ * All rights reserved
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted providing that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
+ * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
+ * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+ * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include
+#include
+#include
+
+const unsigned char TOP_BIT_ON_BYTE = (128);
+const unsigned char TOP_BIT_OFF_BYTE = (127);
+
+// return 0 if decode completed otherwise 1 negative on error
+var_int_op_code decode_unsigned_varint(unsigned char varIntByte, uint64_t* varIntValue, int count)
+{
+ var_int_op_code returnValue = OPERATION_COMPLETED;
+
+ if (count > 9 || varIntValue == 0) {
+ return ERR_PARAMETTERS;
+ }
+
+ if (count == 0) {
+ *varIntValue = 0;
+ }
+
+ int hasMore = varIntByte & TOP_BIT_ON_BYTE;
+ varIntByte &= TOP_BIT_OFF_BYTE;
+
+ uint64_t byteAs64int = varIntByte;
+
+ for (int i = 0; i < count; i++) {
+ byteAs64int <<= 7;
+ }
+ *varIntValue |= byteAs64int;
+
+ if (hasMore) {
+ returnValue = OPERATION_NEEDS_MORE_DATA;
+ } else {
+ returnValue = OPERATION_COMPLETED;
+ }
+
+ return returnValue;
+}
+
+int encode_unsigned_varint(uint64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX)
+{
+ unsigned int pos = 0;
+ do {
+ if (pos >= BUFF_SIZE_MAX) {
+ return ERR_BUFFER_TOO_SMALL; // protecting buf from overwrite
+ }
+ buf[pos] = (unsigned char) value;
+ value >>= 7;
+ if (value > 0) {
+ buf[pos] |= TOP_BIT_ON_BYTE;
+ } else {
+ buf[pos] &= TOP_BIT_OFF_BYTE;
+ }
+ pos++;
+ } while (value > 0);
+
+ return pos;
+}
+
+int encode_signed_varint(int64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX)
+{
+ unsigned int pos = 0;
+
+ if (value < 0) {
+ value = value * -1; // change value to positive number.
+ value <<= 1;
+ value |= 1; // set lowest bit 1 if it was negative;
+ } else {
+ value <<= 1; // lower bit set to 0 if not negative.
+ }
+
+ do {
+ if (pos >= BUFF_SIZE_MAX) {
+ return ERR_BUFFER_TOO_SMALL; // protecting buf from overwrite
+ }
+ buf[pos] = (unsigned char) value;
+ value >>= 7;
+ if (value > 0) {
+ buf[pos] |= TOP_BIT_ON_BYTE;
+ } else {
+ buf[pos] &= TOP_BIT_OFF_BYTE;
+ }
+ pos++;
+ } while (value > 0);
+
+ return pos;
+}
+
+var_int_op_code decode_signed_varint(unsigned char varIntByte, int64_t* varIntValue, int count)
+{
+ var_int_op_code returnValue = OPERATION_COMPLETED;
+
+ if (count > 9 || varIntValue == 0) {
+ return ERR_PARAMETTERS;
+ }
+
+ if (count == 0) {
+ *varIntValue = 0;
+ }
+
+ int hasMore = varIntByte & TOP_BIT_ON_BYTE;
+ varIntByte &= TOP_BIT_OFF_BYTE;
+
+ uint64_t byteAs64int = varIntByte;
+
+ for (int i = 0; i < count; i++) {
+ byteAs64int <<= 7;
+ }
+ *varIntValue |= byteAs64int;
+
+ if (hasMore) {
+ returnValue = OPERATION_NEEDS_MORE_DATA;
+ } else {
+ returnValue = OPERATION_COMPLETED;
+ if (*varIntValue & 1) // this is negative value
+ {
+ *varIntValue >>= 1;
+ *varIntValue = *varIntValue * -1;
+ } else {
+ *varIntValue >>= 1; // positive value just eat the lowest bit away.
+ }
+ }
+
+ return returnValue;
+}
+
diff --git a/bsdiff/varint.h b/bsdiff/varint.h
new file mode 100644
index 0000000..89806e3
--- /dev/null
+++ b/bsdiff/varint.h
@@ -0,0 +1,40 @@
+// ----------------------------------------------------------------------------
+// Copyright 2019 ARM Ltd.
+//
+// SPDX-License-Identifier: Apache-2.0
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+// ----------------------------------------------------------------------------
+
+#ifndef VARINT_H
+#define VARINT_H
+
+#include
+
+typedef enum {
+ ERR_BUFFER_TOO_SMALL = -7,
+ ERR_PARAMETTERS = -6,
+ OPERATION_COMPLETED = 0,
+ OPERATION_NEEDS_MORE_DATA = 1
+}var_int_op_code;
+
+// decodes varint with multiple calls one byte at a time, returns 1 of more data is needed caller should pass
+// number of calls already done int count
+var_int_op_code decode_unsigned_varint(unsigned char varIntByte, uint64_t* varIntValue, int count);
+var_int_op_code decode_signed_varint(unsigned char varIntByte, int64_t* varIntValue, int count);
+
+// encodes varint to stream, BUFF_SIZE_MAX should containt maxbytes in buf to avoid overwrites
+int encode_unsigned_varint(uint64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX);
+int encode_signed_varint(int64_t value, unsigned char *buf, uint32_t BUFF_SIZE_MAX);
+
+#endif
diff --git a/changelog.md b/changelog.md
new file mode 100644
index 0000000..4799318
--- /dev/null
+++ b/changelog.md
@@ -0,0 +1,38 @@
+# Changelog
+
+## 2.0.0
+Works with client-lite.
+
+Key differences from previous version:
+
+| | Manifest 1.5.2 | Manifest 2.0.0 |
+|:----------------------------------|:---------------------------|:----------------------------------------------------------------------------|
+| Supported manifest schema version | `v1` | `v1` and `v3` |
+| Delta update | Supported | Supported |
+| Component update | Not supported | Supported |
+| PDMC | Supported 4.5.0 or earlier | `v1` support covers PDMC, `v3` support is only available on Client Lite |
+| Client Lite | Supported | Supports both `v1` (by default) and `v3` and can be configured at build time|
+
+**Changes:**
+
+- introduce new ASN manifest format `v3`
+- added delta-tool as Python module
+- introduced [Semantic version](https://semver.org/) format
+- add an option to sign candidate image using update private key -
+ allowing to implement secure boot on a device side
+- work with ECDSA raw signatures `(R||S)` - reduce verify code size on
+ target device
+- simplified command line interface
+ - split between developer and production tools:
+ - `manifest-tool` - is for production use
+ - `manifest-dev-tool` - is for developer use only
+ - `manifest-delta-tool` - is the tool for preparing delta patches
+- cleanup developer tool CLI by removing various configuration that
+ have no practical use at current point
+- backward comparability with ASN manifest format v1 is preserved via
+ dedicated commands:
+ - `manifest-tool create-v1`
+ - `manifest-dev-tool update-v1`
+ - `manifest-dev-tool create-v1`
+
+# 1.5.2
diff --git a/dev-README.md b/dev-README.md
new file mode 100644
index 0000000..c67999b
--- /dev/null
+++ b/dev-README.md
@@ -0,0 +1,89 @@
+# Package Development
+
+## Pyenv - https://github.com/pyenv/pyenv
+`pyenv` helps to manage different Python installations side by side.
+
+Example:
+```shell
+$ pyenv install 3.8.0
+$ pyenv install 3.7.5
+$ pyenv install 3.6.9
+$ pyenv install 3.5.7
+$ pyenv local 3.8.0 3.7.5 3.6.9 3.5.7
+$ python --version
+Python 3.8.0
+```
+## Editable distribution
+
+For development it is preferable to install `manifest-tool` package in
+"editable mode" (a.k.a "developer mode") by:
+```shell
+$ pip install -editable .
+```
+
+## dev_init.sh
+
+A helper script for bootstrapping development environment.
+
+Usage:
+```shell
+$ source dev_init.sh
+$ manifest-dev-tool --version
+Manifest-Tool version 2.0
+```
+
+## pytest
+
+execute `pytest` command to verify no regression was introduced.
+`pytest` will also generate `htmlcov/index.html` that can be opened in a browser for showing test coverage statistics.
+
+## tox
+
+`tox` is an automation tool. Details can be found here:
+https://tox.readthedocs.io/en/latest/
+`tox` helps to automate testing on different python versions.
+
+Execute: `tox` command to test all supported Python environments.
+Execute `tox -e py38` to test only the python3.8 environment.
+
+## wheel creation
+
+```shell
+$ pyenv local 3.7.5
+$ python setup.py bdist_wheel
+$ pyenv local 3.6.9
+$ python setup.py bdist_wheel
+```
+do the same on each platform (Windows, Linux, macOS) per Python
+interpreter.
+
+The resulting wheel packages will be found under `dist` directory.
+
+> Note: all the packages are created automatically by running `tox`
+> command.
+
+## sdist
+
+Source distribution - can be done once as it is platform and Python
+version agnostic.
+
+```shell
+python setup.py sdist
+```
+the resulting archive (`tar.gz`) will be found under `dist` directory
+
+> Note: all the packages are created automatically by running `tox`
+> command.
+
+## Dependent packages versions
+Dependent packages version should be tested with both lower and higher
+bound. Tox tests with new virtual env where all the latest versions will
+be installed.
+When issuing a new release:
+- test lower bound versions - if they are still applicable to latest
+ changes.
+- bump the higher bound versions and test against them.
+
+We must freeze upper bound versions to the version which were tested at
+the release creation time.
+
diff --git a/dev-requirements.txt b/dev-requirements.txt
new file mode 100644
index 0000000..9d71a01
--- /dev/null
+++ b/dev-requirements.txt
@@ -0,0 +1,10 @@
+pytest
+pytest-mock
+pytest-cov
+tox
+tox-pyenv
+pylint
+pycodestyle
+coverage
+wheel
+bandit
\ No newline at end of file
diff --git a/bin/manifest-tool b/dev_init.sh
similarity index 68%
rename from bin/manifest-tool
rename to dev_init.sh
index 01c9787..2fa4855 100755
--- a/bin/manifest-tool
+++ b/dev_init.sh
@@ -1,7 +1,6 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
+#!/bin/bash -ex
# ----------------------------------------------------------------------------
-# Copyright 2016 ARM Limited or its affiliates
+# Copyright 2019 ARM Limited or its affiliates
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -17,14 +16,15 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
-import sys
-import os
-manifesttoolPath = os.path.join(os.path.dirname(os.path.realpath(__file__)),'..')
-sys.path.insert(0,manifesttoolPath)
-from manifesttool import clidriver
-def main():
- return clidriver.main()
-if __name__ == "__main__":
- sys.exit(main())
+if [[ ! -d venv ]]; then
+virtualenv -p python3 venv
+fi
+
+source venv/bin/activate
+
+pip uninstall manifesttool --yes
+pip install --editable .
+
+pip install -r dev-requirements.txt
diff --git a/manifesttool/__init__.py b/manifesttool/__init__.py
index f5916dd..15386d3 100644
--- a/manifesttool/__init__.py
+++ b/manifesttool/__init__.py
@@ -1,6 +1,5 @@
-# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
-# Copyright 2016-2017 ARM Limited or its affiliates
+# Copyright 2019 ARM Limited or its affiliates
#
# SPDX-License-Identifier: Apache-2.0
#
@@ -16,4 +15,5 @@
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
-__version__ = '1.5.2'
+
+__version__ = "2.0.0"
diff --git a/manifesttool/argparser.py b/manifesttool/argparser.py
deleted file mode 100644
index a7ea6da..0000000
--- a/manifesttool/argparser.py
+++ /dev/null
@@ -1,316 +0,0 @@
-# -*- coding: utf-8 -*-
-# ----------------------------------------------------------------------------
-# Copyright 2016-2017 ARM Limited or its affiliates
-#
-# SPDX-License-Identifier: Apache-2.0
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ----------------------------------------------------------------------------
-import sys, argparse, os
-from manifesttool import defaults, __version__
-
-class MainArgumentParser(object):
-
- def __init__(self):
- self.parser = self._make_parser()
-
- def _make_parser(self):
- parser = argparse.ArgumentParser(description = 'Create or transform a manifest.'
- ' Use {} [command] -h for help on each command.'.format(sys.argv[0]))
-
- # Add all top-level commands
- parser.add_argument('-l', '--log-level', choices=['debug','info','warning','exception'], default='info')
- parser.add_argument('--version', action='version', version=__version__,
- help='display the version'
- )
- subparsers = parser.add_subparsers(dest="action")
- subparsers.required = True
- create_parser = subparsers.add_parser('create', help='Create a new manifest')
- parse_parser = subparsers.add_parser('parse', help='Parse an existing manifest')
- verify_parser = subparsers.add_parser('verify', help='Verify an existing manifest')
- cert_parser = subparsers.add_parser('cert', help='Create or examine a certificate')
- init_parser = subparsers.add_parser('init', help='Set default values for manifests',
- description='''Configures default values for manifests.
-
- The manifest init command requires a certificate. If one is not provided, init will guide the user through
- the process of creating a certificate. Currently, the only supported type of created certificate is
- self-signed, which should only be used for testing/development purposes.
-
- When using an existing certificate, the user may supply a script to use in performing signing operations.
- This script is to support the use of exsiting Hardware Security Modules, etc.''')
- sign_parser = subparsers.add_parser('sign', help='Sign an existing manifest',
- description='''Signs an existing manifest with one additional signature. The manifest must first be
- validated, so defaults for validation are extracted from .manifest_tool.json when values are not supplied
- as arguments to the tool''')
- update_parser = subparsers.add_parser('update', help='Work with the Device Management Update service')
-
- # Options for creating a new manifest
- self._addCreateArgs(create_parser)
-
- # Options for parsing an existing manifest
- parse_parser.add_argument('-j','--pretty-json', action='store_true')
- parse_parser.add_argument('-e','--encoding', choices=['der'], default='der',
- help='Decode created manifest using the provided encoding scheme')
- # deprecated as of 2020:
- if sys.version_info[0] == 2:
- parse_parser.add_argument('-i', '--input-file', metavar='FILE',
- help='Specify the input file. stdin by default',
- type=argparse.FileType('rb'), default=sys.stdin)
- elif sys.version_info[0] >= 3:
- parse_parser.add_argument('-i', '--input-file', metavar='FILE',
- help='Specify the input file. stdin by default',
- type=argparse.FileType('rb'), default=sys.stdin.buffer)
- self._add_output_file_arg(parse_parser)
-
- # Options for verifying an existing manifest
- self._addVerifyArgs(verify_parser)
-
- cert_subparsers = cert_parser.add_subparsers(dest="cert_action")
- cert_subparsers.required = True
-
- cert_create_parser = cert_subparsers.add_parser('create',
- help='Create a certificate.\nWARNING: Certificates generated with this tool are self-signed and for testing only.',
- description='Create a certificate.\nWARNING: Certificates generated with this tool are self-signed and for testing only.'
- )
- # cert_read_parser = cert_subparsers.add_parser('read', help='Create a certificate')
-
- cert_create_parser.add_argument('-C','--country', help='Country of the subject', required=False)
- cert_create_parser.add_argument('-S','--state', help='State or province of the subject', required=False)
- cert_create_parser.add_argument('-L','--locality', help='Locality (city or region) of the subject', required=False)
- cert_create_parser.add_argument('-O','--organization', help='Subject organization that will hold the certificate', required=False)
- cert_create_parser.add_argument('-U','--common-name', help='Common name for the subject organization', required=False)
- cert_create_parser.add_argument('-V','--valid-time', help='time for the certificate to be valid, in days, starting now',
- type=int, required=True)
- cert_create_parser.add_argument('-K','--key-output', help='file to store the private key generated for the new certificate',
- type=argparse.FileType('wb'), required=True)
- cert_add_parser = cert_subparsers.add_parser('add',
- help='Add a certificate to the manifest-tool\'s list of certificates for use in manifest-tool verify.',
- description='Adds a certificate to the {} directory.'.format(defaults.certificatePath))
-
- cert_add_parser.add_argument('-c', '--certificate',
- help='DER-encoded certificate to add to the certificate query directory ({})'.format(defaults.certificatePath),
- type=argparse.FileType('rb'), required=True)
-
- self._add_output_file_arg(cert_create_parser)
-
- init_parser.add_argument('-c','--certificate', help='Provide an existing certificate to init',
- type=argparse.FileType('rb'), required=False)
- init_existing_cert_signing = init_parser.add_mutually_exclusive_group(required=False)
- init_existing_cert_signing.add_argument('-k','--private-key',
- help='Provide a private key file for the certificate provided with -c. ' +
- 'This allows the manifest tool to perform manifest signing internally.',
- type=argparse.FileType('rb'))
- init_existing_cert_signing.add_argument('-s','--signing-tool',
- help='Provide a tool that should be used for signing. ' +
- 'This allows signing with existing infrastructure. ' +
- 'The arguments to the tool are: ' +
- '