We derive a partial differential equation (PDE) representation for the value of financial derivatives with bilateral counterparty risk and funding costs. The model is very general in that the funding rate may be different for lending and borrowing and the mark-to-market value at default can be specified exogenously. The buying back of a party's own bonds is a key part of the delta hedging strategy; we discuss how the cash account of the replication strategy provides sufficient funds for this. First, we assume that the mark-to-market value at default is given by the total value of the derivative, which includes counterparty risk.We find that the resulting pricing PDE becomes nonlinear, except in special cases, when the nonlinear terms vanish and a Feynman-Kac representation of the total value can be obtained. In these cases, the total value of the derivative can be decomposed into the default-free value plus a bilateral credit-valuation and funding adjustment. Second, we assume that the mark-to-market value at default is given by the counterparty-risk-free value of the derivative. This time, the resulting PDE is linear and the corresponding Feynman-Kac representation is used to decompose the total value of the derivative into the default-free value plus bilateral creditvaluation and funding-cost adjustments.Anumerical example shows that the effect on the valuation adjustments of a nonzero funding spread can be significant.