#!/usr/bin/env bash

#**************************************************************************
#*                                                                        *
#*                                 OCaml                                  *
#*                                                                        *
#*                 Stephen Dolan, University of Cambridge                 *
#*                                                                        *
#*   Copyright 2016 Stephen Dolan.                                        *
#*                                                                        *
#*   All rights reserved.  This file is distributed under the terms of    *
#*   the GNU Lesser General Public License version 2.1, with the          *
#*   special exception on linking described in the file LICENSE.          *
#*                                                                        *
#**************************************************************************

set -o pipefail

[ -z "$*" ] && { echo "Usage: $0 libfoo.a" 1>&2; exit 2; }

nm -A -P "$@" | LC_ALL=C awk '
# ignore caml_foo, camlFoo_bar, _caml_foo, _camlFoo_bar
$2 ~ /^(\.refptr\.)?(_?__emutls_v\.)?(_?caml[_A-Z])/ { next }
# ignore re_foo
$2 ~ /^(\.refptr\.)?(_?re_)/ { next }
# ignore "extern char **environ"
$2 ~ /^(\.refptr\.)?(environ)/ { next }
# ignore symbols pulled in by SHGetKnownFolderPath
$2 ~ /^\.refptr\.FOLDERID_[a-zA-Z]+/ { next }
# ignore local and undefined symbols
$3 ~ /^[a-zU]$/ { next }
# ignore "main", which should be externally linked
$2 ~ /^_?main$/ { next }
$2 ~ /^_?wmain$/ { next }
# for x86 PIC mode
$2 ~ /^__x86.get_pc_thunk./ { next }
# for mingw32
$2 ~ /^.debug_/ { next }
# ignore "__tsan_default_suppressions"
$2 ~ /^___?tsan_default_suppressions$/ { next }
# ignore custom handlers of volatile reads/writes for TSan
$2 ~ /^___?tsan(_unaligned)?_volatile_(read|write)[0-9]+$/ { next }
# print the rest
{ found=1; print $1 " " $2 " " $3 }
# fail if there were any results
END { exit found ? 1 : 0 }
'
exit $?
