Section 1717 fixes a specific unfairness. Contracts are often drafted so that one side — the landlord, the lender, the company — recovers its legal costs if it has to enforce the agreement, while the other side recovers nothing if it wins. Subdivision (a) makes that clause reciprocal: in any action on a contract where the contract specifically provides that attorney's fees incurred to enforce it shall be awarded either to one of the parties or to the prevailing party, the party determined to be prevailing on the contract, whether or not that is the party specified, is entitled to reasonable attorney's fees in addition to other costs.
The subdivision goes further in two ways. A fees provision is construed as applying to the entire contract, unless each party was represented by counsel in the negotiation and execution and that fact is specified in the contract. And the entitlement cannot be waived: fees provided for by the section are not subject to waiver by the parties, and any provision purporting to waive them is void.
Subdivision (b) supplies the machinery. The court, on notice and motion, determines who prevailed on the contract, whether or not the suit reaches final judgment; the prevailing party is the one who recovered greater relief on the contract, and the court may find that no party prevailed. Paragraph (2) contains the rule that surprises litigants: where an action is voluntarily dismissed, or dismissed under a settlement, there is no prevailing party for the purposes of the section. It also treats a defendant who pleaded and deposited a full tender as prevailing where that allegation is found true. The section applies to actions on a contract, so whether your claim is on the contract and whether the clause is engaged are questions to raise with a lawyer early — they change what losing costs.