3. Smali Writer API

Contains standard implementations for Smali writers that are able to procude classes, method, fields and annotations.

3.1. Code cache

class smali.writer._ContainsCodeCache

Interface to make sure the code cache is returned via a method.

get_cache() _CodeCache

Returns the current code cache.

Returns:

the code cache

Return type:

_CodeCache

class smali.writer._CodeCache(indent=0)

Simple container class for a code cache.

Parameters:

indent (int, optional) – the indentation level of this code, defaults to 0

add(line: str, start: str = '', end: str = '', custom_indent: int = -1) None

Appends the given line of code at the end of this cache.

Parameters:
  • line (str) – the line to add

  • start (str, optional) – additional prefix, defaults to “”

  • end (str, optional) – additional suffix, defaults to “”

add_comment(comment: str) None

Adds the given comment to the last line

Parameters:

comment (str) – the comment to add

add_to_cache(cache: _ContainsCodeCache) None

Appends the given code cache to the end of this cache.

Parameters:

cache (_CodeCache) – the cache to append

apply_code_cache(clear_caches=False) None

Applies stored caches to this one.

The stored caches will be cleared and removed afterwards.

Parameters:

clear_caches (bool, optional) – whether sub-caches should be applied, defaults to False

clear() None

Clears this cache.

get_code(clear_cache=False) str

Returns the Smali-Code

Parameters:

clear_cache (bool, optional) – whether cached objects should be applied first, defaults to False

Returns:

the source code as utf-8 string

Return type:

str

property indent: int

Returns the indentation level

Returns:

the indent amount

Return type:

int

peek() _ContainsCodeCache

Returns the last element of this cache

Returns:

the last element that contains itself a _CodeCache

Return type:

_ContainsCodeCache

pop_comments() list

Clears the comment cache and returns all elements.

Returns:

the comments that have been stored.

Return type:

list

3.2. Writer implementation

smali.writer.SmaliWriter

alias of _SmaliClassWriter

class smali.writer._SmaliClassWriter(reader: SmaliReader = None, indent=0)

Public standard implementation of a Smali Source-Code writer.

property code: str

Returns the source code as an utf-8 string

Returns:

the complete source code

Return type:

str

reset() None

Resets the writer.

Use this method before calling #visit() to ensure the internal buffer is cleared.