By enforcing invariance under S-duality in type IIB string theory compactified on a Calabi-Yau threefold, we derive modular properties of the generating function of BPS degeneracies of D4-D2-D0 black holes in type IIA string theory compactified on the same space. Mathematically, these BPS degeneracies are the generalized Donaldson-Thomas invariants counting coherent sheaves with support on a divisor $cal D$, at the large volume attractor point. For $cal D$ irreducible, this function is closely related to the elliptic genus of the superconformal field theory obtained by wrapping M5-brane on $cal D$ and is therefore known to be modular. Instead, when $cal D$ is the sum of $n$ irreducible divisors ${cal D}_i$, we show that the generating function acquires a modular anomaly. We characterize this anomaly for arbitrary $n$ by providing an explicit expression for a non-holomorphic modular completion in terms of generalized error functions. As a result, the generating function turns out to be a (mixed) mock modular form of depth $n-1$.