Skip to content

Commit

Permalink
Merge pull request erlang-lager#101 from basho/adt-format-errors
Browse files Browse the repository at this point in the history
Reject invalid format strings more aggressively
  • Loading branch information
Vagabond committed Dec 12, 2012
2 parents 86c7c62 + ecebfe4 commit 5cfaba3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/lager_format.erl
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,29 @@
format(FmtStr, Args, MaxLen) ->
format(FmtStr, Args, MaxLen, []).

format(FmtStr, Args, MaxLen, Opts) ->
Options = make_options(Opts, #options{}),
Cs = collect(FmtStr, Args),
{Cs2, MaxLen2} = build(Cs, [], MaxLen, Options),
%% count how many terms remain
{Count, StrLen} = lists:foldl(
fun({_C, _As, _F, _Adj, _P, _Pad, _Enc}, {Terms, Chars}) ->
{Terms + 1, Chars};
(_, {Terms, Chars}) ->
{Terms, Chars + 1}
end, {0, 0}, Cs2),
build2(Cs2, Count, MaxLen2 - StrLen).
format(FmtStr, Args, MaxLen, Opts) when is_atom(FmtStr) ->
format(atom_to_list(FmtStr), Args, MaxLen, Opts);
format(FmtStr, Args, MaxLen, Opts) when is_binary(FmtStr) ->
format(binary_to_list(FmtStr), Args, MaxLen, Opts);
format(FmtStr, Args, MaxLen, Opts) when is_list(FmtStr) ->
case lager_stdlib:string_p(FmtStr) of
true ->
Options = make_options(Opts, #options{}),
Cs = collect(FmtStr, Args),
{Cs2, MaxLen2} = build(Cs, [], MaxLen, Options),
%% count how many terms remain
{Count, StrLen} = lists:foldl(
fun({_C, _As, _F, _Adj, _P, _Pad, _Enc}, {Terms, Chars}) ->
{Terms + 1, Chars};
(_, {Terms, Chars}) ->
{Terms, Chars + 1}
end, {0, 0}, Cs2),
build2(Cs2, Count, MaxLen2 - StrLen);
false ->
erlang:error(badarg)
end;
format(_FmtStr, _Args, _MaxLen, _Opts) ->
erlang:error(badarg).

collect([$~|Fmt0], Args0) ->
{C,Fmt1,Args1} = collect_cseq(Fmt0, Args0),
Expand Down
11 changes: 11 additions & 0 deletions src/lager_trunc_io.erl
Original file line number Diff line number Diff line change
Expand Up @@ -721,4 +721,15 @@ depth_limit_test() ->

ok.

print_terms_without_format_string_test() ->
?assertError(badarg, format({hello, world}, [], 50)),
?assertError(badarg, format([{google, bomb}], [], 50)),
?assertError(badarg, format([$h,$e,$l,$l,$o, 3594], [], 50)),
?assertEqual("helloworld", lists:flatten(format([$h,$e,$l,$l,$o, "world"], [], 50))),
?assertEqual("hello", lists:flatten(format(<<"hello">>, [], 50))),
?assertEqual("hello", lists:flatten(format('hello', [], 50))),
?assertError(badarg, format(<<1, 2, 3, 1:7>>, [], 100)),
?assertError(badarg, format(65535, [], 50)),
ok.

-endif.

0 comments on commit 5cfaba3

Please sign in to comment.